text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [honeycode](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonhoneycode.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Honeycode extends PolicyStatement { public servicePrefix = 'honeycode'; /** * Statement provider for service [honeycode](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonhoneycode.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 approve a team association request for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team-association.html#approve-team-association */ public toApproveTeamAssociation() { return this.to('ApproveTeamAssociation'); } /** * Grants permission to create new rows in a table * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_BatchCreateTableRows.html */ public toBatchCreateTableRows() { return this.to('BatchCreateTableRows'); } /** * Grants permission to delete rows from a table * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_BatchDeleteTableRows.html */ public toBatchDeleteTableRows() { return this.to('BatchDeleteTableRows'); } /** * Grants permission to update rows in a table * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_BatchUpdateTableRows.html */ public toBatchUpdateTableRows() { return this.to('BatchUpdateTableRows'); } /** * Grants permission to upsert rows in a table * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_BatchUpsertTableRows.html */ public toBatchUpsertTableRows() { return this.to('BatchUpsertTableRows'); } /** * Grants permission to create a new Amazon Honeycode team for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team.html#create-team */ public toCreateTeam() { return this.to('CreateTeam'); } /** * Grants permission to create a new tenant within Amazon Honeycode for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/tenant.html#create-tenant */ public toCreateTenant() { return this.to('CreateTenant'); } /** * Grants permission to remove groups from an Amazon Honeycode team for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/group.html#deregister-groups */ public toDeregisterGroups() { return this.to('DeregisterGroups'); } /** * Grants permission to get details about a table data import job * * Access Level: Read * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_DescribeTableDataImportJob.html */ public toDescribeTableDataImportJob() { return this.to('DescribeTableDataImportJob'); } /** * Grants permission to get details about Amazon Honeycode teams for your AWS Account * * Access Level: Read * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team.html#describe-team */ public toDescribeTeam() { return this.to('DescribeTeam'); } /** * Grants permission to load the data from a screen * * Access Level: Read * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_GetScreenData.html */ public toGetScreenData() { return this.to('GetScreenData'); } /** * Grants permission to invoke a screen automation * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_InvokeScreenAutomation.html */ public toInvokeScreenAutomation() { return this.to('InvokeScreenAutomation'); } /** * Grants permission to list all Amazon Honeycode domains and their verification status for your AWS Account * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/domain.html#list-domains */ public toListDomains() { return this.to('ListDomains'); } /** * Grants permission to list all groups in an Amazon Honeycode team for your AWS Account * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/group.html#list-groups */ public toListGroups() { return this.to('ListGroups'); } /** * Grants permission to list the columns in a table * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_ListTableColumns.html */ public toListTableColumns() { return this.to('ListTableColumns'); } /** * Grants permission to list the rows in a table * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_ListTableRows.html */ public toListTableRows() { return this.to('ListTableRows'); } /** * Grants permission to list the tables in a workbook * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_ListTables.html */ public toListTables() { return this.to('ListTables'); } /** * Grants permission to list all pending and approved team associations with your AWS Account * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team-association.html#list-team-associations */ public toListTeamAssociations() { return this.to('ListTeamAssociations'); } /** * Grants permission to list all tenants of Amazon Honeycode for your AWS Account * * Access Level: List * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/tenant.html#list-tenants */ public toListTenants() { return this.to('ListTenants'); } /** * Grants permission to query the rows of a table using a filter * * Access Level: Read * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_QueryTableRows.html */ public toQueryTableRows() { return this.to('QueryTableRows'); } /** * Grants permission to request verification of the Amazon Honeycode domains for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/domain.html#register-domain-for-verification */ public toRegisterDomainForVerification() { return this.to('RegisterDomainForVerification'); } /** * Grants permission to add groups to an Amazon Honeycode team for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/group.html#register-groups */ public toRegisterGroups() { return this.to('RegisterGroups'); } /** * Grants permission to reject a team association request for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team-association.html#reject-team-association */ public toRejectTeamAssociation() { return this.to('RejectTeamAssociation'); } /** * Grants permission to restart verification of the Amazon Honeycode domains for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/domain.html#restart-domain-verification */ public toRestartDomainVerification() { return this.to('RestartDomainVerification'); } /** * Grants permission to start a table data import job * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/API_StartTableDataImportJob.html */ public toStartTableDataImportJob() { return this.to('StartTableDataImportJob'); } /** * Grants permission to update an Amazon Honeycode team for your AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/team.html#update-team */ public toUpdateTeam() { return this.to('UpdateTeam'); } protected accessLevelList: AccessLevelList = { "Write": [ "ApproveTeamAssociation", "BatchCreateTableRows", "BatchDeleteTableRows", "BatchUpdateTableRows", "BatchUpsertTableRows", "CreateTeam", "CreateTenant", "DeregisterGroups", "InvokeScreenAutomation", "RegisterDomainForVerification", "RegisterGroups", "RejectTeamAssociation", "RestartDomainVerification", "StartTableDataImportJob", "UpdateTeam" ], "Read": [ "DescribeTableDataImportJob", "DescribeTeam", "GetScreenData", "QueryTableRows" ], "List": [ "ListDomains", "ListGroups", "ListTableColumns", "ListTableRows", "ListTables", "ListTeamAssociations", "ListTenants" ] }; /** * Adds a resource of type workbook to the statement * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/resource-workbook.html * * @param workbookId - Identifier for the workbookId. * @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 onWorkbook(workbookId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:honeycode:${Region}:${Account}:workbook:workbook/${WorkbookId}'; arn = arn.replace('${WorkbookId}', workbookId); 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 table to the statement * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/resource-table.html * * @param workbookId - Identifier for the workbookId. * @param tableId - Identifier for the tableId. * @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 onTable(workbookId: string, tableId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:honeycode:${Region}:${Account}:table:workbook/${WorkbookId}/table/${TableId}'; arn = arn.replace('${WorkbookId}', workbookId); arn = arn.replace('${TableId}', tableId); 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 screen to the statement * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/resource-screen.html * * @param workbookId - Identifier for the workbookId. * @param appId - Identifier for the appId. * @param screenId - Identifier for the screenId. * @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 onScreen(workbookId: string, appId: string, screenId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:honeycode:${Region}:${Account}:screen:workbook/${WorkbookId}/app/${AppId}/screen/${ScreenId}'; arn = arn.replace('${WorkbookId}', workbookId); arn = arn.replace('${AppId}', appId); arn = arn.replace('${ScreenId}', screenId); 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 screen-automation to the statement * * https://docs.aws.amazon.com/honeycode/latest/UserGuide/resource-screen-automation.html * * @param workbookId - Identifier for the workbookId. * @param appId - Identifier for the appId. * @param screenId - Identifier for the screenId. * @param automationId - Identifier for the automationId. * @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 onScreenAutomation(workbookId: string, appId: string, screenId: string, automationId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:honeycode:${Region}:${Account}:screen-automation:workbook/${WorkbookId}/app/${AppId}/screen/${ScreenId}/automation/${AutomationId}'; arn = arn.replace('${WorkbookId}', workbookId); arn = arn.replace('${AppId}', appId); arn = arn.replace('${ScreenId}', screenId); arn = arn.replace('${AutomationId}', automationId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, Directive, ElementRef, EventEmitter, Injector, Input, OnChanges, OnDestroy, OnInit, Optional, Output, Renderer2, SimpleChanges, TemplateRef, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core'; import { Direction, Directionality } from '@angular/cdk/bidi'; import { CdkConnectedOverlay, CdkOverlayOrigin, ConnectedOverlayPositionChange, ConnectionPositionPair } from '@angular/cdk/overlay'; import { Subject, Subscription } from 'rxjs'; import { DEFAULT_POPOVER_POSITIONS, getPlacementName, popoverMotion, PopoverPlacement, POSITION_MAP, PropertyMapping } from '@shared/components/popover.models'; import { distinctUntilChanged, takeUntil } from 'rxjs/operators'; import { isNotEmptyStr, onParentScrollOrWindowResize } from '@core/utils'; export type TbPopoverTrigger = 'click' | 'focus' | 'hover' | null; @Directive({ selector: '[tb-popover]', exportAs: 'tbPopover', host: { '[class.tb-popover-open]': 'visible' } }) export class TbPopoverDirective implements OnChanges, OnDestroy, AfterViewInit { // tslint:disable:no-input-rename @Input('tbPopoverContent') content?: string | TemplateRef<void>; @Input('tbPopoverTrigger') trigger?: TbPopoverTrigger = 'hover'; @Input('tbPopoverPlacement') placement?: string | string[] = 'top'; @Input('tbPopoverOrigin') origin?: ElementRef<HTMLElement>; @Input('tbPopoverVisible') visible?: boolean; @Input('tbPopoverMouseEnterDelay') mouseEnterDelay?: number; @Input('tbPopoverMouseLeaveDelay') mouseLeaveDelay?: number; @Input('tbPopoverOverlayClassName') overlayClassName?: string; @Input('tbPopoverOverlayStyle') overlayStyle?: { [klass: string]: any }; @Input() tbPopoverBackdrop = false; // tslint:disable-next-line:no-output-rename @Output('tbPopoverVisibleChange') readonly visibleChange = new EventEmitter<boolean>(); componentFactory: ComponentFactory<TbPopoverComponent> = this.resolver.resolveComponentFactory(TbPopoverComponent); component?: TbPopoverComponent; private readonly destroy$ = new Subject<void>(); private readonly triggerDisposables: Array<() => void> = []; private delayTimer?; private internalVisible = false; constructor( private elementRef: ElementRef, private hostView: ViewContainerRef, private resolver: ComponentFactoryResolver, private renderer: Renderer2 ) {} ngOnChanges(changes: SimpleChanges): void { const { trigger } = changes; if (trigger && !trigger.isFirstChange()) { this.registerTriggers(); } if (this.component) { this.updatePropertiesByChanges(changes); } } ngAfterViewInit(): void { this.registerTriggers(); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); this.clearTogglingTimer(); this.removeTriggerListeners(); } show(): void { if (!this.component) { this.createComponent(); } this.component?.show(); } hide(): void { this.component?.hide(); } updatePosition(): void { if (this.component) { this.component.updatePosition(); } } private createComponent(): void { const componentRef = this.hostView.createComponent(this.componentFactory); this.component = componentRef.instance; this.renderer.removeChild( this.renderer.parentNode(this.elementRef.nativeElement), componentRef.location.nativeElement ); this.component.setOverlayOrigin({ elementRef: this.origin || this.elementRef }); this.initProperties(); this.component.tbVisibleChange .pipe(distinctUntilChanged(), takeUntil(this.destroy$)) .subscribe((visible: boolean) => { this.internalVisible = visible; this.visibleChange.emit(visible); }); } private registerTriggers(): void { // When the method gets invoked, all properties has been synced to the dynamic component. // After removing the old API, we can just check the directive's own `nzTrigger`. const el = this.elementRef.nativeElement; const trigger = this.trigger; this.removeTriggerListeners(); if (trigger === 'hover') { let overlayElement: HTMLElement; this.triggerDisposables.push( this.renderer.listen(el, 'mouseenter', () => { this.delayEnterLeave(true, true, this.mouseEnterDelay); }) ); this.triggerDisposables.push( this.renderer.listen(el, 'mouseleave', () => { this.delayEnterLeave(true, false, this.mouseLeaveDelay); if (this.component?.overlay.overlayRef && !overlayElement) { overlayElement = this.component.overlay.overlayRef.overlayElement; this.triggerDisposables.push( this.renderer.listen(overlayElement, 'mouseenter', () => { this.delayEnterLeave(false, true, this.mouseEnterDelay); }) ); this.triggerDisposables.push( this.renderer.listen(overlayElement, 'mouseleave', () => { this.delayEnterLeave(false, false, this.mouseLeaveDelay); }) ); } }) ); } else if (trigger === 'focus') { this.triggerDisposables.push(this.renderer.listen(el, 'focusin', () => this.show())); this.triggerDisposables.push(this.renderer.listen(el, 'focusout', () => this.hide())); } else if (trigger === 'click') { this.triggerDisposables.push( this.renderer.listen(el, 'click', (e: MouseEvent) => { e.preventDefault(); if (this.component?.visible) { this.hide(); } else { this.show(); } }) ); } // Else do nothing because user wants to control the visibility programmatically. } private updatePropertiesByChanges(changes: SimpleChanges): void { this.updatePropertiesByKeys(Object.keys(changes)); } private updatePropertiesByKeys(keys?: string[]): void { const mappingProperties: PropertyMapping = { // common mappings content: ['tbContent', () => this.content], trigger: ['tbTrigger', () => this.trigger], placement: ['tbPlacement', () => this.placement], visible: ['tbVisible', () => this.visible], mouseEnterDelay: ['tbMouseEnterDelay', () => this.mouseEnterDelay], mouseLeaveDelay: ['tbMouseLeaveDelay', () => this.mouseLeaveDelay], overlayClassName: ['tbOverlayClassName', () => this.overlayClassName], overlayStyle: ['tbOverlayStyle', () => this.overlayStyle], tbPopoverBackdrop: ['tbBackdrop', () => this.tbPopoverBackdrop] }; (keys || Object.keys(mappingProperties).filter(key => !key.startsWith('directive'))).forEach( (property: any) => { if (mappingProperties[property]) { const [name, valueFn] = mappingProperties[property]; this.updateComponentValue(name, valueFn()); } } ); this.component?.updateByDirective(); } private initProperties(): void { this.updatePropertiesByKeys(); } private updateComponentValue(key: string, value: any): void { if (typeof value !== 'undefined') { // @ts-ignore this.component[key] = value; } } private delayEnterLeave(isOrigin: boolean, isEnter: boolean, delay: number = -1): void { if (this.delayTimer) { this.clearTogglingTimer(); } else if (delay > 0) { this.delayTimer = setTimeout(() => { this.delayTimer = undefined; isEnter ? this.show() : this.hide(); }, delay * 1000); } else { // `isOrigin` is used due to the tooltip will not hide immediately // (may caused by the fade-out animation). isEnter && isOrigin ? this.show() : this.hide(); } } private removeTriggerListeners(): void { this.triggerDisposables.forEach(dispose => dispose()); this.triggerDisposables.length = 0; } private clearTogglingTimer(): void { if (this.delayTimer) { clearTimeout(this.delayTimer); this.delayTimer = undefined; } } } @Component({ selector: 'tb-popover', exportAs: 'tbPopoverComponent', animations: [popoverMotion], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, styleUrls: ['./popover.component.scss'], template: ` <ng-template #overlay="cdkConnectedOverlay" cdkConnectedOverlay [cdkConnectedOverlayHasBackdrop]="hasBackdrop" [cdkConnectedOverlayOrigin]="origin" [cdkConnectedOverlayPositions]="positions" [cdkConnectedOverlayOpen]="visible" [cdkConnectedOverlayPush]="true" (overlayOutsideClick)="onClickOutside($event)" (detach)="hide()" (positionChange)="onPositionChange($event)" > <div #popoverRoot [@popoverMotion]="tbAnimationState" (@popoverMotion.done)="animationDone()"> <div class="tb-popover" [class.tb-popover-rtl]="dir === 'rtl'" [ngClass]="classMap" [ngStyle]="tbOverlayStyle" > <div class="tb-popover-content"> <div class="tb-popover-arrow"> <span class="tb-popover-arrow-content"></span> </div> <div class="tb-popover-inner" [ngStyle]="tbPopoverInnerStyle" role="tooltip"> <div class="tb-popover-close-button" (click)="closeButtonClick($event)">×</div> <div style="width: 100%; height: 100%;"> <div class="tb-popover-inner-content"> <ng-container *ngIf="tbContent"> <ng-container *tbStringTemplateOutlet="tbContent">{{ tbContent }}</ng-container> </ng-container> <ng-container *ngIf="tbComponentFactory" [tbComponentOutlet]="tbComponentFactory" [tbComponentInjector]="tbComponentInjector" [tbComponentOutletContext]="tbComponentContext" (componentChange)="onComponentChange($event)" [tbComponentStyle]="tbComponentStyle"> </ng-container> </div> </div> </div> </div> </div> </div> </ng-template> ` }) export class TbPopoverComponent implements OnDestroy, OnInit { @ViewChild('overlay', { static: false }) overlay!: CdkConnectedOverlay; @ViewChild('popoverRoot', { static: false }) popoverRoot!: ElementRef<HTMLElement>; tbContent: string | TemplateRef<void> | null = null; tbComponentFactory: ComponentFactory<any> | null = null; tbComponentRef: ComponentRef<any> | null = null; tbComponentContext: any; tbComponentInjector: Injector | null = null; tbComponentStyle: { [klass: string]: any } = {}; tbOverlayClassName!: string; tbOverlayStyle: { [klass: string]: any } = {}; tbPopoverInnerStyle: { [klass: string]: any } = {}; tbBackdrop = false; tbMouseEnterDelay?: number; tbMouseLeaveDelay?: number; tbHideOnClickOutside = true; tbAnimationState = 'active'; tbVisibleChange = new Subject<boolean>(); tbAnimationDone = new Subject<void>(); tbComponentChange = new Subject<ComponentRef<any>>(); tbDestroy = new Subject<void>(); set tbVisible(value: boolean) { const visible = value; if (this.visible !== visible) { this.visible = visible; this.tbVisibleChange.next(visible); } } get tbVisible(): boolean { return this.visible; } visible = false; set tbHidden(value: boolean) { const hidden = value; if (this.hidden !== hidden) { this.hidden = hidden; if (this.hidden) { this.renderer.setStyle(this.popoverRoot.nativeElement, 'width', this.popoverRoot.nativeElement.offsetWidth + 'px'); this.renderer.setStyle(this.popoverRoot.nativeElement, 'height', this.popoverRoot.nativeElement.offsetHeight + 'px'); } else { setTimeout(() => { this.renderer.removeStyle(this.popoverRoot.nativeElement, 'width'); this.renderer.removeStyle(this.popoverRoot.nativeElement, 'height'); }); } this.updateStyles(); this.cdr.markForCheck(); } } get tbHidden(): boolean { return this.hidden; } hidden = false; lastIsIntersecting = true; set tbTrigger(value: TbPopoverTrigger) { this.trigger = value; } get tbTrigger(): TbPopoverTrigger { return this.trigger; } protected trigger: TbPopoverTrigger = 'hover'; set tbPlacement(value: PopoverPlacement | PopoverPlacement[]) { if (typeof value === 'string') { this.positions = [POSITION_MAP[value], ...DEFAULT_POPOVER_POSITIONS]; } else { const preferredPosition = value.map(placement => POSITION_MAP[placement]); this.positions = [...preferredPosition, ...DEFAULT_POPOVER_POSITIONS]; } } get hasBackdrop(): boolean { return this.tbTrigger === 'click' ? this.tbBackdrop : false; } preferredPlacement: PopoverPlacement = 'top'; origin!: CdkOverlayOrigin; public dir: Direction = 'ltr'; classMap: { [klass: string]: any } = {}; positions: ConnectionPositionPair[] = [...DEFAULT_POPOVER_POSITIONS]; private parentScrollSubscription: Subscription = null; private intersectionObserver = new IntersectionObserver((entries) => { if (this.lastIsIntersecting !== entries[0].isIntersecting) { this.lastIsIntersecting = entries[0].isIntersecting; this.updateStyles(); this.cdr.markForCheck(); } }, {threshold: [0.5]}); constructor( public cdr: ChangeDetectorRef, private renderer: Renderer2, @Optional() private directionality: Directionality ) {} ngOnInit(): void { this.directionality.change?.pipe(takeUntil(this.tbDestroy)).subscribe((direction: Direction) => { this.dir = direction; this.cdr.detectChanges(); }); this.dir = this.directionality.value; } ngOnDestroy(): void { if (this.parentScrollSubscription) { this.parentScrollSubscription.unsubscribe(); this.parentScrollSubscription = null; } if (this.origin) { const el = this.origin.elementRef.nativeElement; this.intersectionObserver.unobserve(el); } this.intersectionObserver.disconnect(); this.intersectionObserver = null; this.tbVisibleChange.complete(); this.tbAnimationDone.complete(); this.tbDestroy.next(); this.tbDestroy.complete(); } closeButtonClick($event: Event) { if ($event) { $event.preventDefault(); $event.stopPropagation(); } this.hide(); } show(): void { if (this.tbVisible) { return; } if (!this.isEmpty()) { this.tbVisible = true; this.tbVisibleChange.next(true); this.cdr.detectChanges(); } if (this.origin && this.overlay && this.overlay.overlayRef) { if (this.overlay.overlayRef.getDirection() === 'rtl') { this.overlay.overlayRef.setDirection('ltr'); } const el = this.origin.elementRef.nativeElement; this.parentScrollSubscription = onParentScrollOrWindowResize(el).subscribe(() => { this.overlay.overlayRef.updatePosition(); }); this.intersectionObserver.observe(el); } } hide(): void { if (!this.tbVisible) { return; } if (this.parentScrollSubscription) { this.parentScrollSubscription.unsubscribe(); this.parentScrollSubscription = null; } if (this.origin) { const el = this.origin.elementRef.nativeElement; this.intersectionObserver.unobserve(el); } this.tbVisible = false; this.tbVisibleChange.next(false); this.cdr.detectChanges(); } updateByDirective(): void { this.updateStyles(); this.cdr.detectChanges(); Promise.resolve().then(() => { this.updatePosition(); this.updateVisibilityByContent(); }); } updatePosition(): void { if (this.origin && this.overlay && this.overlay.overlayRef) { this.overlay.overlayRef.updatePosition(); } } onPositionChange(position: ConnectedOverlayPositionChange): void { this.preferredPlacement = getPlacementName(position); this.updateStyles(); this.cdr.detectChanges(); } updateStyles(): void { this.classMap = { [`tb-popover-placement-${this.preferredPlacement}`]: true, ['tb-popover-hidden']: this.tbHidden || !this.lastIsIntersecting }; if (this.tbOverlayClassName) { this.classMap[this.tbOverlayClassName] = true; } } setOverlayOrigin(origin: CdkOverlayOrigin): void { this.origin = origin; this.cdr.markForCheck(); } onClickOutside(event: MouseEvent): void { if (this.tbHideOnClickOutside && !this.origin.elementRef.nativeElement.contains(event.target) && this.tbTrigger !== null) { this.hide(); } } onComponentChange(component: ComponentRef<any>) { this.tbComponentRef = component; this.tbComponentChange.next(component); } animationDone() { this.tbAnimationDone.next(); } private updateVisibilityByContent(): void { if (this.isEmpty()) { this.hide(); } } private isEmpty(): boolean { return (this.tbComponentFactory instanceof ComponentFactory || this.tbContent instanceof TemplateRef) ? false : !isNotEmptyStr(this.tbContent); } }
the_stack
import type { ElementReport, ElementType, ElementTypes, VisibleElement, } from "../shared/hints"; import { isModifierKey, keyboardEventToKeypress, KeyboardMapping, KeyboardModeWorker, KeyTranslations, normalizeKeypress, } from "../shared/keyboard"; import { addEventListener, addListener, Box, CONTAINER_ID, decode, extractText, fireAndForget, getLabels, getTextRects, getViewport, LAST_NON_WHITESPACE, log, NON_WHITESPACE, Resets, walkTextNodes, } from "../shared/main"; import type { FromBackground, FromWorker, ToBackground, } from "../shared/messages"; import { TimeTracker } from "../shared/perf"; import { selectorString, tweakable, unsignedInt } from "../shared/tweakable"; import { FrameMessage } from "./decoders"; import ElementManager from "./ElementManager"; type CurrentElements = { elements: Array<VisibleElement>; frames: Array<HTMLFrameElement | HTMLIFrameElement>; viewports: Array<Box>; types: ElementTypes; indexes: Array<number>; words: Array<string>; waitId: WaitId; }; type WaitId = | { tag: "NotWaiting"; } | { tag: "RequestAnimationFrame"; id: number; } | { tag: "RequestIdleCallback"; id: IdleCallbackID; }; export const t = { // How long a copied element should be selected. FLASH_COPIED_ELEMENT_DURATION: unsignedInt(200), // ms // Elements that look bad when inverted. FLASH_COPIED_ELEMENT_NO_INVERT_SELECTOR: selectorString( "img, audio, video, object, embed, iframe, frame, input, textarea, select, progress, meter, canvas" ), HINTS_REFRESH_IDLE_CALLBACK_TIMEOUT: unsignedInt(100), // ms }; export const tMeta = tweakable("Worker", t); export default class WorkerProgram { isPinned = true; keyboardShortcuts: Array<KeyboardMapping> = []; keyboardMode: KeyboardModeWorker = "Normal"; keyTranslations: KeyTranslations = {}; current: CurrentElements | undefined = undefined; oneTimeWindowMessageToken: string | undefined = undefined; mac = false; suppressNextKeyup: { key: string; code: string } | undefined = undefined; resets = new Resets(); elementManager = new ElementManager({ onMutation: this.onMutation.bind(this), }); async start(): Promise<void> { this.resets.add( addListener( browser.runtime.onMessage, this.onMessage.bind(this), "WorkerProgram#onMessage" ), addEventListener( window, "keydown", this.onKeydown.bind(this), "WorkerProgram#onKeydown", { passive: false } ), addEventListener( window, "keyup", this.onKeyup.bind(this), "WorkerProgram#onKeyup", { passive: false } ), addEventListener( window, "message", this.onWindowMessage.bind(this), "WorkerProgram#onWindowMessage" ), addEventListener( window, "pagehide", this.onPageHide.bind(this), "WorkerProgram#onPageHide" ), addEventListener( window, "pageshow", this.onPageShow.bind(this), "WorkerProgram#onPageShow" ) ); await this.elementManager.start(); this.markTutorial(); // See `RendererProgram#start`. try { await browser.runtime.sendMessage( wrapMessage({ type: "WorkerScriptAdded" }) ); } catch { return; } browser.runtime.connect().onDisconnect.addListener(() => { this.stop(); }); } stop(): void { log("log", "WorkerProgram#stop"); this.resets.reset(); this.elementManager.stop(); this.oneTimeWindowMessageToken = undefined; this.suppressNextKeyup = undefined; this.clearCurrent(); } sendMessage(message: FromWorker): void { log("log", "WorkerProgram#sendMessage", message.type, message); fireAndForget( browser.runtime.sendMessage(wrapMessage(message)).then(() => undefined), "WorkerProgram#sendMessage", message ); } onMessage(wrappedMessage: FromBackground): void { // See `RendererProgram#onMessage`. if (wrappedMessage.type === "FirefoxWorkaround") { this.sendMessage({ type: "WorkerScriptAdded" }); return; } if (wrappedMessage.type !== "ToWorker") { return; } const { message } = wrappedMessage; log("log", "WorkerProgram#onMessage", message.type, message); switch (message.type) { case "StateSync": log.level = message.logLevel; this.isPinned = message.isPinned; this.keyboardShortcuts = message.keyboardShortcuts; this.keyboardMode = message.keyboardMode; this.keyTranslations = message.keyTranslations; this.oneTimeWindowMessageToken = message.oneTimeWindowMessageToken; this.mac = message.mac; if (message.clearElements) { this.clearCurrent(); } break; case "StartFindElements": { const run = (types: ElementTypes): void => { const { oneTimeWindowMessageToken } = this; if (oneTimeWindowMessageToken === undefined) { log("error", "missing oneTimeWindowMessageToken", message); return; } const viewport = getViewport(); this.reportVisibleElements( types, [viewport], oneTimeWindowMessageToken ); }; if (this.current === undefined) { run(message.types); } else { this.current.types = message.types; switch (this.current.waitId.tag) { case "NotWaiting": { const id1 = requestAnimationFrame(() => { if (this.current !== undefined) { const id2 = requestIdleCallback( () => { if (this.current !== undefined) { this.current.waitId = { tag: "NotWaiting" }; run(this.current.types); } }, { timeout: t.HINTS_REFRESH_IDLE_CALLBACK_TIMEOUT.value } ); this.current.waitId = { tag: "RequestIdleCallback", id: id2 }; } }); this.current.waitId = { tag: "RequestAnimationFrame", id: id1 }; break; } case "RequestAnimationFrame": case "RequestIdleCallback": break; } } break; } case "UpdateElements": { const { current, oneTimeWindowMessageToken } = this; if (current === undefined) { return; } current.viewports = [getViewport()]; this.updateVisibleElements({ current, oneTimeWindowMessageToken, }); break; } case "GetTextRects": { const { current } = this; if (current === undefined) { return; } const { indexes, words } = message; current.indexes = indexes; current.words = words; const elements = current.elements.filter((_elementData, index) => indexes.includes(index) ); const wordsSet = new Set(words); const rects = elements.flatMap((elementData) => getTextRectsHelper({ element: elementData.element, type: elementData.type, viewports: current.viewports, words: wordsSet, }) ); this.sendMessage({ type: "ReportTextRects", rects, }); break; } case "FocusElement": { const elementData = this.getElement(message.index); if (elementData === undefined) { log("error", "FocusElement: Missing element", message, this.current); return; } const { element } = elementData; const activeElement = this.elementManager.getActiveElement(document); const textInputIsFocused = activeElement !== undefined && isTextInput(activeElement); // Allow opening links in new tabs without losing focus from a text // input. if (!textInputIsFocused) { element.focus(); } break; } case "ClickElement": { const elementData = this.getElement(message.index); if (elementData === undefined) { log("error", "ClickElement: Missing element", message, this.current); return; } log("log", "WorkerProgram: ClickElement", elementData); const { element } = elementData; const defaultPrevented = this.clickElement(element); if ( !defaultPrevented && elementData.type === "link" && element instanceof HTMLAnchorElement && !isInternalHashLink(element) ) { // I think it’s fine to send this even if the link opened in a new tab. this.sendMessage({ type: "ClickedLinkNavigatingToOtherPage" }); } break; } case "SelectElement": { const elementData = this.getElement(message.index); if (elementData === undefined) { log("error", "SelectElement: Missing element", message, this.current); return; } log("log", "WorkerProgram: SelectElement", elementData); const { element } = elementData; if ( element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ) { // Focus and, if possible, select the text inside. There are two cases // here: "Text input" (`<textarea>`, `<input type="text">`, `<input // type="search">`, `<input type="unknown">`, etc) style elements // technically only need `.select()`, but it doesn't hurt calling // `.focus()` first. For all other types (`<input type="checkbox">`, // `<input type="color">`, etc) `.select()` seems to be a no-op, so // `.focus()` is strictly needed but calling `.select()` also doesn't // hurt. element.focus(); element.select(); } else if ( // Text inside `<button>` elements can be selected and copied just // fine in Chrome, but not in Firefox. In Firefox, // `document.elementFromPoint(x, y)` returns the `<button>` for // elements nested inside, causing them not to get hints either. (BROWSER === "firefox" && element instanceof HTMLButtonElement) || // `<select>` elements _can_ be selected, but you seem to get the // empty string when trying to copy them. element instanceof HTMLSelectElement || // Frame elements can be selected in Chrome, but that just looks // weird. The reason to focus a frame element is to allow the arrow // keys to scroll them. element instanceof HTMLIFrameElement || element instanceof HTMLFrameElement ) { element.focus(); } else { // Focus the element, even if it isn't usually focusable. if (element !== this.elementManager.getActiveElement(document)) { focusElement(element); } // Try to select the text of the element, or the element itself. const selection = window.getSelection(); if (selection !== null) { // Firefox won’t select text inside a ShadowRoot without this timeout. setTimeout(() => { const range = selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); }, 0); } } break; } case "CopyElement": { const elementData = this.getElement(message.index); if (elementData === undefined) { log("error", "CopyElement: Missing element", message, this.current); return; } log("log", "WorkerProgram: CopyElement", elementData); const { element } = elementData; const text: string = element instanceof HTMLAnchorElement ? element.href : element instanceof HTMLImageElement || element instanceof HTMLMediaElement ? element.currentSrc : element instanceof HTMLObjectElement ? element.data : element instanceof HTMLEmbedElement || element instanceof HTMLIFrameElement || element instanceof HTMLFrameElement ? element.src : element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement ? element.value : element instanceof HTMLProgressElement || element instanceof HTMLMeterElement ? element.value.toString() : element instanceof HTMLCanvasElement ? element.toDataURL() : element instanceof HTMLPreElement ? extractText(element) : // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions normalizeWhitespace(extractText(element)) || element.outerHTML; fireAndForget( navigator.clipboard.writeText(text), "WorkerProgram#onMessage->CopyElement->clipboard.writeText", message, text ); flashElement(element); break; } // Used instead of `browser.tabs.create` in Chrome, to have the opened tab // end up in the same position as if you'd clicked a link with the mouse. // This technique does not seem to work in Firefox, but it's not needed // there anyway (see background/Program.ts). case "OpenNewTab": { const { url, foreground } = message; const link = document.createElement("a"); link.href = url; link.dispatchEvent( new MouseEvent("click", { ctrlKey: true, metaKey: true, shiftKey: foreground, }) ); break; } case "Escape": { const activeElement = this.elementManager.getActiveElement(document); if (activeElement !== undefined) { activeElement.blur(); } const selection = window.getSelection(); if (selection !== null) { selection.removeAllRanges(); } break; } case "ReverseSelection": { const selection = window.getSelection(); if (selection !== null) { reverseSelection(selection); } break; } } } onWindowMessage(event: MessageEvent): void { const { oneTimeWindowMessageToken } = this; if ( oneTimeWindowMessageToken !== undefined && typeof event.data === "object" && event.data !== null && !Array.isArray(event.data) && (event.data as Record<string, unknown>).token === oneTimeWindowMessageToken && typeof (event.data as Record<string, unknown>).type === "string" ) { let message = undefined; try { message = decode(FrameMessage, event.data); } catch (error) { log( "warn", "Ignoring bad window message", oneTimeWindowMessageToken, event, error ); return; } this.oneTimeWindowMessageToken = undefined; log("log", "WorkerProgram#onWindowMessage", message); switch (message.type) { case "FindElements": this.sendMessage({ type: "ReportVisibleFrame" }); this.reportVisibleElements( message.types, message.viewports, oneTimeWindowMessageToken ); break; case "UpdateElements": { const { current } = this; if (current === undefined) { return; } current.viewports = message.viewports; this.updateVisibleElements({ current, oneTimeWindowMessageToken, }); break; } } } } // This is run in the capture phase of the keydown event, overriding any site // shortcuts. The initial idea was to run in the bubble phase (mostly) and let // sites use `event.preventDefault()` to override the extension shortcuts // (just like any other browser shortcut). However, duckduckgo.com has "j/k" // shortcuts for navigation, but don't check for the alt key and don't call // `event.preventDefault()`, making it impossible to use alt-j as an extension // shortcut without causing side-effects. This feels like a common thing, so // (at least for now) the extension shortcuts always do their thing (making it // impossible to trigger a site shortcut using the same keys). onKeydown(event: KeyboardEvent): void { if (!event.isTrusted) { log("log", "WorkerProgram#onKeydown", "ignoring untrusted event", event); return; } const keypress = normalizeKeypress({ keypress: keyboardEventToKeypress(event), keyTranslations: this.keyTranslations, }); const match = this.keyboardShortcuts.find((mapping) => { const { shortcut } = mapping; return ( keypress.key === shortcut.key && keypress.alt === shortcut.alt && keypress.cmd === shortcut.cmd && keypress.ctrl === shortcut.ctrl && (keypress.shift === undefined || keypress.shift === shortcut.shift) ); }); const suppress = // If we matched one of our keyboard shortcuts, always suppress. match !== undefined || // Just after activating a hint, suppress everything for a short while. this.keyboardMode === "PreventOverTyping" || // When capturing keypresses in the Options UI, always suppress. this.keyboardMode === "Capture" || // Allow ctrl and cmd system shortcuts in hints mode (but always suppress // pressing modifier keys _themselves_ in case the page does unwanted // things when holding down alt for example). ctrl and cmd can't safely be // combined with hint chars anyway, due to some keyboard shortcuts not // being suppressible (such as ctrl+n, ctrl+q, ctrl+t, ctrl+w) (and // ctrl+alt+t opens a terminal by default in Ubuntu). // This always uses `event.key` since we are looking for _actual_ modifier // keypresses (keys may be rebound). // Note: On mac, alt/option is used to type special characters, while most // (if not all) ctrl shortcuts are up for grabs by extensions, so on mac // ctrl is used to activate hints in a new tab instead of alt. // In hints mode… (this.keyboardMode === "Hints" && // …suppress lone modifier keypresses (as mentioned above)… (isModifierKey(event.key) || // …or any other keypress really, with a few exceptions: (this.mac ? // On mac, allow cmd shortcuts (option is not used for shortcuts // but for typing special characters, and ctrl is used to // activate hints in new tabs): !event.metaKey : // On Windows and Linux, allow ctrl and win/super system shortcuts // (alt is used to activate hints in new tabs): !event.ctrlKey && !event.metaKey))); if (suppress) { suppressEvent(event); // `keypress` events are automatically suppressed when suppressing // `keydown`, but `keyup` needs to be manually suppressed. Note that if a // keyboard shortcut is alt+j it's possible to either release the alt key // first or the J key first, so we have to store _which_ key we want to // suppress the `keyup` event for. this.suppressNextKeyup = { key: event.key, code: event.code, }; log("log", "WorkerProgram#onKeydown", "suppressing event", { key: event.key, code: event.code, event, match, keyboardMode: this.keyboardMode, suppressNextKeyup: this.suppressNextKeyup, }); } // The "keydown" event fires at an interval while it is pressed. We're only // interested in the event where the key was actually pressed down. Ignore // the rest. Don't log this since it results in a _lot_ of logs. This is // done _after_ suppression – we still want to consistently suppress the key, // but don't want it to trigger more actions. if (event.repeat) { return; } if (this.keyboardMode === "Capture") { if (!isModifierKey(event.key)) { this.sendMessage({ type: "KeypressCaptured", keypress, }); } } else if (match !== undefined) { this.sendMessage({ type: "KeyboardShortcutMatched", action: match.action, timestamp: Date.now(), }); } else if (this.keyboardMode === "Hints" && suppress) { this.sendMessage({ type: "NonKeyboardShortcutKeypress", keypress, timestamp: Date.now(), }); } } onKeyup(event: KeyboardEvent): void { if (!event.isTrusted) { log("log", "WorkerProgram#onKeyup", "ignoring untrusted event", event); return; } if (this.suppressNextKeyup !== undefined) { const { key, code } = this.suppressNextKeyup; if (event.key === key && event.code === code) { log("log", "WorkerProgram#onKeyup", "suppressing event", { event, keyboardMode: this.keyboardMode, suppressNextKeyup: this.suppressNextKeyup, }); suppressEvent(event); this.suppressNextKeyup = undefined; } } } onMutation(records: Array<MutationRecord>): void { const { current } = this; if (current === undefined) { return; } const newElements = this.getAllNewElements(records); updateElementsWithEqualOnes(current, newElements); // In addition to the "UpdateElements" polling, update as soon as possible // when elements are removed/added/changed for better UX. For example, if a // modal closes it looks nicer if the hints for elements in the modal // disappear immediately rather than after a small delay. // Just after entering hints mode a mutation _always_ happens – inserting // the div with the hints. Don’t let that trigger an update. if (!(newElements.length === 1 && newElements[0].id === CONTAINER_ID)) { this.updateVisibleElements({ current, // Skip updating child frames since we only know that things changed in // _this_ frame. Child frames will be updated during the next poll. oneTimeWindowMessageToken: undefined, }); } } onPageHide(event: Event): void { if (!event.isTrusted) { log("log", "WorkerProgram#onPageHide", "ignoring untrusted event", event); return; } if (window.top === window) { // The top page is about to be “die.” this.sendMessage({ type: "TopPageHide" }); } } onPageShow(event: PageTransitionEvent): void { if (!event.isTrusted) { log("log", "WorkerProgram#onPageShow", "ignoring untrusted event", event); return; } if (event.persisted) { // We have returned to the page via the back/forward buttons. this.sendMessage({ type: "PersistedPageShow" }); } } getAllNewElements(records: Array<MutationRecord>): Array<HTMLElement> { const elements = new Set<HTMLElement>(); for (const record of records) { for (const node of record.addedNodes) { if (node instanceof HTMLElement && !elements.has(node)) { elements.add(node); const children = this.elementManager.getAllElements(node); for (const child of children) { elements.add(child); } } } } return Array.from(elements); } getElement(index: number): VisibleElement | undefined { return this.current === undefined ? undefined : this.current.elements[index]; } reportVisibleElements( types: ElementTypes, viewports: Array<Box>, oneTimeWindowMessageToken: string ): void { const time = new TimeTracker(); const [elementsWithNulls, timeLeft]: [ Array<VisibleElement | undefined>, number ] = this.elementManager.getVisibleElements(types, viewports, time); const elements = elementsWithNulls.flatMap((elementData) => elementData === undefined ? [] : elementData ); time.start("frames"); const frames = this.elementManager.getVisibleFrames(viewports); for (const frame of frames) { if (frame.contentWindow !== null) { const message: FrameMessage = { type: "FindElements", token: oneTimeWindowMessageToken, types, viewports: viewports.concat(getFrameViewport(frame)), }; frame.contentWindow.postMessage(message, "*"); } } time.start("element reports"); const elementReports = makeElementReports(elements, { maxDuration: timeLeft, prefix: "WorkerProgram#reportVisibleElements", }); time.start("send results"); this.sendMessage({ type: "ReportVisibleElements", elements: elementReports, numFrames: frames.length, stats: this.elementManager.makeStats(time.export()), }); this.current = { elements, frames, viewports, types, indexes: [], words: [], waitId: { tag: "NotWaiting" }, }; } updateVisibleElements({ current, oneTimeWindowMessageToken, }: { current: CurrentElements; oneTimeWindowMessageToken: string | undefined; }): void { const [elements, timeLeft]: [Array<VisibleElement | undefined>, number] = this.elementManager.getVisibleElements( current.types, current.viewports, new TimeTracker(), current.elements.map(({ element }) => element) ); const { words } = current; if (oneTimeWindowMessageToken !== undefined) { for (const frame of current.frames) { // Removing an iframe from the DOM nukes its page (this will be detected // by the port disconnecting). Re-inserting it causes the page to be // loaded anew. if (frame.contentWindow !== null) { const message: FrameMessage = { type: "UpdateElements", token: oneTimeWindowMessageToken, viewports: current.viewports.concat(getFrameViewport(frame)), }; frame.contentWindow.postMessage(message, "*"); } } } const wordsSet = new Set(words); const rects = words.length === 0 ? [] : elements.flatMap((maybeItem, index) => { if (maybeItem === undefined || !current.indexes.includes(index)) { return []; } const { element, type } = maybeItem; return getTextRectsHelper({ element, type, viewports: current.viewports, words: wordsSet, }); }); const elementReports = makeElementReports(elements, { maxDuration: timeLeft, prefix: "WorkerProgram#updateVisibleElements", }); this.sendMessage({ type: "ReportUpdatedElements", elements: elementReports, rects, }); } // Let the tutorial page know that Link Hints is installed, so it can toggle // some content. markTutorial(): void { if ( (window.location.origin + window.location.pathname === META_TUTORIAL || (!PROD && document.querySelector(`.${META_SLUG}Tutorial`) !== null)) && document.documentElement !== null ) { document.documentElement.classList.add("is-installed"); } } clickElement(element: HTMLElement): boolean { if (element instanceof HTMLMediaElement) { element.focus(); if (element.paused) { fireAndForget( element.play(), "WorkerProgram#clickElement->play", element ); } else { element.pause(); } return false; } const targetElement = getTargetElement(element); const rect = targetElement.getBoundingClientRect(); const options = { // Mimic real events as closely as possible. bubbles: true, cancelable: true, composed: true, detail: 1, view: window, // These seem to automatically set `x`, `y`, `pageX` and `pageY` as well. // There’s also `screenX` and `screenY`, but we can’t know those. clientX: Math.round(rect.left), clientY: Math.round(rect.top + rect.height / 2), }; // Just calling `.click()` isn’t enough to open dropdowns in gmail. That // requires the full mousedown+mouseup+click event sequence. const mousedownEvent = new MouseEvent("mousedown", { ...options, buttons: 1, }); const mouseupEvent = new MouseEvent("mouseup", options); const clickEvent = new MouseEvent("click", options); let cleanup = undefined; if (BROWSER === "firefox") { cleanup = firefoxPopupBlockerWorkaround({ element, isPinned: this.isPinned, ourClickEvent: clickEvent, }); } // When clicking a link for real the focus happens between the mousedown and // the mouseup, but moving this line between those two `.dispatchEvent` calls // below causes dropdowns in gmail not to be triggered anymore. // Note: The target element is clicked, but the original element is // focused. The idea is that the original element is a link or button, and // the target element might be a span or div. element.focus(); targetElement.dispatchEvent(mousedownEvent); targetElement.dispatchEvent(mouseupEvent); let defaultPrevented = !targetElement.dispatchEvent(clickEvent); if (BROWSER === "firefox") { if (cleanup !== undefined) { const result = cleanup(); if (result.pagePreventedDefault !== undefined) { defaultPrevented = result.pagePreventedDefault; } this.sendMessage({ type: "OpenNewTabs", urls: result.urlsToOpenInNewTabs, }); } } return defaultPrevented; } clearCurrent(): void { if (this.current !== undefined) { const { waitId } = this.current; switch (waitId.tag) { case "NotWaiting": break; case "RequestAnimationFrame": cancelAnimationFrame(waitId.id); break; case "RequestIdleCallback": cancelIdleCallback(waitId.id); break; } this.current = undefined; } } } function wrapMessage(message: FromWorker): ToBackground { return { type: "FromWorker", message, }; } function getFrameViewport(frame: HTMLFrameElement | HTMLIFrameElement): Box { const rect = frame.getBoundingClientRect(); const computedStyle = window.getComputedStyle(frame); const border = { left: parseFloat(computedStyle.getPropertyValue("border-left-width")), right: parseFloat(computedStyle.getPropertyValue("border-right-width")), top: parseFloat(computedStyle.getPropertyValue("border-top-width")), bottom: parseFloat(computedStyle.getPropertyValue("border-bottom-width")), }; const padding = { left: parseFloat(computedStyle.getPropertyValue("padding-left")), right: parseFloat(computedStyle.getPropertyValue("padding-right")), top: parseFloat(computedStyle.getPropertyValue("padding-top")), bottom: parseFloat(computedStyle.getPropertyValue("padding-bottom")), }; return { x: rect.left + border.left + padding.left, y: rect.top + border.top + padding.top, width: rect.width - border.left - border.right - padding.left - padding.right, height: rect.height - border.top - border.bottom - padding.top - padding.bottom, }; } // Focus any element. Temporarily alter tabindex if needed, and properly // restore it again when blurring. function focusElement(element: HTMLElement): void { const focusable = isFocusable(element); const tabIndexAttr = element.getAttribute("tabindex"); if (!focusable) { element.setAttribute("tabindex", "-1"); } element.focus(); if (!focusable) { let tabIndexChanged = false; const stop = (): void => { element.removeEventListener("blur", stop, options); mutationObserver.disconnect(); if (!tabIndexChanged) { if (tabIndexAttr === null) { element.removeAttribute("tabindex"); } else { element.setAttribute("tabindex", tabIndexAttr); } } }; const options = { capture: true, passive: true }; element.addEventListener("blur", stop, options); const mutationObserver = new MutationObserver((records) => { const removed = !element.isConnected; tabIndexChanged = records.some((record) => record.type === "attributes"); if (removed || tabIndexChanged) { stop(); } }); mutationObserver.observe(element, { attributes: true, attributeFilter: ["tabindex"], }); for (const root of getRootNodes(element)) { mutationObserver.observe(root, { childList: true, subtree: true, }); } } } function* getRootNodes(fromNode: Node): Generator<Node, void, void> { let node = fromNode; do { const root = node.getRootNode(); yield root; if (root instanceof ShadowRoot) { node = root.host; } else { break; } } while (true); } // When triggering a click on an element, it might actually make more sense to // trigger the click on one of its children. If `element` contains a single // child element (and no non-blank text nodes), use that child element instead // (recursively). Clicking an element _inside_ a link or button still triggers // the link or button. // This is because sites with bad markup might have links and buttons with an // inner element with where the actual click listener is attached. When clicking // the link or button with a real mouse, you actually click the inner element // and as such trigger the click listener. The actual link or button has no // click listener itself, so triggering a click there doesn’t do anything. Using // this function, we can try to simulate a real mouse click. If a link or button // has multiple children it is unclear which (if any!) child we should click, so // then we use the original element. function getTargetElement(element: HTMLElement): HTMLElement { const children = Array.from(element.childNodes).filter( (node) => !(node instanceof Text && node.data.trim() === "") ); const onlyChild = children.length === 1 ? children[0] : undefined; return onlyChild instanceof HTMLElement ? getTargetElement(onlyChild) : element; } // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-integers const TABINDEX = /^\s*([+-]\d+)\s*$/; // Returns whether `element.focus()` will do anything or not. function isFocusable(element: HTMLElement): boolean { const propValue = element.tabIndex; // `<a>`, `<button>`, etc. are natively focusable (`.tabIndex === 0`). // `.tabIndex` can also be set if the HTML contains a valid `tabindex` // attribute. // `-1` means either that the element isn't focusable, or that // `tabindex="-1"` was set, so we have to use `.getAttribute` to // disambiguate. if (propValue !== -1) { return true; } // Contenteditable elements are always focusable. if (element.isContentEditable) { return true; } const attrValue = element.getAttribute("tabindex"); if (attrValue === null) { return false; } // In Firefox, elements are focusable if they have the tabindex attribute, // regardless of whether it is valid or not. if (BROWSER === "firefox") { return true; } return TABINDEX.test(attrValue); } function isTextInput(element: HTMLElement): boolean { return ( element.isContentEditable || element instanceof HTMLTextAreaElement || // `.selectionStart` is set to a number for all `<input>` types that you can // type regular text into (`<input type="text">`, `<input type="search">`, // `<input type="unknown">`, etc), but not for `<input type="email">` and // `<input type="number">` for some reason. (element instanceof HTMLInputElement && (element.selectionStart !== null || element.type === "email" || element.type === "number")) ); } function reverseSelection(selection: Selection): void { const direction = getSelectionDirection(selection); if (direction === undefined) { return; } const range = selection.getRangeAt(0); const [edgeNode, edgeOffset] = direction ? [range.startContainer, range.startOffset] : [range.endContainer, range.endOffset]; range.collapse(!direction); selection.removeAllRanges(); selection.addRange(range); selection.extend(edgeNode, edgeOffset); } // true → forward, false → backward, undefined → unknown function getSelectionDirection(selection: Selection): boolean | undefined { if (selection.isCollapsed) { return undefined; } const { anchorNode, focusNode } = selection; if (anchorNode === null || focusNode === null) { return undefined; } const range = document.createRange(); range.setStart(anchorNode, selection.anchorOffset); range.setEnd(focusNode, selection.focusOffset); return !range.collapsed; } // Select the text of an element (if any – otherwise select the whole element // (such as an image)), ignoring leading and trailing whitespace. function selectNodeContents(element: HTMLElement): Range { const range = document.createRange(); let start = undefined; let end = undefined; for (const textNode of walkTextNodes(element)) { if (start === undefined) { const index = textNode.data.search(NON_WHITESPACE); if (index >= 0) { start = { textNode, index }; } } if (start !== undefined) { const index = textNode.data.search(LAST_NON_WHITESPACE); if (index >= 0) { end = { textNode, index: index + 1 }; } } } let method = undefined; if (start !== undefined && end !== undefined) { method = "text nodes"; range.setStart(start.textNode, start.index); range.setEnd(end.textNode, end.index); } else if (element.childNodes.length === 0) { method = "selectNode"; range.selectNode(element); } else { method = "selectNodeContents"; range.selectNodeContents(element); } log("log", "selectNodeContents", { method, start, end, element }); return range; } function getTextWeight(text: string, weight: number): number { // The weight used for hints after filtering by text is the number of // non-whitespace characters, plus a tiny bit of the regular hint weight in // case of ties. return Math.max(1, text.replace(/\s/g, "").length + Math.log10(weight)); } function suppressEvent(event: Event): void { event.preventDefault(); // `event.stopPropagation()` prevents the event from propagating further // up and down the DOM tree. `event.stopImmediatePropagation()` also // prevents additional listeners on the same node (`window` in this case) // from being called. event.stopImmediatePropagation(); // `event.preventDefault()` doesn’t work for `accesskey="x"` in Chrome. See: // https://stackoverflow.com/a/34008999/2010616 // Instead, temporarily remove all accesskeys. if (BROWSER === "chrome") { const elements = document.querySelectorAll<HTMLElement>("[accesskey]"); const accesskeyMap = new Map<HTMLElement, string>(); for (const element of elements) { const accesskey = element.getAttribute("accesskey"); if (accesskey !== null) { accesskeyMap.set(element, accesskey); element.removeAttribute("accesskey"); } } setTimeout(() => { for (const [element, accesskey] of accesskeyMap) { element.setAttribute("accesskey", accesskey); } }, 0); } } function makeElementReports( elements: Array<VisibleElement | undefined>, { maxDuration, prefix }: { maxDuration: number; prefix: string } ): Array<ElementReport> { const startTime = Date.now(); const elementReports = elements.flatMap((elementData, index) => elementData !== undefined ? visibleElementToElementReport(elementData, { index, textContent: Date.now() - startTime > maxDuration, }) : [] ); const skipped = elementReports.filter((report) => report.textContent); if (skipped.length > 0) { log( "warn", prefix, `Used .textContent for ${skipped.length} element(s) due to timeout`, { duration: Date.now() - startTime, max: maxDuration, skipped, } ); } return elementReports; } function visibleElementToElementReport( { element, type, measurements, hasClickListener }: VisibleElement, { index, textContent }: { index: number; textContent: boolean } ): ElementReport { const text = textContent ? element.textContent ?? "" : extractTextHelper(element, type); return { type, index, url: type === "link" && element instanceof HTMLAnchorElement ? element.href : undefined, urlWithTarget: type === "link" && element instanceof HTMLAnchorElement ? getUrlWithTarget(element) : undefined, text, textContent, textWeight: getTextWeight(text, measurements.weight), isTextInput: isTextInput(element), hasClickListener, hintMeasurements: measurements, }; } function updateElementsWithEqualOnes( current: CurrentElements, newElements: Array<HTMLElement> ): void { if (newElements.length === 0) { return; } for (const item of current.elements) { // If an element with a hint has been removed, try to find a new element // that seems to be equal. If only one is found – go for it and use the new // one. Some sites, like Gmail and GitHub, replace elements with new, // identical ones shortly after things load. That caused hints to disappear // for seemingly no reason (one cannot tell with one’s eyes that the hint’s // element had _technically_ been removed). This is an attempt to give such // hints new elements. if (!item.element.isConnected) { const equalElements = newElements.filter((element) => item.element.isEqualNode(element) ); if (equalElements.length === 1) { item.element = equalElements[0]; } } } } function extractTextHelper(element: HTMLElement, type: ElementType): string { // Scrollable elements do have `.textContent`, but it’s not intuitive to // filter them by text (especially since the matching text might be scrolled // away). Treat them more like frames (where you can’t look inside). if (type === "scrollable") { return ""; } // For text inputs, textareas, checkboxes, selects, etc, use their label text // for filtering. For buttons with a label, use both the button text and the // label text. const labels = getLabels(element); if (labels !== undefined) { return normalizeWhitespace( [extractText(element)] .concat(Array.from(labels, (label) => extractText(label))) .join(" ") ); } return normalizeWhitespace(extractText(element)); } function normalizeWhitespace(string: string): string { return string.trim().replace(/\s+/g, " "); } export function getTextRectsHelper({ element, type, viewports, words, checkElementAtPoint, }: { element: HTMLElement; type: ElementType; viewports: Array<Box>; words: Set<string>; checkElementAtPoint?: boolean; }): Array<Box> { // See `extractTextHelper`. if (type === "scrollable") { return []; } // See `extractTextHelper`. const labels = getLabels(element); if (labels !== undefined) { return [element].concat(Array.from(labels)).flatMap((element2) => getTextRects({ element: element2, viewports, words, checkElementAtPoint, }) ); } return getTextRects({ element, viewports, words, checkElementAtPoint }); } // Used to decide if two links can get the same hint. If they have the same href // and target they can. For some targets the frame must be the same as well. function getUrlWithTarget(link: HTMLAnchorElement): string { const target = link.target.toLowerCase(); const [caseTarget, frameHref] = target === "" || target === "_blank" || target === "_top" ? [target, ""] // Case insensitive target, not frame specific. : target === "_self" || target === "_parent" ? [target, window.location.href] // Case insensitive target, frame specific. : [link.target, window.location.href]; // Case sensitive target, frame specific. // `|` is not a valid URL character, so it is safe to use as a separator. return `${encodeURIComponent(caseTarget)}|${frameHref}|${link.href}`; } // In Firefox, programmatically clicking on an `<a href="..." // target="_blank">` (or on a link that goes to another site in a pinned // tab) causes the popup blocker to block the new tab/window from opening. // As a workaround, open such links in new tabs manually. // `target="someName"` can also trigger a new tab/window, but it can also // re-use `<iframe name="someName">` anywhere in the browsing context (not // just in the current frame), or re-use a previously opened tab/window with // "someName". Let’s not bother with those. They’re rare and it’s unclear // what we should do with them (where should they open?). // Similarly, `window.open` also triggers the popup blocker. It’s second // argument is similar to the `target` attribute on links. // Relevant bugzilla tickets: <bugzil.la/1615860>, <bugzil.la/1356309> and // <bugzil.la/1348213>. function firefoxPopupBlockerWorkaround({ element, isPinned, ourClickEvent, }: { element: HTMLElement; isPinned: boolean; ourClickEvent: MouseEvent; }): () => { pagePreventedDefault: boolean | undefined; urlsToOpenInNewTabs: Array<string>; } { const prefix = "firefoxPopupBlockerWorkaround"; const { wrappedJSObject } = window; // In the Options page, `window.wrappedJSObject` does not exist. if (wrappedJSObject === undefined) { log("log", prefix, "No window.wrappedJSObject"); return () => ({ pagePreventedDefault: undefined, urlsToOpenInNewTabs: [], }); } const resets = new Resets(); let linkUrl: string | undefined = undefined; // If the link has `target="_blank"` (or the pinned tab stuff is true), then // `event.preventDefault()` must _always_ be called, no matter what. Either // the page or ourselves will do it. We have to wait doing it ourselves for as // long as possible, though, to be able to detect `return false` from inline // listeners. let defaultPrevented: "ByPage" | "ByUs" | "NotPrevented" = "NotPrevented"; // Returns `element` if it is a link, or its first parent that is a link (if // any). Clicking on an element inside a link also activates the link. const linkElement = element.closest("a"); const link = linkElement instanceof HTMLAnchorElement ? linkElement : undefined; const shouldWorkaroundLinks = link !== undefined && (link.target.toLowerCase() === "_blank" || (isPinned && link.hostname !== window.location.hostname)); if (shouldWorkaroundLinks && link !== undefined) { // Default to opening this link in a new tab. linkUrl = link.href; const override = ( method: "preventDefault" | "stopImmediatePropagation", fn: (original: () => void) => () => void ): (() => void) => { const { prototype } = wrappedJSObject.Event; const original = prototype[method]; exportFunction(fn(original), prototype, { defineAs: method, }); return () => { prototype[method] = original; }; }; const onPagePreventDefault = (): void => { defaultPrevented = "ByPage"; // If the page prevents the default action, it does not want the link // opened at all, so clear out `linkUrl`. linkUrl = undefined; }; // Since Firefox supports `event.cancelBubble = true` and `event.returnValue // = false` things become a little complicated. I tried overriding those // properties with getters/setters to be able to detect when they are set, // but the `get`/`set` callback never seem to have been called. Instead, I // came up with another solution. // // The browser goes through every event target from the top (`window`) down // to `element`, and then up again. When visiting an event target, the // browser calls all listeners registered on that target and calls them in // order. If one of the listeners were to stop propagation, all remaining // listeners for the current target will still be executed, but the browser // won’t move on to the next targets. // // So we add a listener to each target, which will be the last listener for // the target. This way we can inspect `event.defaultPrevented` to see if // any previous listeners prevented the default action, and // `event.cancelBubble` to see if any previous listeners stopped // propagation. for (const target of getAllEventTargetsUpwards(element)) { for (const capture of [true, false]) { resets.add( addEventListener( target, "click", // eslint-disable-next-line @typescript-eslint/no-loop-func (event: Event) => { if (event !== ourClickEvent) { log( "log", prefix, "ignoring click event triggered by page while handling our click event", event, target ); return; } // We’re already done – just skip remaining listeners. if (defaultPrevented !== "NotPrevented") { return; } // The page has prevented the default action via one of the following: // - `event.preventDefault()` // - `event.returnValue = false` // - `return false` in an inline listener if (event.defaultPrevented) { log("log", prefix, "page preventDefault", event, target); onPagePreventDefault(); return; } // The page has stopped propagation using one of the following: // - `event.stopPropagation()` // - `event.cancelBubble = true` // We are the last listener to execute, so time to prevent default // ourselves. // (If the page uses `event.stopImmediatePropagation()` we never // end up here – see below.) if (event.cancelBubble || (target === window && !capture)) { log( "log", prefix, "extension preventDefault because of stopPropagation", event, target ); event.preventDefault(); defaultPrevented = "ByUs"; return; } // If the page never prevents the default action or stops // propagation, then the event will eventually bubble up to // `window` – the last target that the event visits. Then it’s // time to prevent default ourselves, to avoid the popup blocker. if (target === window && !capture) { log( "log", prefix, "extension preventDefault because of bubbled to window", event, target ); event.preventDefault(); defaultPrevented = "ByUs"; } }, "firefoxPopupBlockerWorkaround click listener", { capture, passive: false } ) ); } } resets.add( // The above approach breaks down if `event.stopImmediatePropagation()` is // called. That method works just like `event.stopPropagation()`, but also // tells the browser not to run any remaining listeners for the current // target. This means that our listeners above won’t run. Instead, we have // to override the `stopImmediatePropagation` method to detect when it is // called. override( "stopImmediatePropagation", (originalStopImmediatePropagation) => function stopImmediatePropagation(this: Event): void { if (this !== ourClickEvent) { log( "log", prefix, "ignoring stopImmediatePropagation for event triggered by page while handling our click event", this ); return; } // We’re already done – just skip remaining listeners. if (defaultPrevented !== "NotPrevented") { originalStopImmediatePropagation.call(this); return; } log("log", prefix, "page stopImmediatePropagation"); // If the page has already prevented the default action itself, // things are easy. Not much more to do. if (this.defaultPrevented) { log("log", prefix, "page preventDefault"); onPagePreventDefault(); originalStopImmediatePropagation.call(this); return; } // Otherwise, this is the last chance to prevent default, to make // sure that the popup blocker isn’t triggered. log( "log", prefix, "extension preventDefault because of stopImmediatePropagation" ); this.preventDefault(); defaultPrevented = "ByUs"; // But the page might call `event.preventDefault()` itself just // after `event.stopImmediatePropagation()`. Override // `preventDefault` so we can detect this, and not open a new tab if // so. This won’t catch `event.returnValue = false` or `return // false` in an inline listener, but hopefully that’s rare. resets.add( override( "preventDefault", (originalPreventDefault) => function preventDefault(this: Event): void { if (this !== ourClickEvent) { log( "log", prefix, "ignoring preventDefault for event triggered by page while handling our click event", this ); return; } log( "log", prefix, "page preventDefault after stopImmediatePropagation", this ); onPagePreventDefault(); originalPreventDefault.call(this); } ) ); originalStopImmediatePropagation.call(this); } ) ); } const urlsToOpenInNewTabs: Array<string> = []; // Temporarily override `window.open`. (If the page has overridden // `window.open` to something completely different, this breaks down a little. // Hopefully that’s rare.) // Note: The thing we triggered a click event on might call `window.open()`. // Right, that’s what we’re after. But it could just as well trigger a click // event on _another_ button that in turn calls `window.open()`. What should // happen then? That’s actually allowed (not blocked)! I think since the // `window.open()` happens synchronously within a trusted click, it’s ok. // eslint-disable-next-line @typescript-eslint/unbound-method const originalOpen = wrappedJSObject.open; exportFunction( function open( this: Window, url: unknown, target: unknown, features: unknown, ...args: Array<unknown> ): unknown { // These may throw exceptions: `{ toString() { throw new Error } }`; // If so – let that happen, just like standard `window.open`. If they // throw we simply don’t continue. // (If using just `String` rather than `window.wrappedJSObject.String`, // the errors would not show up in the console.) const toString = wrappedJSObject.String; const urlString: string = toString(url); const targetString = toString(target); toString(features); if ( // When clicking something with the mouse, Firefox only allows one // `window.open` call – the rest are blocked by the popup blocker. This // sounds reasonable – one wouldn’t want a button to open up 100 popups. urlsToOpenInNewTabs.length < 1 && // All of these mean opening in a new tab/window. (target === undefined || targetString === "" || targetString === "_blank") ) { const href = url === undefined || urlString === "" ? "about:blank" : new URL(urlString, window.location.href).toString(); urlsToOpenInNewTabs.push(href); log("log", prefix, "window.open", href); // Since we don’t have access to the `window` of the to-be-opened tab, // lie to the page and say that the window couldn’t be opened. return null; } // @ts-expect-error Intentionally passing on the original, possibly invalid, arguments. return originalOpen.call(this, url, target, features, ...args); }, window.wrappedJSObject, { defineAs: "open" } ); return () => { resets.reset(); wrappedJSObject.open = originalOpen; const result = { pagePreventedDefault: shouldWorkaroundLinks ? defaultPrevented === "ByPage" : undefined, urlsToOpenInNewTabs: linkUrl !== undefined ? [linkUrl, ...urlsToOpenInNewTabs] : urlsToOpenInNewTabs, }; log("log", prefix, "result", result); return result; }; } function* getAllEventTargetsUpwards( fromNode: Node ): Generator<EventTarget, void, void> { let node: Node = fromNode; do { yield node; const parent = node.parentNode; if (parent instanceof ShadowRoot) { yield parent; node = parent.host; } else { // `parent` can be `null` here. That will end the loop. But at the start // of the loop we know that `node` is never `null`. node = parent as Node; } } while (node !== null); yield window; } function isInternalHashLink(element: HTMLAnchorElement): boolean { return ( element.href.includes("#") && stripHash(element.href) === stripHash(window.location.href) ); } function stripHash(url: string): string { const index = url.indexOf("#"); return index === -1 ? url : url.slice(0, index); } function flashElement(element: HTMLElement): void { const selector = t.FLASH_COPIED_ELEMENT_NO_INVERT_SELECTOR.value; const changes = [ temporarilySetFilter( element, element.matches(selector) ? "contrast(0.5)" : "invert(0.75)" ), ...Array.from(element.querySelectorAll<HTMLElement>(selector), (image) => temporarilySetFilter(image, "invert(1)") ), ]; for (const { apply } of changes) { apply(); } setTimeout(() => { for (const { reset } of changes) { reset(); } }, t.FLASH_COPIED_ELEMENT_DURATION.value); } function temporarilySetFilter( element: HTMLElement, value: string ): { apply: () => void; reset: () => void } { const prop = "filter"; const originalValue = element.style.getPropertyValue(prop); const important = element.style.getPropertyPriority(prop); const newValue = `${originalValue} ${value}`.trim(); return { apply: () => { element.style.setProperty(prop, newValue, "important"); }, reset: () => { if ( element.style.getPropertyValue(prop) === newValue && element.style.getPropertyPriority(prop) === "important" ) { element.style.setProperty(prop, originalValue, important); } }, }; }
the_stack
import { ValidatePatternRules, ValidateArrayRules, getMessage } from "@formily/validator"; import { lowercase, map, each, isEmpty, isEqual, isArr, toArr, isBool, isValid, FormPathPattern, FormPath, deprecate } from "@formily/shared"; import { SchemaMessage, ISchema } from "@formily/react-schema-renderer"; const numberRE = /^\d+$/; type SchemaProperties<T = Schema> = { [key: string]: T; }; const findProperty = (object: any, propertyKey: string | number) => { if (!object) return object; if (object[propertyKey]) { return object[propertyKey]; } //降级搜索,如果key通过映射的方式没有完全映射上,会提供降级搜索方式,保证完备性 for (let key in object) { if (FormPath.parse(key).match(`[[${propertyKey}]]`)) { return object[key]; } } }; export const filterProperties = <T extends object>( object: T, keys: string[] ): T => { let result = {} as any; for (let key in object) { if (!keys.includes(key) && Object.hasOwnProperty.call(object, key)) { result[key] = object[key]; } } return result; }; //向后兼容逻辑,未来会干掉 const COMPAT_FORM_ITEM_PROPS = [ //next "required", "prefix", "labelAlign", "hasFeedback", "labelCol", "wrapperCol", "label", "help", "labelTextAlign", "fullWidth", "extra", "size", "asterisk", "labelWidth", "device", "isPreview", "renderPreview", "validateState", //antd "colon", "htmlFor", "validateStatus", "prefixCls", //formily "triggerType", "itemStyle", "itemClassName", "addonAfter" ]; export class Schema implements ISchema { /** base json schema spec**/ public title?: SchemaMessage; public description?: SchemaMessage; public default?: any; public readOnly?: boolean; public writeOnly?: boolean; public type?: ISchema["type"]; public enum?: ISchema["enum"]; public const?: any; public multipleOf?: number; public maximum?: number; public exclusiveMaximum?: number; public minimum?: number; public exclusiveMinimum?: number; public maxLength?: number; public minLength?: number; public pattern?: string | RegExp; public maxItems?: number; public minItems?: number; public uniqueItems?: boolean; public maxProperties?: number; public minProperties?: number; public required?: string | boolean | string[]; public format?: string; /** nested json schema spec **/ public properties?: SchemaProperties; public items?: Schema | Schema[]; public additionalItems?: Schema; public patternProperties?: { [key: string]: Schema; }; public additionalProperties?: Schema; /** extend json schema specs */ public editable?: boolean; public visible?: boolean; public display?: boolean; public triggerType?: "onBlur" | "onChange"; public ["x-props"]?: { [name: string]: any }; public ["x-index"]?: number; public ["x-rules"]?: ValidatePatternRules; public ["x-component"]?: string; public ["x-component-props"]?: ISchema["x-component-props"]; public ["x-render"]?: ISchema["x-render"]; public ["x-effect"]?: ISchema["x-effect"]; /** schema class self specs**/ public parent?: Schema; public children?: Schema[]; public _isJSONSchemaObject = true; public __ID__?:string public key?: string; public path?: string; constructor(json: ISchema, parent?: Schema, key?: string) { if (key) { this.key = key; } this.setParent(parent); if (json instanceof Schema) { if (this.parent) { json.parent = this.parent; } if (this.key) { json.key = this.key; } if (this.path) { json.path = this.path; } return json; } return this.fromJSON(json) as any; } setParent(parent?: Schema) { if (parent) { this.parent = parent; } if (this.parent && this.parent.isArray()) { this.path = this.parent.path + ".0"; } else { if (this.parent) { this.path = this.parent.path ? this.parent.path + "." + this.key : this.key; } else { this.path = ""; } } } /** * getters */ get(path?: FormPathPattern) { if (!path) { return this; } let res: Schema = this; let depth = 0; let parsed = FormPath.parse(path); parsed.forEach(key => { if (res && !isEmpty(res.properties)) { res = findProperty(res.properties, key) || findProperty(res.properties, parsed.segments.slice(depth).join(".")); } else if (res && !isEmpty(res.items) && numberRE.test(key as string)) { res = isArr(res.items) ? findProperty(res.items, key) : res.items; } depth++; }); return res; } merge(spec: any) { if (spec instanceof Schema) { Object.assign(this, spec.getSelfProps()); } else { Object.assign(this, spec); } return this; } getEmptyValue() { if (this.type === "string") { return ""; } if (this.type === "array") { return []; } if (this.type === "object") { return {}; } if (this.type === "number") { return 0; } } getSelfProps() { const { _isJSONSchemaObject, __ID__, properties, additionalProperties, additionalItems, patternProperties, items, path, parent, children, ...props } = this; return props; } getExtendsRules() { let rules: ValidateArrayRules = []; if (this.format) { rules.push({ format: this.format }); } if (isValid(this.maxItems)) { rules.push({ max: this.maxItems }); } if (isValid(this.minItems)) { rules.push({ min: this.minItems }); } if (isValid(this.maxLength)) { rules.push({ max: this.maxLength }); } if (isValid(this.minLength)) { rules.push({ min: this.minLength }); } if (isValid(this.maximum)) { rules.push({ maximum: this.maximum }); } if (isValid(this.minimum)) { rules.push({ minimum: this.minimum }); } if (isValid(this.exclusiveMaximum)) { rules.push({ exclusiveMaximum: this.exclusiveMaximum }); } if (isValid(this.exclusiveMinimum)) { rules.push({ exclusiveMinimum: this.exclusiveMinimum }); } if (isValid(this.pattern)) { rules.push({ pattern: this.pattern }); } if (isValid(this.const)) { rules.push({ validator: value => { return value === this.const ? "" : getMessage("schema.const"); } }); } if (isValid(this.multipleOf)) { rules.push({ validator: value => { return value % this.multipleOf === 0 ? "" : getMessage("schema.multipleOf"); } }); } if (isValid(this.maxProperties)) { rules.push({ validator: value => { return Object.keys(value || {}).length <= this.maxProperties ? "" : getMessage("schema.maxProperties"); } }); } if (isValid(this.minProperties)) { rules.push({ validator: value => { return Object.keys(value || {}).length >= this.minProperties ? "" : getMessage("schema.minProperties"); } }); } if (isValid(this.uniqueItems) && this.uniqueItems) { rules.push({ validator: value => { value = toArr(value); return value.some((item: any, index: number) => { for (let start = index; start < value.length; start++) { if (isEqual(value[start], item)) { return false; } } }) ? getMessage("schema.uniqueItems") : ""; } }); } /**剩余校验的都是关联型复杂校验,不抹平,让用户自己处理 */ if (isValid(this["x-rules"])) { rules = rules.concat(this["x-rules"]); } return rules; } getExtendsRequired() { if (isBool(this.required)) { return this.required; } } getExtendsEditable(): boolean { const { editable } = this.getExtendsComponentProps(); if (isValid(this.editable)) { return this.editable; } else if (isValid(editable)) { return editable; } else if (isValid(this.readOnly)) { return !this.readOnly; } } getExtendsVisible(): boolean { const { visible } = this.getExtendsComponentProps(); if (isValid(this.visible)) { return this.visible; } else if (isValid(visible)) { return visible; } } getExtendsDisplay(): boolean { const { display } = this.getExtendsComponentProps(); if (isValid(this.display)) { return this.display; } else if (isValid(display)) { return display; } } getExtendsTriggerType() { const itemProps = this.getExtendsItemProps(); const props = this.getExtendsProps(); const componentProps = this.getExtendsComponentProps(); if (this.triggerType) { return this.triggerType; } if (itemProps.triggerType) { return itemProps.triggerType; } else if (props.triggerType) { return props.triggerType; } else if (componentProps.triggerType) { return componentProps.triggerType; } } getExtendsItemProps() { if (isValid(this["x-item-props"])) { deprecate("x-item-props is deprecate in future, Please do not use it."); } return this["x-item-props"] || {}; } getExtendsComponent() { return this["x-component"]; } getExtendsRenderer() { if (isValid(this["x-render"])) { deprecate("x-render is deprecate in future, Please do not use it."); } return this["x-render"]; } getExtendsEffect() { return this["x-effect"]; } getExtendsProps() { return this["x-props"] || {}; } getExtendsComponentProps() { return { ...filterProperties(this["x-props"], COMPAT_FORM_ITEM_PROPS), ...this["x-component-props"] }; } getExtendsLinkages() { return this["x-linkages"]; } /** * getters */ setProperty(key: string, schema: ISchema) { this.properties = this.properties || {}; this.children = this.children || []; const alreadyHaveProperty = !!this.properties[key]; this.properties[key] = new Schema(schema, this, key); if (!alreadyHaveProperty) { this.properties[key]["x-index"] = this.children.length; this.children.push(this.properties[key]); } else { this.children[this.properties[key]["x-index"]] = this.properties[key]; } return this.properties[key]; } setProperties(properties: SchemaProperties<ISchema>) { let orderProperties = []; const unorderProperties = []; each(properties, (item, key) => { if (!item) return; const index = item["x-index"]; this.properties[key] = new Schema(item, this, key); if (typeof index === "number") { orderProperties[index] = this.properties[key]; } else { unorderProperties.push(this.properties[key]); } }); orderProperties = orderProperties.filter(item => item) this.children = orderProperties .concat(unorderProperties) .map((schema, index) => { schema["x-index"] = index; return schema; }); return this.properties; } setArrayItems(schema: ISchema) { this.items = new Schema(schema, this); return this.items; } toJSON() { const result: ISchema = this.getSelfProps(); if (isValid(this.properties)) { result.properties = map(this.properties, schema => { return schema.toJSON(); }); } if (isValid(this.items)) { result.items = isArr(this.items) ? this.items.map(schema => schema.toJSON()) : this.items.toJSON(); } if (isValid(this.additionalItems)) { result.additionalItems = this.additionalItems.toJSON(); } if (isValid(this.additionalProperties)) { result.additionalProperties = this.additionalProperties.toJSON(); } if (isValid(this.patternProperties)) { result.patternProperties = map(this.patternProperties, schema => { return schema.toJSON(); }); } return result; } fromJSON(json: ISchema = {}) { if (typeof json === "boolean") return json; if (json instanceof Schema) { Object.assign(this, json); return this; } else { Object.assign(this, json); } if (isValid(json.type)) { this.type = lowercase(String(json.type)); } if (isValid(json["x-component"])) { this["x-component"] = lowercase(json["x-component"]); } const emptyProperties = isEmpty(json.properties); const emptyItems = isEmpty(json.items); if (!emptyProperties) { this.children = []; this.setProperties(json.properties); } if (isValid(json.additionalProperties)) { this.additionalProperties = new Schema(json.additionalProperties, this); } if (isValid(json.patternProperties)) { this.patternProperties = map(json.patternProperties, (item, key) => { return new Schema(item, this, key); }); } if (!emptyItems) { this.items = isArr(json.items) ? map(json.items, item => new Schema(item, this)) : new Schema(json.items, this); if (isValid(json.additionalItems)) { this.additionalItems = new Schema(json.additionalItems, this); } } if (emptyProperties && emptyItems) { this.children = []; } return this; } /** * tools */ isObject() { return this.type === "object"; } isArray() { return this.type === "array"; } mapProperties(callback?: (schema: Schema, key: string) => any) { if (this.children && this.children.length) { return this.children.map(schema => { return callback(schema, schema.key); }); } return this.getOrderProperties().map(({ schema, key }) => { return callback(schema, key); }); } getOrderProperties() { return Schema.getOrderProperties(this); } unrelease_getOrderPatternProperties() { return Schema.getOrderProperties(this, "patternProperties"); } unrelease_mapPatternProperties( callback?: (schema: Schema, key: string) => any ) { return this.unrelease_getOrderPatternProperties().map(({ schema, key }) => { return callback(schema, key); }); } /** node mutators **/ append(key: string, json: ISchema): Schema { let schema:Schema if (this.isArray()) { this.items = new Schema( { type: "object" }, this ); this.children = [this.items]; return this.items.append(key, json); } else { if (json instanceof Schema && json.parent) { json.remove(); schema = json; } else { schema = new Schema(json) } this.setProperty(key, schema); } return this; } removeChildByKey(key: string): Schema { if (this.isArray()) { if (this.items instanceof Schema) { this.items.removeChildByKey(key); } } else { this.properties = this.properties || {}; const foundIndex = this.children.findIndex( schema => this.properties[key] === schema ); let index = 0; this.children = this.children.reduce((buf, schema, idx) => { if (idx === foundIndex) { return buf; } else { schema.setParent(this); schema["x-index"] = index++; return buf.concat(schema); } }, []); delete this.properties[key]; } return this; } removeChildByIndex(index: number): Schema { if (this.isArray()) { if (this.items instanceof Schema) { this.items.removeChildByIndex(index); } } else if (this.children && this.children[index]) { let _index = 0; this.children = this.children.reduce((buf, schema, idx) => { if (idx === index) { return buf; } else { schema.setParent(this); schema["x-index"] = _index++; return buf.concat(schema); } }, []); delete this.properties[this.children[index].key]; } return this; } remove(): Schema { if (this.parent) { if (this.key) { this.parent.removeChildByKey(this.key); } else { if (this.parent.isArray()) { delete this.parent.items; } } } return this; } insertBefore(json: ISchema) { let schema: Schema; if (json instanceof Schema) { if ( this.parent && this.parent.properties && this.parent.properties[json.key] ) { if (this.parent.properties[json.key] !== json) { throw new Error("The schema node key cannot be duplicated"); } } if (json.parent) { json.remove(); } schema = json; } else { schema = new Schema(json); if (!schema["key"]) { throw new Error("The schema node must have 'key' property."); } } if (this.parent) { let index = 0; const newChildren = []; const targetIndex = this["x-index"]; for (let idx = 0; idx < this.parent.children.length; idx++) { const item = this.parent.children[idx]; if (idx === targetIndex) { schema["x-index"] = index; item["x-index"] = index + 1; item.setParent(this.parent); index += 2; newChildren.push(schema, item); } else { item["x-index"] = index++; newChildren.push(item); } } schema.setParent(this.parent); this.parent.children = newChildren; this.parent.properties[schema["key"]] = schema; } else { throw new Error("The schema root node cannot be moved."); } } insertAfter(json: ISchema) { let schema: Schema; if (json instanceof Schema) { if ( this.parent && this.parent.properties && this.parent.properties[json.key] ) { if (this.parent.properties[json.key] !== json) { throw new Error("The schema node key cannot be duplicated"); } } if (json.parent) { json.remove(); } schema = json; } else { schema = new Schema(json); if (!schema["key"]) { throw new Error("The schema node must have 'key' property."); } } if (this.parent) { let index = 0; const newChildren = []; const targetIndex = this["x-index"]; for (let idx = 0; idx < this.parent.children.length; idx++) { const item = this.parent.children[idx]; if (idx === targetIndex) { item["x-index"] = index; schema["x-index"] = index + 1; item.setParent(this.parent); index += 2; newChildren.push(item, schema); } else { item["x-index"] = index++; newChildren.push(item); } } schema.setParent(this.parent); this.parent.children = newChildren; this.parent.properties[schema["key"]] = schema; } else { throw new Error("The schema root node cannot be moved."); } } static getOrderProperties = ( schema: ISchema = {}, propertiesName: string = "properties" ) => { const newSchema = new Schema(schema); const orderProperties = []; const unorderProperties = []; each(newSchema[propertiesName], (item, key) => { const index = item["x-index"]; if (typeof index === "number") { orderProperties[index] = { schema: item, key }; } else { unorderProperties.push({ schema: item, key }); } }); return orderProperties.filter(schema => !!schema).concat(unorderProperties); }; }
the_stack
export enum Phase { /** No event is being processed at this time. */ NONE, /** The event is being propagated through the target's ancestor objects. */ CAPTURING_PHASE, /** The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If Event.bubbles is false, processing the event is finished after this phase is complete. */ AT_TARGET, /** The event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing Window. This is known as bubbling, and occurs only if Event.bubbles is true. Event listeners registered for this phase are triggered during this process. */ BUBBLING_PHASE, } export interface EventInit { bubbles?: boolean; cancelable?: boolean; composed?: boolean; } /** * The Event interface represents an event which takes place in the DOM. * * An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). * * There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. * * Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connected (or "attached") to various HTML elements (such as <button>, <div>, <span>, etc.) using EventTarget.addEventListener(), and this generally replaces using the old HTML event handler attributes. Further, when properly added, such handlers can also be disconnected if needed using removeEventListener(). */ export class Event { constructor(type: string, eventInitDict?: EventInit) { this._type = type; if (eventInitDict) { this._bubbles = eventInitDict.bubbles; this._cancelable = eventInitDict.cancelable; this._composed = eventInitDict.composed; } } /** * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ get bubbles(): boolean { return this._bubbles; } protected _bubbles: boolean; cancelBubble: boolean; /** * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ get cancelable(): boolean { return this._cancelable; } protected _cancelable: boolean; /** * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ get composed(): boolean { return this._composed; } protected _composed: boolean; /** * Returns the object whose event listener's callback is currently being invoked. */ get currentTarget(): EventTarget { return this._currentTarget; } protected _currentTarget: EventTarget; /** * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ get defaultPrevented(): boolean { return this._defaultPrevented; } protected _defaultPrevented: boolean; /** * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ get eventPhase(): Phase { return this._eventPhase; } protected _eventPhase: Phase; /** * Returns true if event was dispatched by the user agent, and false otherwise. */ get isTrusted(): boolean { return this._isTrusted; } protected _isTrusted: boolean; returnValue: boolean; /** * Returns the object to which event is dispatched (its target). */ get target(): EventTarget { return this._target; } protected _target: EventTarget; /** * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ get timeStamp(): number { return this._timeStamp; } protected _timeStamp: number; /** * Returns the type of event, e.g. "click", "hashchange", or "submit". */ get type(): string { return this._type; } protected _type: string; /** * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. */ composedPath(): EventTarget[] { return []; } initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void { this._type = type; this._bubbles = bubbles; this._cancelable = cancelable; } /** * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. */ preventDefault(): void { if (this.cancelable) { this._defaultPrevented = true; } } /** * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. */ stopImmediatePropagation(): void { this._defaultPrevented = true; this.cancelBubble = false; } /** * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. */ stopPropagation(): void { if (this._bubbles) { this.cancelBubble = true; } } } interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; total?: number; } /** Events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). */ export class ProgressEvent<T extends EventTarget = EventTarget> extends Event { get lengthComputable(): boolean { return this._lengthComputable; } protected _lengthComputable: boolean; get loaded(): number { return this._loaded; } protected _loaded: number; get total(): number { return this._total; } protected _total: number; constructor(type: string, eventInitDict?: ProgressEventInit) { super(type, eventInitDict); if (eventInitDict) { this._lengthComputable = eventInitDict.lengthComputable; this._loaded = eventInitDict.loaded; this._total = eventInitDict.total; } } } export interface EventListener { (evt: Event): void; } export interface EventListenerObject { handleEvent(evt: Event): void; } export interface EventListenerOptions { capture?: boolean; } export interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; } export type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface EventListenerRecord extends AddEventListenerOptions { listener: EventListenerOrEventListenerObject; } export class EventTarget { protected _listeners: {[key: string]: EventListenerRecord[]} = {}; /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ public addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { if (!listener) return; if (!(type in this._listeners)) { this._listeners[type] = []; } let recorder: EventListenerRecord = { listener }; if (typeof options === "boolean") { recorder.capture = options; } else if (typeof options === 'object') { recorder = { ...options, listener }; } this._listeners[type].push(recorder); } /** * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ public dispatchEvent(event: Event): boolean { if (!event || typeof event.type != 'string') return true; const origin_recorders = this._listeners[event.type]; if (!origin_recorders) return true; const recorders = origin_recorders.slice(); if (!recorders.length) return !event.defaultPrevented; event['_target'] = this; let once_listeners: EventListenerRecord[] = []; for (const recorder of recorders) { let listener: EventListener = null; if ((recorder.listener as EventListenerObject).handleEvent) { listener = (recorder.listener as EventListenerObject).handleEvent; } else { listener = recorder.listener as EventListener; } if (typeof listener === 'function') { listener.call(this, event); } if (recorder.once) { once_listeners.push(recorder); } if (event.defaultPrevented) break; } for (let i = 0; i < once_listeners.length; i++) { origin_recorders.splice(origin_recorders.indexOf(once_listeners[i]), 1); } return !event.defaultPrevented; } /** * Removes the event listener in target's event listener list with the same type, callback, and options. */ public removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void { if (!listener || !(type in this._listeners)) return; const recorders = this._listeners[type]; for (let i = 0; i < recorders.length; i++) { const recorder = recorders[i]; if (recorder.listener === listener) { let sameOptions = true; if (typeof options === "boolean") { sameOptions = recorder.capture == options; } else if (typeof options === 'object') { sameOptions = recorder.capture == options.capture; } if (sameOptions) { recorders.splice(i, 1); break; } } } } /** * Removes the event listeners in target's event listener list with the same type * * Clear all listeners if type is `undefined` * */ public clearEventListeners(type?: string): void { if (typeof(type) === 'string') { this._listeners[type] = undefined; } else if (typeof(type) === 'undefined') { this._listeners = {}; } } } export default { exports: { Phase, Event, ProgressEvent, EventTarget } };
the_stack
import { WebRTCConnection, WebRTCConnectionCommand, WebRTCConnectionEvent, WebRTCConnectionProxy, WebRTCConnectionsHost, WebSocketConnection } from 'net/transport'; import { LinkupManager, LinkupAddress, LinkupManagerEvent, LinkupManagerHost, LinkupManagerCommand, LinkupManagerProxy } from 'net/linkup'; import { describeProxy } from 'config'; import { Connection } from 'net/transport/Connection'; import { RNGImpl } from 'crypto/random'; describeProxy('[TRA] Transports', () => { test('[TRA01] WebRTC send / answer', (done) => { let linkupManager1 = new LinkupManager(); let linkupManager2 = new LinkupManager(); //let linkupServer2 = LinkupManager.defaultLinkupServer; let linkupServer1 = LinkupManager.defaultLinkupServer; const rnd = new RNGImpl().randomHexString(64); let address1 = new LinkupAddress(linkupServer1, 'addressOne_C_' + rnd); let address2 = new LinkupAddress(linkupServer1, 'addressTwo_C_' + rnd); let theCallId = 'DUMMY_CALL_ID_TEST_C_' + rnd; let channelName = "test_data_channel"; let conn2: WebRTCConnection|undefined = undefined; linkupManager2.listenForMessagesNewCall(address2, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { receiver; conn2 = new WebRTCConnection(linkupManager2, address2, sender, callId, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); }); conn2.setMessageCallback((message: any, _conn: Connection) => { expect(message).toEqual("hola"); conn2?.send("chau"); }); conn2.answer(message); }); let conn1 = new WebRTCConnection(linkupManager1, address1, address2, theCallId, (conn: Connection) => { conn.send("hola"); }); conn1.setMessageCallback((message: any) => { expect(message).toEqual("chau"); conn1.close(); conn2?.close(); linkupManager1.shutdown(); linkupManager2.shutdown(); done(); }); conn1.open(channelName); }, 15000); test('[TRA02] WebSocket send / answer', (done) => { //let linkupManager1 = new LinkupManager(); let linkupManager2 = new LinkupManager(); //let linkupServer2 = LinkupManager.defaultLinkupServer; let listenAddress1 = 'ws://localhost:10000'; let listenAddress2 = 'ws://localhost:10001'; const rnd = new RNGImpl().randomHexString(64); let address1 = new LinkupAddress(listenAddress1, 'addressOne_D_' + rnd); let address2 = new LinkupAddress(listenAddress2, 'addressTwo_D_' + rnd); let theCallId = 'DUMMY_CALL_ID_TEST_D_' + rnd; let conn2: WebSocketConnection|undefined = undefined; linkupManager2.listenForMessagesNewCall(address2, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { receiver; conn2 = new WebSocketConnection(callId, address2, sender, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); }); conn2.setMessageCallback((message: any, _conn: Connection) => { expect(message).toEqual("hola"); conn2?.send("chau"); }); conn2.answer(message); }); let conn1 = new WebSocketConnection(theCallId, address1, address2, (conn: Connection) => { conn.send("hola"); }); conn1.setMessageCallback((message: any) => { expect(message).toEqual("chau"); conn1.close(); conn2?.close(); linkupManager2.shutdown(); done(); }); setTimeout(() => { conn1.open(); }, 100); }, 15000); test('[TRA03] WebRTC -> WebSocket send / answer', (done) => { //let linkupManager1 = new LinkupManager(); let linkupManager2 = new LinkupManager(); //let linkupServer2 = LinkupManager.defaultLinkupServer; let listenAddress1 = LinkupManager.defaultLinkupServer; let listenAddress2 = 'ws://localhost:10011'; const rnd = new RNGImpl().randomHexString(64); let address1 = new LinkupAddress(listenAddress1, 'addressOne_F_' + rnd); let address2 = new LinkupAddress(listenAddress2, 'addressTwo_F_' + rnd); let theCallId = 'DUMMY_CALL_ID_TEST_F_' + rnd; let conn2: WebSocketConnection|undefined = undefined; linkupManager2.listenForMessagesNewCall(address2, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { receiver; conn2 = new WebSocketConnection(callId, address2, sender, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); }); conn2.setMessageCallback((message: any, _conn: Connection) => { expect(message).toEqual("hola"); conn2?.send("chau"); }); conn2.answer(message); }); let conn1 = new WebSocketConnection(theCallId, address1, address2, (conn: Connection) => { conn.send("hola"); }); conn1.setMessageCallback((message: any) => { expect(message).toEqual("chau"); conn1.close(); conn2?.close(); linkupManager2.shutdown(); done(); }); setTimeout(() => { conn1.open(); }, 100); }, 15000); test('[TRA04] WebSocket -> WebRTC send / answer w/reverse connection', (done) => { let linkupManager1 = new LinkupManager(); let linkupManager2 = new LinkupManager(); //let linkupServer2 = LinkupManager.defaultLinkupServer; let listenAddress1 = 'ws://localhost:10020'; let listenAddress2 = LinkupManager.defaultLinkupServer; const rnd = new RNGImpl().randomHexString(64); let address1 = new LinkupAddress(listenAddress1, 'addressOne_E_' + rnd); let address2 = new LinkupAddress(listenAddress2, 'addressTwo_E_' + rnd); let theCallId = 'DUMMY_CALL_ID_TEST_E_' + rnd; let conn2: WebSocketConnection|undefined = undefined; linkupManager2.listenForMessagesNewCall(address2, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { receiver; conn2 = new WebSocketConnection(callId, address2, sender, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); expect(conn.initiatedLocally()).toBeFalsy(); }); conn2.setMessageCallback((message: any, _conn: Connection) => { expect(message).toEqual("hola"); conn2?.send("chau"); }); conn2.answer(message); }); let conns:any = {}; linkupManager1.listenForMessagesNewCall(address1, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { sender; receiver; if (callId === theCallId) { let c = conns[callId]; c.answer(message); } }); let conn1 = new WebSocketConnection(theCallId, address1, address2, (conn: Connection) => { conn.send("hola"); }, linkupManager1); conns[theCallId] = conn1; conn1.setMessageCallback((message: any) => { expect(message).toEqual("chau"); expect(conn1.initiatedLocally()).toBeTruthy(); conn1.close(); conn2?.close(); linkupManager1.shutdown(); linkupManager2.shutdown(); done(); }); setTimeout(() => { conn1.open(); }, 100); }, 15000); test('[TRA05] WebRTC send / answer w/proxies', (done) => { let eventCallback = (ev: LinkupManagerEvent) => { linkupManager1.linkupManagerEventIngestFn(ev); } let linkupManager1Host = new LinkupManagerHost(eventCallback); let commandForwardingFn = (cmd: LinkupManagerCommand) => { linkupManager1Host.execute(cmd); } let linkupManager1 = new LinkupManagerProxy(commandForwardingFn); let eventCallback2 = (ev: LinkupManagerEvent) => { linkupManager2.linkupManagerEventIngestFn(ev); } let linkupManager2Host = new LinkupManagerHost(eventCallback2); let commandForwardingFn2 = (cmd: LinkupManagerCommand) => { linkupManager2Host.execute(cmd); } let linkupManager2 = new LinkupManagerProxy(commandForwardingFn2); //let linkupServer2 = LinkupManager.defaultLinkupServer; let linkupServer1 = LinkupManager.defaultLinkupServer; const rnd = new RNGImpl().randomHexString(64); let address1 = new LinkupAddress(linkupServer1, 'addressOne_F_' + rnd); let address2 = new LinkupAddress(linkupServer1, 'addressTwo_F_' + rnd); let theCallId = 'DUMMY_CALL_ID_TEST_F_' + rnd; let channelName = "test_data_channel"; let conn2: WebRTCConnection|undefined = undefined; linkupManager2.listenForMessagesNewCall(address2, (sender: LinkupAddress, receiver: LinkupAddress, callId: string, message: any) => { receiver; let webRTCEventCallback2 = (ev: WebRTCConnectionEvent) => { conn2.connectionEventIngestFn(ev); } let connHost2 = new WebRTCConnectionsHost(webRTCEventCallback2, linkupManager2 as any as LinkupManager); let webRTCcommandForwardingFn2 = (cmd: WebRTCConnectionCommand) => { connHost2.execute(cmd); } let conn2 = new WebRTCConnectionProxy(address2, sender, callId, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); }, webRTCcommandForwardingFn2) /*conn2 = new WebRTCConnection(linkupManager2, address2, sender, callId, (conn: Connection) => { expect(sender.linkupId).toEqual(address1.linkupId); expect(conn.getConnectionId()).toEqual(theCallId); });*/ conn2.setMessageCallback((message: any, _conn: Connection) => { expect(message).toEqual("hola"); conn2?.send("chau"); }); conn2.answer(message); }); let webRTCEventCallback1 = (ev: WebRTCConnectionEvent) => { conn1.connectionEventIngestFn(ev); } let connHost1 = new WebRTCConnectionsHost(webRTCEventCallback1, linkupManager1 as any as LinkupManager); let webRTCcommandForwardingFn1 = (cmd: WebRTCConnectionCommand) => { connHost1.execute(cmd); } let conn1 = new WebRTCConnectionProxy(address1, address2, theCallId, (conn: Connection) => { conn.send("hola"); }, webRTCcommandForwardingFn1) /*let _conn1 = new WebRTCConnection(linkupManager1 as any as LinkupManager, address1, address2, theCallId, (conn: Connection) => { conn.send("hola"); });*/ conn1.setMessageCallback((message: any) => { expect(message).toEqual("chau"); conn1.close(); conn2?.close(); linkupManager1Host.linkup.shutdown(); linkupManager2Host.linkup.shutdown(); done(); }); conn1.open(channelName); }, 15000); });
the_stack
import { HeatMap } from '../heatmap'; import { Rect, Size, measureText, TextOption, rotateTextSize, textTrim, CanvasTooltip, PathOption, textWrap } from '../utils/helper'; import { Axis } from './axis'; import { sum, titlePositionX, LineOption, Line, DrawSvgCanvas, TextBasic, titlePositionY, MultiLevelPosition } from '../utils/helper'; import { extend, Browser } from '@syncfusion/ej2-base'; import { TitleModel } from '../model/base-model'; import { DataModel } from '../datasource/adaptor-model'; import { MultiLevelLabels, MultiLevelCategories } from '../model/base'; export class AxisHelper { private heatMap: HeatMap; private initialClipRect: Rect; private htmlObject: HTMLElement; private element: Element; private padding: number; private drawSvgCanvas: DrawSvgCanvas; constructor(heatMap?: HeatMap) { this.heatMap = heatMap; this.padding = 10; this.drawSvgCanvas = new DrawSvgCanvas(heatMap); } /** * To render the x and y axis. * * @private */ public renderAxes(): void { this.initialClipRect = this.heatMap.initialClipRect; const heatMap: HeatMap = this.heatMap; let axisElement: Element; let element: Element; if (!heatMap.enableCanvasRendering) { axisElement = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'AxisCollection' }); } const axes: Axis[] = this.heatMap.axisCollections; for (let i: number = 0, len: number = axes.length; i < len; i++) { const axis: Axis = axes[i]; if (axis.orientation === 'Horizontal') { if (!heatMap.enableCanvasRendering) { element = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'XAxisGroup' }); } this.drawXAxisLine(element, axis); this.drawXAxisTitle(axis, element, axis.rect); this.drawXAxisLabels(axis, element, axis.rect); } else { element = heatMap.renderer.createGroup({ id: heatMap.element.id + 'YAxisGroup' }); this.drawYAxisLine(element, axis); this.drawYAxisTitle(axis, element, axis.rect); this.drawYAxisLabels(axis, element, axis.rect); } if (axis.multiLevelLabels.length > 0) { this.drawMultiLevels(element, axis); } if (!heatMap.enableCanvasRendering) { axisElement.appendChild(element); } } if (!heatMap.enableCanvasRendering) { this.heatMap.svgObject.appendChild(axisElement); } } private drawXAxisLine(parent: Element, axis: Axis): void { const y: number = this.initialClipRect.y + (!axis.opposedPosition ? this.initialClipRect.height : 0); const line: LineOption = new LineOption( this.heatMap.element.id + '_XAxisLine', new Line(this.initialClipRect.x, y, this.initialClipRect.x + this.initialClipRect.width, y), 'transparent', 0); this.drawSvgCanvas.drawLine(line, parent); } private drawYAxisLine(parent: Element, axis: Axis): void { const x: number = this.initialClipRect.x + ((!axis.opposedPosition) ? 0 : this.initialClipRect.width); const line: LineOption = new LineOption( this.heatMap.element.id + '_YAxisLine', new Line(x, this.initialClipRect.y, x, this.initialClipRect.height + this.initialClipRect.y), 'transparent', 0); this.drawSvgCanvas.drawLine(line, parent); } private drawXAxisTitle(axis: Axis, parent: Element, rect: Rect): void { const titlepadding: number = (axis.textStyle.size === '0px' ? 0 : 10); const y: number = rect.y + (!axis.opposedPosition ? (axis.maxLabelSize.height + titlepadding + sum(axis.xAxisMultiLabelHeight)) : - (axis.maxLabelSize.height + titlepadding + sum(axis.xAxisMultiLabelHeight))); if (axis.title.text) { const heatMap: HeatMap = this.heatMap; const title: TitleModel = axis.title; const elementSize: Size = measureText(title.text, title.textStyle); let padding: number = this.padding; const anchor: string = title.textStyle.textAlignment === 'Near' ? 'start' : title.textStyle.textAlignment === 'Far' ? 'end' : 'middle'; padding = axis.opposedPosition ? - (padding + elementSize.height / 4) : (padding + (3 * elementSize.height / 4)); const options: TextOption = new TextOption( heatMap.element.id + '_XAxisTitle', new TextBasic(rect.x + titlePositionX(rect.width, 0, 0, title.textStyle), y + padding, anchor, title.text), title.textStyle, title.textStyle.color || heatMap.themeStyle.axisTitle); this.drawSvgCanvas.createText(options, parent, title.text); } } private drawYAxisTitle(axis: Axis, parent: Element, rect: Rect): void { if (axis.title.text) { const title: TitleModel = axis.title; const heatMap: HeatMap = this.heatMap; const labelRotation: number = (axis.opposedPosition) ? 90 : -90; const anchor: string = title.textStyle.textAlignment === 'Near' ? 'start' : title.textStyle.textAlignment === 'Far' ? 'end' : 'middle'; let padding: number = 10; padding = axis.opposedPosition ? padding : -padding; const titlepadding: number = (axis.textStyle.size === '0px' ? 0 : padding); const x: number = rect.x + titlepadding + ((axis.opposedPosition) ? axis.maxLabelSize.width + sum(axis.yAxisMultiLabelHeight) : -(axis.maxLabelSize.width + sum(axis.yAxisMultiLabelHeight))); const y: number = rect.y + titlePositionY(rect, 0, 0, title.textStyle) + (axis.opposedPosition ? this.padding : -this.padding); const options: TextOption = new TextOption( heatMap.element.id + '_YAxisTitle', new TextBasic( x, y - this.padding, anchor, title.text, labelRotation, 'rotate(' + labelRotation + ',' + (x) + ',' + (y) + ')', 'auto'), title.textStyle, title.textStyle.color || heatMap.themeStyle.axisTitle); if (!this.heatMap.enableCanvasRendering) { this.drawSvgCanvas.createText(options, parent, title.text); } else { this.drawSvgCanvas.canvasDrawText(options, title.text, x, y); } } } /** * Get the visible labels for both x and y axis * * @private */ public calculateVisibleLabels(): void { const heatmap: HeatMap = this.heatMap; let axis: Axis; const axisCollection: Axis[] = heatmap.axisCollections; const data: DataModel = this.heatMap.dataSourceSettings; const processLabels: boolean = !(data && data.isJsonData && data.adaptorType === 'Cell'); for (let i: number = 0, len: number = axisCollection.length; i < len; i++) { axis = axisCollection[i]; if (axis.valueType === 'Numeric' && processLabels) { axis.clearAxisLabel(); axis.calculateNumericAxisLabels(this.heatMap); } else if (axis.valueType === 'DateTime' && processLabels) { axis.clearAxisLabel(); axis.calculateDateTimeAxisLabel(this.heatMap); } else if (axis.valueType === 'Category') { axis.clearAxisLabel(); axis.calculateCategoryAxisLabels(); } axis.tooltipLabels = axis.isInversed ? axis.tooltipLabels.reverse() : axis.tooltipLabels; } } /** * Measure the title and labels rendering position for both X and Y axis. * * @param rect * @private */ public measureAxis(rect: Rect): void { const heatmap: HeatMap = this.heatMap; let axis: Axis; const axisCollection: Axis[] = heatmap.axisCollections; for (let i: number = axisCollection.length - 1; i >= 0; i--) { axis = axisCollection[i]; const padding: number = axis.textStyle.size === '0px' ? 0 : this.padding; axis.nearSizes = []; axis.farSizes = []; axis.computeSize(axis, heatmap, rect); if (!axis.opposedPosition) { if (axis.orientation === 'Horizontal') { rect.height -= (sum(axis.nearSizes) + padding); } else { rect.x += sum(axis.nearSizes) + padding; rect.width -= sum(axis.nearSizes) + padding; } } else { if (axis.orientation === 'Horizontal') { rect.y += sum(axis.farSizes) + padding; rect.height -= sum(axis.farSizes) + padding; } else { rect.width -= sum(axis.farSizes) + padding; } } } } /** * Calculate the X and Y axis line position * * @param rect * @private */ public calculateAxisSize(rect: Rect): void { const heatmap: HeatMap = this.heatMap; const axisCollection: Axis[] = heatmap.axisCollections; for (let i: number = 0, len: number = axisCollection.length; i < len; i++) { const axis: Axis = axisCollection[i]; axis.rect = <Rect>extend({}, rect, null, true); if (axis.orientation === 'Horizontal' && !axis.opposedPosition) { axis.rect.y = rect.y + rect.height; axis.rect.height = 0; } if (axis.orientation === 'Vertical' && axis.opposedPosition) { axis.rect.x = rect.x + rect.width; axis.rect.width = 0; } axis.multiLevelPosition = []; for (let i: number = 0; i < axis.multiLevelLabels.length; i++) { const multiPosition: MultiLevelPosition = axis.multiPosition(axis, i); axis.multiLevelPosition.push(multiPosition); } } } private drawXAxisLabels(axis: Axis, parent: Element, rect: Rect): void { const heatMap: HeatMap = this.heatMap; let labels: string[] = axis.axisLabels; const borderWidth: number = this.heatMap.cellSettings.border.width > 5 ? (this.heatMap.cellSettings.border.width / 2) : 0; const interval: number = (rect.width - borderWidth) / axis.axisLabelSize; let compactInterval: number = 0; let axisInterval: number = axis.interval ? axis.interval : 1; let tempintervel: number = rect.width / (axis.axisLabelSize / axis.axisLabelInterval); let temp: number = axis.axisLabelInterval; if (tempintervel > 0) { while (tempintervel < parseInt(axis.textStyle.size, 10)) { temp = temp + 1; tempintervel = rect.width / (axis.axisLabelSize / temp); } } else { temp = axis.tooltipLabels.length; } if (axis.axisLabelInterval < temp) { compactInterval = temp; labels = axis.tooltipLabels; axisInterval = temp; } let y: number; let padding: number = 10; let lableStrtX: number = rect.x + (!axis.isInversed ? 0 : rect.width); let labelPadding: number; let angle: number = axis.angle; padding = this.padding; let labelElement: Element; let borderElement: Element; if (!heatMap.enableCanvasRendering) { labelElement = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'XAxisLabels' }); borderElement = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'XAxisLabelBorder' }); } if (axis.isInversed && axis.labelIntersectAction === 'MultipleRows') { axis.multipleRow.reverse(); } for (let i: number = 0, len: number = labels.length; i < len; i++) { const lableRect: Rect = new Rect(lableStrtX, rect.y, interval, rect.height); let label: string = (axis.labelIntersectAction === 'Trim' && axis.isIntersect) ? axis.valueType !== 'DateTime' || axis.showLabelOn === 'None' ? textTrim(interval * axisInterval, labels[i], axis.textStyle) : textTrim(axis.dateTimeAxisLabelInterval[i] * interval, labels[i], axis.textStyle) : labels[i]; label = axis.enableTrim ? textTrim(axis.maxLabelLength, labels[i], axis.textStyle) : label; const elementSize: Size = measureText(label, axis.textStyle); let transform: string; labelPadding = (axis.opposedPosition) ? -(padding) : (padding + ((angle % 360) === 0 ? (elementSize.height / 2) : 0)); let x: number = lableRect.x + ((!axis.isInversed) ? (lableRect.width / 2) - (elementSize.width / 2) : -((lableRect.width / 2) + (elementSize.width / 2))); if (axis.labelIntersectAction === 'Trim') { x = (!axis.isInversed) ? (x >= lableRect.x ? x : lableRect.x) : (x > (lableStrtX - interval) ? x : (lableStrtX - interval)); } else if (angle % 180 === 0) { x = x < rect.x ? rect.x : x; x = ((x + elementSize.width) > (rect.x + rect.width)) ? (rect.x + rect.width - elementSize.width) : x; } if (axis.labelIntersectAction === 'MultipleRows' && axis.labelRotation === 0) { const a: number = axis.opposedPosition ? -(axis.multipleRow[i].index - 1) : (axis.multipleRow[i].index - 1); if (axis.multipleRow[i].index > 1) { y = rect.y + labelPadding + (elementSize.height * a) + (axis.opposedPosition ? -(((elementSize.height * 0.5) / 2) * axis.multipleRow[i].index) : (((elementSize.height * 0.5) / 2) * axis.multipleRow[i].index)); } else { y = rect.y + labelPadding + (axis.opposedPosition ? - ((elementSize.height * 0.5) / 2) : ((elementSize.height * 0.5) / 2)); } } else { y = rect.y + labelPadding; } this.drawXAxisBorder(axis, borderElement, axis.rect, x, elementSize.width, i); if (angle % 360 !== 0) { angle = (angle > 360) ? angle % 360 : angle; const rotateSize: Size = rotateTextSize(axis.textStyle, <string>label, angle); x = lableRect.x + (axis.isInversed ? -(lableRect.width / 2) : (lableRect.width / 2)); y = y + (axis.opposedPosition ? -(rotateSize.height / 2) : (((angle % 360) === 180 || (angle % 360) === -180) ? 0 : (rotateSize.height) / 2)); transform = 'rotate(' + angle + ',' + x + ',' + y + ')'; } if (this.heatMap.cellSettings.border.width > 5 && axis.opposedPosition) { y = y - (this.heatMap.cellSettings.border.width / 2); } if (this.heatMap.yAxis.opposedPosition && this.heatMap.cellSettings.border.width > 5) { x = x + (this.heatMap.cellSettings.border.width / 2); } if (this.heatMap.xAxis.isInversed && this.heatMap.cellSettings.border.width > 5) { x = x - (this.heatMap.cellSettings.border.width / 2); } const options: TextOption = new TextOption( heatMap.element.id + '_XAxis_Label' + i, new TextBasic(x, y, (angle % 360 === 0) ? 'start' : 'middle', label, angle, transform), axis.textStyle, axis.textStyle.color || heatMap.themeStyle.axisLabel ); if (angle !== 0 && this.heatMap.enableCanvasRendering) { this.drawSvgCanvas.canvasDrawText(options, label); } else { this.drawSvgCanvas.createText(options, labelElement, label); } if (compactInterval === 0) { const labelInterval: number = (axis.valueType === 'DateTime' && axis.showLabelOn !== 'None') ? axis.dateTimeAxisLabelInterval[i] : axis.axisLabelInterval; lableStrtX = lableStrtX + (!axis.isInversed ? (labelInterval * interval) : -(labelInterval * interval)); } else { lableStrtX = lableStrtX + (!axis.isInversed ? (compactInterval * interval) : -(compactInterval * interval)); } if (label.indexOf('...') !== -1) { this.heatMap.tooltipCollection.push( new CanvasTooltip( labels[i], new Rect(x, y - elementSize.height, elementSize.width, elementSize.height))); } if (compactInterval !== 0) { i = i + (compactInterval - 1); } } if (!heatMap.enableCanvasRendering) { parent.appendChild(labelElement); parent.appendChild(borderElement); } } private drawYAxisLabels(axis: Axis, parent: Element, rect: Rect): void { const heatMap: HeatMap = this.heatMap; let labels: string[] = axis.axisLabels; const interval: number = rect.height / axis.axisLabelSize; let compactInterval: number = 0; let tempintervel: number = rect.height / (axis.axisLabelSize / axis.axisLabelInterval); let temp: number = axis.axisLabelInterval; let label: string; if (tempintervel > 0) { while (tempintervel < parseInt(axis.textStyle.size, 10)) { temp = temp + 1; tempintervel = rect.height / (axis.axisLabelSize / temp); } } else { temp = axis.tooltipLabels.length; } if (axis.axisLabelInterval < temp) { compactInterval = temp; labels = axis.tooltipLabels; } let padding: number = 10; let lableStartY: number = rect.y + (axis.isInversed ? 0 : rect.height); const anchor: string = axis.opposedPosition ? 'start' : 'end'; padding = axis.opposedPosition ? padding : -padding; let labelElement: Element; let borderElement: Element; if (!heatMap.enableCanvasRendering) { labelElement = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'YAxisLabels' }); borderElement = this.heatMap.renderer.createGroup({ id: heatMap.element.id + 'YAxisLabelBorder' }); } for (let i: number = 0, len: number = labels.length; i < len; i++) { const labelRect: Rect = new Rect(rect.x, lableStartY, rect.width, interval); const position: number = labelRect.height / 2; //titlePositionY(lableRect, 0, 0, axis.textStyle); const axisWidth: number = this.heatMap.cellSettings.border.width >= 20 ? (this.heatMap.cellSettings.border.width / 2) : 0; const x: number = labelRect.x + padding + (axis.opposedPosition ? axisWidth : -axisWidth); const indexValue: number = this.heatMap.cellSettings.border.width > 5 ? (((this.heatMap.cellSettings.border.width / 2) / len) * (axis.isInversed ? (i) : (len - i))) : 0; const y: number = (labelRect.y - indexValue) + (axis.isInversed ? position : -position); label = axis.enableTrim ? textTrim(axis.maxLabelLength, labels[i], axis.textStyle) : labels[i]; const options: TextOption = new TextOption( heatMap.element.id + '_YAxis_Label' + i, new TextBasic(x, y, anchor, label, 0, 'rotate(' + axis.angle + ',' + (x) + ',' + (y) + ')', 'middle'), axis.textStyle, axis.textStyle.color || heatMap.themeStyle.axisLabel); if (Browser.isIE && !heatMap.enableCanvasRendering) { options.dy = '1ex'; } this.drawSvgCanvas.createText(options, labelElement, label); if (compactInterval === 0) { const labelInterval: number = (axis.valueType === 'DateTime' && axis.showLabelOn !== 'None') ? axis.dateTimeAxisLabelInterval[i] : axis.axisLabelInterval; lableStartY = lableStartY + (axis.isInversed ? (labelInterval * interval) : -(labelInterval * interval)); } else { lableStartY = lableStartY + (axis.isInversed ? (compactInterval * interval) : -(compactInterval * interval)); i = i + (compactInterval - 1); } const elementSize: Size = measureText(label, axis.textStyle); this.drawYAxisBorder(axis, borderElement, axis.rect, y, elementSize.height, i); if (label.indexOf('...') !== -1) { const xValue: number = axis.opposedPosition ? x : (x - elementSize.width); this.heatMap.tooltipCollection.push( new CanvasTooltip( labels[i], new Rect( xValue, y - elementSize.height, elementSize.width, elementSize.height))); } } if (!heatMap.enableCanvasRendering) { parent.appendChild(labelElement); parent.appendChild(borderElement); } } private drawXAxisBorder(axis: Axis, parent: Element, rect: Rect, lableX: number, width: number, index: number): void { const interval: number = rect.width / axis.axisLabelSize; let path: string = ''; const padding: number = 10; const axisInterval: number = axis.interval ? axis.interval : 1; const startX: number = axis.isInversed ? rect.x + rect.width - (interval * index * axisInterval) : rect.x + (interval * index * axisInterval); const startY: number = rect.y; let endX: number; let endY: number; endY = startY + (axis.opposedPosition ? -(axis.maxLabelSize.height + padding) : axis.maxLabelSize.height + padding); // eslint-disable-next-line prefer-const endX = axis.isInversed ? startX - interval : startX + interval; const endY1: number = axis.isInversed ? (lableX + width + padding) : (lableX - padding); const endY2: number = axis.isInversed ? (lableX - padding) : (lableX + width + padding); switch (axis.border.type) { case 'Rectangle': path = ('M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + startY); break; case 'WithoutTopBorder': path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' '; break; case 'WithoutBottomBorder': path = 'M' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'WithoutTopandBottomBorder': path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'M' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'Brace': endY = startY + ((endY - startY) / 2) + (axis.opposedPosition ? 0 : 5); path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endY1 + ' ' + endY + ' ' + 'M' + ' ' + endY2 + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' '; break; } if (axis.border.width > 0 && axis.border.type !== 'WithoutBorder') { this.createAxisBorderElement(axis, path, parent, index); } } private drawYAxisBorder(axis: Axis, parent: Element, rect: Rect, lableY: number, height: number, index: number): void { const interval: number = rect.height / axis.axisLabelSize; let path: string = ''; const padding: number = 20; const axisInterval: number = axis.interval ? axis.interval : 1; const startX: number = rect.x; const startY: number = axis.isInversed ? rect.y + (interval * index * axisInterval) : rect.y + rect.height - (interval * index * axisInterval); let endX: number; let endY: number; endX = startX + (!axis.opposedPosition ? -(axis.maxLabelSize.width + padding) : axis.maxLabelSize.width + padding); // eslint-disable-next-line prefer-const endY = axis.isInversed ? startY + interval : startY - interval; const endY1: number = axis.isInversed ? lableY - height / 2 : lableY + height / 2; const endY2: number = axis.isInversed ? lableY + height / 2 : lableY - height / 2; switch (axis.border.type) { case 'Rectangle': path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + startY; break; case 'WithoutTopBorder': path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' '; break; case 'WithoutBottomBorder': path = 'M' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'WithoutTopandBottomBorder': path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'M' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' '; break; case 'Brace': endX = startX - (startX - endX) / 2; path = 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY1 + ' ' + 'M' + ' ' + endX + ' ' + endY2 + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY; break; } if (axis.border.width > 0 && axis.border.type !== 'WithoutBorder') { this.createAxisBorderElement(axis, path, parent, index); } } /** * To create border element for axis. * * @returns {void} * @private */ private createAxisBorderElement(axis: Axis, labelBorder: string, parent: Element, index: number): void { let canvasTranslate: Int32Array; const id: string = axis.orientation === 'Horizontal' ? '_XAxis_Label_Border' : '_YAxis_Label_Border'; const pathOptions: PathOption = new PathOption( this.heatMap.element.id + id + index, 'transparent', axis.border.width, axis.border.color, 1, 'none', labelBorder); if (!this.heatMap.enableCanvasRendering) { const borderElement: Element = this.heatMap.renderer.drawPath(pathOptions); parent.appendChild(borderElement); } else { this.heatMap.canvasRenderer.drawPath(pathOptions, canvasTranslate); } } private drawMultiLevels(parent: Element, axis: Axis): void { let element: Element; if (!this.heatMap.enableCanvasRendering) { element = this.heatMap.renderer.createGroup({ id: this.heatMap.element.id + '_' + axis.orientation + '_MultiLevelLabel' }); } if ( axis.orientation === 'Horizontal' ) { this.renderXAxisMultiLevelLabels(axis, element) ; } else{ this.renderYAxisMultiLevelLabels(axis, element); } if (!this.heatMap.enableCanvasRendering) { parent.appendChild(element); } } /** * render x axis multi level labels * * @private * @returns {void} */ public renderXAxisMultiLevelLabels(axis: Axis, parent: Element): void { let x: number = 0; let y: number; const padding: number = 10; let startX: number; let startY: number; let endX: number = 0; let tooltip: boolean; let start: number | Date; let end: number | Date; let labelSize: Size; let anchor: string; const isInversed: boolean = axis.isInversed; let labelElement: Element; const opposedPosition: boolean = axis.opposedPosition; let pathRect: string = ''; let gap: number; let textLength: number; const position: number = (isInversed ? axis.rect.width : 0) + axis.rect.x; axis.multiLevelLabels.map((multiLevel: MultiLevelLabels, level: number) => { labelElement = this.heatMap.renderer.createGroup({ id: this.heatMap.element.id + '_XAxisMultiLevelLabel' + level }); multiLevel.categories.map((categoryLabel: MultiLevelCategories, i: number) => { if (this.heatMap.theme === 'Bootstrap5' || this.heatMap.theme === 'Bootstrap5Dark') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (multiLevel as any).setProperties({ textStyle : { fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"' }}, true); } if (this.heatMap.theme === 'Tailwind' || this.heatMap.theme === 'TailwindDark') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (multiLevel as any).setProperties({ textStyle : { fontFamily: 'Inter' }}, true); } if (this.heatMap.theme === 'Fluent' || this.heatMap.theme === 'FluentDark') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (multiLevel as any).setProperties({ textStyle : { fontFamily: '"Segoe UI", -apple-system, BlinkMacSystemFont, "Roboto", "Helvetica Neue", sans-serif' }}, true); } tooltip = false; start = typeof categoryLabel.start === 'number' ? categoryLabel.start : Number(new Date(<string>categoryLabel.start)); end = typeof categoryLabel.end === 'number' ? categoryLabel.end : Number(new Date(<string>categoryLabel.end)); startX = position + this.calculateLeftPosition(axis, start, categoryLabel.start, axis.rect); startY = axis.multiLevelPosition[level].y; endX = position + this.calculateWidth(axis, categoryLabel.end, end, axis.rect); labelSize = measureText(categoryLabel.text, multiLevel.textStyle); gap = ((categoryLabel.maximumTextWidth === null) ? Math.abs(endX - startX) : categoryLabel.maximumTextWidth) - padding; y = startY + (opposedPosition ? -((axis.xAxisMultiLabelHeight[level] - labelSize.height)) : labelSize.height); x = !isInversed ? startX + padding : startX - gap; if (multiLevel.alignment === 'Center') { x = ((endX - startX) / 2) + startX; x -= (labelSize.width > gap ? gap : labelSize.width) / 2; } else if (multiLevel.alignment === 'Far') { x = !isInversed ? endX - padding : startX - padding; x -= (labelSize.width > gap ? gap : labelSize.width); } else { x = !isInversed ? startX + padding : endX + padding; } if (multiLevel.overflow === 'None' && labelSize.width > Math.abs(endX - startX)) { x = !isInversed ? startX + padding : startX - labelSize.width - padding; anchor = 'start'; } const textBasic: TextBasic = new TextBasic( x, y, anchor, categoryLabel.text, 0, 'translate(0,0)'); const options: TextOption = new TextOption( this.heatMap.element.id + '_XAxis_MultiLevel' + level + '_Text' + i, textBasic, multiLevel.textStyle, multiLevel.textStyle.color || this.heatMap.themeStyle.axisLabel); if (multiLevel.overflow === 'Wrap') { options.text = textWrap(categoryLabel.text, gap, multiLevel.textStyle); textLength = options.text.length; } else if (multiLevel.overflow === 'Trim') { options.text = textTrim(gap, categoryLabel.text, multiLevel.textStyle); textLength = 1; } if (multiLevel.overflow === 'Wrap' && options.text.length > 1) { this.drawSvgCanvas.createWrapText(options, multiLevel.textStyle, labelElement); for (let i: number = 0; i < options.text.length; i++) { if (options.text[i].indexOf('...') !== -1) { tooltip = true; break; } } } else { this.drawSvgCanvas.createText(options, labelElement, options.text); } if (!this.heatMap.enableCanvasRendering) { parent.appendChild(labelElement); } if (options.text.indexOf('...') !== -1 || options.text[0].indexOf('...') !== -1 || tooltip) { this.heatMap.tooltipCollection.push( new CanvasTooltip( categoryLabel.text, new Rect(x, y - labelSize.height, gap, labelSize.height * textLength))); } if (multiLevel.border.width > 0 && multiLevel.border.type !== 'WithoutBorder') { pathRect = this.renderXAxisLabelBorder( level, axis, startX, startY, endX, pathRect, level, labelSize, gap, x ); } }); if (pathRect !== '') { this.createBorderElement(level, axis, pathRect, parent); pathRect = ''; } }); if (!this.heatMap.enableCanvasRendering) { parent.appendChild(labelElement); } } /** * render x axis multi level labels border * * @private * @returns {void} */ private renderXAxisLabelBorder( labelIndex: number, axis: Axis, startX: number, startY: number, endX: number, path: string, level: number, labelSize: Size, gap: number, x: number): string { let path1: number; let path2: number; const endY: number = startY + (axis.opposedPosition ? - (axis.xAxisMultiLabelHeight[labelIndex]) : axis.xAxisMultiLabelHeight[labelIndex]); const padding: number = 3; switch (axis.multiLevelLabels[level].border.type) { case 'Rectangle': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' '; break; case 'WithoutTopBorder': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' '; break; case 'WithoutBottomBorder': path += 'M' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'WithoutTopandBottomBorder': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'M' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'Brace': path1 = axis.isInversed ? (labelSize.width > gap ? gap : labelSize.width) + x + padding : x - padding; path2 = axis.isInversed ? x - padding : (labelSize.width > gap ? gap : labelSize.width) + x + padding; path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + (startY + (endY - startY) / 2) + ' ' + 'L' + ' ' + path1 + ' ' + (startY + (endY - startY) / 2) + ' ' + 'M' + ' ' + path2 + ' ' + (startY + (endY - startY) / 2) + ' ' + 'L' + ' ' + endX + ' ' + (startY + (endY - startY) / 2) + ' ' + 'L' + ' ' + endX + ' ' + startY + ' '; break; } return path; } /** * render y axis multi level labels * * @private * @returns {void} */ public renderYAxisMultiLevelLabels(axis: Axis, parent: Element): void { let x: number = 0; let y: number; const padding: number = 10; let startX: number; let startY: number; let endY: number; let start: number | Date; let end: number | Date; let labelSize: Size; const isInversed: boolean = axis.isInversed; let labelElement: Element; let pathRect: string = ''; let gap: number; let text: string | string[]; const position: number = (!isInversed ? axis.rect.height : 0) + axis.rect.y; axis.multiLevelLabels.map((multiLevel: MultiLevelLabels, level: number) => { startY = axis.multiLevelPosition[level].y; labelElement = this.heatMap.renderer.createGroup({ id: this.heatMap.element.id + '_YAxisMultiLevelLabel' + level }); multiLevel.categories.map((categoryLabel: MultiLevelCategories, i: number) => { if (this.heatMap.theme === 'Tailwind' || this.heatMap.theme === 'TailwindDark') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (multiLevel as any).setProperties({ textStyle : { fontFamily: 'Inter' }}, true); } if (this.heatMap.theme === 'Bootstrap5' || this.heatMap.theme === 'Bootstrap5Dark') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (multiLevel as any).setProperties({ textStyle : { fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"' }}, true); } start = typeof categoryLabel.start === 'number' ? categoryLabel.start : Number(new Date(<string>categoryLabel.start)); end = typeof categoryLabel.end === 'number' ? categoryLabel.end : Number(new Date(<string>categoryLabel.end)); startY = position + this.calculateLeftPosition(axis, start, categoryLabel.start, axis.rect); startX = axis.multiLevelPosition[level].x; endY = position + this.calculateWidth(axis, categoryLabel.start, end, axis.rect); labelSize = measureText(categoryLabel.text, multiLevel.textStyle); gap = ((categoryLabel.maximumTextWidth === null) ? Math.abs(startX) : categoryLabel.maximumTextWidth) - padding; const maxWidth: number = Math.abs(startX - (startX - axis.multiLevelSize[level].width - 2 * padding)) / 2 - (labelSize.width / 2); x = (axis.opposedPosition ? startX : startX - axis.multiLevelSize[level].width - 2 * padding) + maxWidth; y = startY + padding; if (multiLevel.overflow !== 'None') { if (multiLevel.overflow === 'Wrap') { text = textWrap(categoryLabel.text, gap, multiLevel.textStyle); } else { text = textTrim(gap, categoryLabel.text, multiLevel.textStyle); } } if (multiLevel.alignment === 'Center') { y += ((endY - startY) / 2 - (text.length * labelSize.height) / 2); } else if (multiLevel.alignment === 'Far') { y = isInversed ? endY - labelSize.height / 2 : y - labelSize.height; } else { y = isInversed ? y + labelSize.height / 2 : endY + labelSize.height; } if (multiLevel.border.width > 0 && multiLevel.border.type !== 'WithoutBorder') { pathRect = this.renderYAxisLabelBorder(level, axis, startX, startY, endY, pathRect, level, labelSize, gap, y); } const textBasic: TextBasic = new TextBasic( x, y, 'start', categoryLabel.text, 0, 'translate(0,0)'); const options: TextOption = new TextOption( this.heatMap.element.id + '_YAxis_MultiLevel' + level + '_Text' + i, textBasic, multiLevel.textStyle, multiLevel.textStyle.color || this.heatMap.themeStyle.axisLabel); options.text = text; this.drawSvgCanvas.createText(options, labelElement, options.text); if (options.text.indexOf('...') !== -1) { this.heatMap.tooltipCollection.push( new CanvasTooltip( categoryLabel.text, new Rect(x, y - labelSize.height, gap, labelSize.height))); } if (!this.heatMap.enableCanvasRendering) { parent.appendChild(labelElement); } }); if (pathRect !== '') { this.createBorderElement(level, axis, pathRect, parent); pathRect = ''; } }); if (!this.heatMap.enableCanvasRendering) { parent.appendChild(labelElement); } } /** * render x axis multi level labels border * * @private * @returns {void} */ private renderYAxisLabelBorder( labelIndex: number, axis: Axis, startX: number, startY: number, endY: number, path: string, level: number, labelSize: Size, gap: number, y: number): string { let padding: number = 20; let path1: number; let path2: number; const endX: number = startX - (axis.opposedPosition ? -(axis.multiLevelSize[labelIndex].width + padding) : (axis.multiLevelSize[labelIndex].width + padding)); switch (axis.multiLevelLabels[level].border.type) { case 'Rectangle': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' '; break; case 'WithoutTopBorder': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' '; break; case 'WithoutBottomBorder': path += 'M' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'WithoutTopandBottomBorder': path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + startY + ' ' + 'M' + ' ' + startX + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' '; break; case 'Brace': padding = 10; path1 = axis.isInversed ? (y - padding - 5) : (y + (labelSize.height) - padding); path2 = axis.isInversed ? (y + (labelSize.height) - padding) : (y - padding - 5); path += 'M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + (startX + (endX - startX) / 2) + ' ' + startY + ' ' + 'L' + ' ' + (startX + (endX - startX) / 2) + ' ' + path1 + ' ' + 'M' + ' ' + (startX + (endX - startX) / 2) + ' ' + path2 + ' ' + 'L' + ' ' + (startX + (endX - startX) / 2) + ' ' + endY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' '; break; } return path; } /** * create borer element * * @returns {void} * @private */ public createBorderElement(borderIndex: number, axis: Axis, path: string, parent: Element): void { let canvasTranslate: Int32Array; const id: string = axis.orientation === 'Horizontal' ? 'XAxis' : 'YAxis'; const pathOptions: PathOption = new PathOption( this.heatMap.element.id + '_' + id + '_MultiLevel_Rect_' + borderIndex, 'Transparent', axis.multiLevelLabels[borderIndex].border.width, axis.multiLevelLabels[borderIndex].border.color, 1, '', path ); const borderElement: Element = this.heatMap.renderer.drawPath(pathOptions) as HTMLElement; if (!this.heatMap.enableCanvasRendering) { parent.appendChild(borderElement); } else { this.heatMap.canvasRenderer.drawPath(pathOptions, canvasTranslate); } } /** * calculate left position of border element * * @private */ public calculateLeftPosition(axis: Axis, start: number, label: number | Date | string, rect: Rect): number { let value: number; let interval: number; if (typeof label === 'number') { if (axis.valueType === 'Numeric' && (axis.minimum || axis.maximum)) { const min: number = axis.minimum ? <number>axis.minimum : 0; start -= min; } const size: number = axis.orientation === 'Horizontal' ? rect.width : rect.height; interval = size / (axis.axisLabelSize * axis.increment); value = (axis.isInversed ? -1 : 1) * start * interval; value = axis.orientation === 'Horizontal' ? value : -value; } else { interval = this.calculateNumberOfDays(start, axis, true, rect); value = axis.isInversed ? -interval : interval; value = axis.orientation === 'Horizontal' ? value : -value; } return value; } /** * calculate width of border element * * @private */ public calculateWidth(axis: Axis, label: number | Date | string, end: number, rect: Rect): number { let interval: number; let value: number; if (typeof label === 'number') { if (axis.valueType === 'Numeric' && (axis.minimum || axis.maximum)) { const min: number = axis.minimum ? <number>axis.minimum : 0; end -= min; } const size: number = axis.orientation === 'Horizontal' ? rect.width : rect.height; interval = size / (axis.axisLabelSize * axis.increment); value = (axis.isInversed ? -1 : 1) * (end + 1) * interval; value = axis.orientation === 'Horizontal' ? value : -value; } else { interval = this.calculateNumberOfDays(end, axis, false, rect); value = interval; value = axis.isInversed ? -value : value; value = axis.orientation === 'Horizontal' ? value : -value; } return value; } private calculateNumberOfDays(date: number, axis: Axis, start: boolean, rect: Rect): number { const oneDay: number = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds const oneMinute: number = 60 * 1000; let firstDate: Date; let secondDate: Date; const labels: (string | number | Date)[] = axis.labelValue; let position: number; const interval: number = (axis.orientation === 'Horizontal' ? rect.width : rect.height) / axis.axisLabelSize; const givenDate: Date = new Date(Number(date)); let days: number = 0; for (let index: number = 0; index < axis.axisLabelSize; index++) { firstDate = new Date(Number(labels[index])); secondDate = axis.isInversed ? new Date(Number(labels[index - 1])) : new Date(Number(labels[index + 1])); if (index === (axis.isInversed ? 0 : axis.axisLabelSize - 1)) { secondDate = new Date(Number(labels[index])); if (axis.intervalType === 'Hours') { secondDate = new Date(Number(secondDate.setHours(secondDate.getHours() + 1))); } else if ((axis.intervalType === 'Minutes')) { secondDate = new Date(Number(secondDate.setMinutes(secondDate.getMinutes() + 1))); } else if ((axis.intervalType === 'Days')) { secondDate = new Date(Number(secondDate.setDate(secondDate.getDate() + 1))); } else { const numberOfDays: number = axis.intervalType === 'Months' ? new Date(secondDate.getFullYear(), secondDate.getMonth() + 1, 0).getDate() : secondDate.getFullYear() % 4 === 0 ? 366 : 365; secondDate = new Date(Number(secondDate.setDate(secondDate.getDate() + numberOfDays))); } } if (Number(firstDate) <= date && Number(secondDate) >= date) { if (axis.intervalType === 'Minutes' || axis.intervalType === 'Hours') { const totalMinutes: number = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneMinute))); const minutesInHours: number = Math.abs((firstDate.getTime() - givenDate.getTime()) / (oneMinute)); days = (interval / totalMinutes) * minutesInHours; index = axis.isInversed ? axis.axisLabelSize - 1 - index : index; position = index * interval + days; break; } else { const numberOfDays: number = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay))); // eslint-disable-next-line start ? givenDate.getDate() : givenDate.setDate(givenDate.getDate() + 1); if (numberOfDays !== 0) { days = (interval / numberOfDays) * (Math.abs((firstDate.getTime() - givenDate.getTime()) / (oneDay))); } index = axis.isInversed ? axis.axisLabelSize - 1 - index : index; position = index * interval + days; break; } } } return position; } }
the_stack
import { Scene, Map, Tile, Dom, SimpleText, AudioManager as AM, Deferred } from "athenajs"; import Shape from "./shape"; import FlashLines from "./flash_lines"; // size constants const MAP_ROWS = 22; const MAP_COLS = 12; const TILE_WIDTH = 20; const TILE_HEIGHT = 20; // tile offsets in the spritesheet const MAP_TILES_OFFSET_Y = 440; const WALL_TILE_OFFSET_X = 140; const BACK_TILE_OFFSET_X = 160; // wall tile number const WALL_TILE = 8; // game width const TOTAL_WIDTH = 800; const TOTAL_HEIGHT = 600; // speed (drop delay) at start const START_TIMING = 1200; // speed increase at each level const LEVEL_TIMING = 55; class Grid extends Scene { // game parameters score: number; level: number; timing: number; lines: number; scoreTable: number[]; // game sprites // current tetris shape shape: Shape; // next tetris shape nextShape: Shape; // next tetris string nextString: SimpleText; // score scoreString: SimpleText; // "line:" linesString: SimpleText; // "level:" levelString: SimpleText; // "pause:" pauseString: SimpleText; // flashing lines flashLines: FlashLines; // ->, <- controls: SimpleText; constructor() { super({ resources: [ { id: "tiles", type: "image", src: "img/tetris_tiles.png" }, { id: "gameover", type: "audio", src: "sound/gameover.mp3" }, { id: "ground", type: "audio", src: "sound/ground.mp3" }, { id: "level", type: "audio", src: "sound/level.mp3" }, { id: "lines", type: "audio", src: "sound/lines.mp3" }, { id: "lines_tetris", type: "audio", src: "sound/lines_tetris.mp3" }, { id: "move", type: "audio", src: "sound/move.mp3" }, { id: "pause", type: "audio", src: "sound/pause.mp3" }, { id: "rotate", type: "audio", src: "sound/rotate.mp3" } ] }); // here we keep game-related properties this.score = 0; this.level = 0; this.lines = 0; this.timing = START_TIMING; this.scoreTable = [40, 100, 300, 1200]; // we only need to catch the 'ground' event from the 'shape' element this.bindEvents("shape:ground"); } /** * Generate tileset for the tetris map, mostly hardcoded stuff * */ generateTileSet() { // create the list of all tiles for the map const tiles = [ { offsetX: WALL_TILE_OFFSET_X, offsetY: MAP_TILES_OFFSET_Y, width: TILE_WIDTH, height: TILE_HEIGHT } ]; // add a tile for each color for (let i = 0, offset = 0; i < 7; ++i, offset += TILE_WIDTH) { tiles.push({ offsetX: offset, offsetY: MAP_TILES_OFFSET_Y, width: TILE_WIDTH, height: TILE_HEIGHT }); } tiles.push({ offsetX: BACK_TILE_OFFSET_X, offsetY: MAP_TILES_OFFSET_Y, width: TILE_WIDTH, height: TILE_HEIGHT }); return tiles; } /** * Generates the map of the game, adding walls around the playground */ createMap() { // first create the map with an empty buffer const map = new Map({ src: "tiles", tileWidth: TILE_WIDTH, tileHeight: TILE_WIDTH, width: TILE_WIDTH * MAP_COLS, height: TILE_HEIGHT * MAP_ROWS, buffer: new ArrayBuffer(MAP_COLS * MAP_ROWS * 2) }); // finally add the tileset map.addTileSet(this.generateTileSet()); return map; } resetMap() { const map = this.map; map.clear(0, Tile.TYPE.AIR); // set map tiles around the playground as wall tiles for (let i = 0; i < map.numRows; ++i) { map.updateTile(0, i, WALL_TILE, Tile.TYPE.WALL); map.updateTile(map.numCols - 1, i, WALL_TILE, Tile.TYPE.WALL); } for (let i = 0; i < map.numCols; ++i) { map.updateTile(i, map.numRows - 1, WALL_TILE, Tile.TYPE.WALL); } } /** * Generates the tile sprite that will be moved by the player */ createShapes() { this.shape = new Shape("shape", { data: { speed: this.timing } }); this.nextShape = new Shape("nextShape", { x: 610, y: 110 }); this.nextShape.movable = false; this.nextString = new SimpleText("nextString", { text: "Next", x: 620, y: 70 }); this.scoreString = new SimpleText("scoreString", { text: "Score: 0", x: 50, y: 70 }); this.linesString = new SimpleText("linesString", { text: "Lines: 0", x: 50, y: 120 }); this.levelString = new SimpleText("levelString", { text: "Level: 0", x: 50, y: 170 }); this.pauseString = new SimpleText("pauseString", { text: "Pause", x: 380, y: 550, visible: false }); this.controls = new SimpleText("controlsString", { text: "Controls:\narrow keys", x: 50, y: 220 }); this.flashLines = new FlashLines("flash", { x: (TOTAL_WIDTH - TILE_WIDTH * MAP_COLS) / 2 + TILE_WIDTH, y: (TOTAL_HEIGHT - TILE_HEIGHT * MAP_ROWS) / 2, width: TILE_WIDTH * (MAP_COLS - 2), lineHeight: TILE_HEIGHT }); } /** * Called when the scene is ready: generates the map and adds the player's shape * sprite onto the screen */ setup() { this.createShapes(); this.map = this.createMap(); } start() { const map = this.map; this.setBackgroundImage("img/background.png"); // center map this.setMap( map, (TOTAL_WIDTH - map.width) / 2, (TOTAL_HEIGHT - map.height) / 2 ); map.addObject(this.shape); this.addObject([ this.nextShape, this.nextString, this.linesString, this.scoreString, this.levelString, this.pauseString, this.flashLines, this.controls ]); this.reset(); } reset() { this.score = 0; this.level = 0; this.lines = 0; this.timing = START_TIMING; this.resetMap(); this.shape.moveToTop(); this.shape.setRandomShape(); this.nextShape.setRandomShape(); this.linesString.setText("Lines: " + this.lines); this.scoreString.setText("Score: " + this.score); this.levelString.setText("Level: " + this.level); this.shape.movable = true; this.shape.behavior.reset(); } /** * Called on game over, simply displays the score in an alert box and restarts the game */ gameover() { AM.play("gameover"); alert("game over!" + this.score); this.reset(); } /** * This method is called whenever an event that has been registered is received * */ onEvent(event: any) { const nextShape = this.nextShape; const shape = this.shape; switch (event.type) { case "shape:ground": // update the map with the new shape this.updateMap(); // check for lines to remove this.removeLinesFromMap( event.data.startLine, event.data.numRows ).then(() => { shape.setShape(nextShape.shapeName, nextShape.rotation); nextShape.setRandomShape(); this.shape.moveToTop(); // we may have a game over here: if the shape collides with another one if (!this.shape.snapTile(0, 0, false)) { this.gameover(); } else { this.shape.movable = true; } }); break; } } /** * This method is called when a shape has reached the ground: in this case * we simply update the map using the shape's matrix */ updateMap() { const shape = this.shape; const data = this.shape.shape; const map = this.map; const pos = map.getTileIndexFromPixel(shape.x, shape.y); const buffer = shape.getMatrix(); const rows = data.height / map.tileHeight; const cols = data.width / map.tileWidth; for (let j = 0; j < rows; ++j) { for (let i = 0; i < cols; ++i) { if (buffer[j * cols + i]) { map.updateTile(pos.x + i, pos.y + j, data.color, Tile.TYPE.WALL); } } } } /** * returns the number of lines that contains no hole, starting from * startLine up to startLine + height * */ getLinesToRemove(startLine: number, height: number): number[] { console.log("[Grid] getLinesToRemove()"); const map = this.map; const lines: number[] = []; let lastLine = startLine + height - 1; // avoid bottom ground if (lastLine > map.numRows - 2) lastLine = map.numRows - 2; for (let j = lastLine; j >= startLine; --j) { let hole = false; for (let i = 1; i < map.numCols - 1; ++i) { hole = hole || map.getTileBehaviorAtIndex(i, j) !== Tile.TYPE.WALL; } if (!hole) { lines.push(j); } } return lines; } /** * Updates level + level object's text */ updateLevel() { const oldLevel = this.level; this.level = Math.floor(this.lines / 10); this.levelString.setText("Level: " + this.level); this.timing = START_TIMING - this.level * LEVEL_TIMING; this.shape.data['speed'] = this.timing; oldLevel !== this.level && AM.play("level"); } /** * Updates the player's score using line number & current level * */ increaseScore(lines: number) { this.score += this.scoreTable[lines - 1] + this.level * this.scoreTable[lines - 1]; this.lines += lines; this.linesString.setText("Lines: " + this.lines); this.scoreString.setText("Score: " + this.score); if (lines === 4) { AM.play("lines_tetris"); } else { AM.play("lines"); } } /** * Removes lines from the map, shifting the map as needed, and adding * empty tiles at the top * */ removeLinesFromMap(startLine: number, height: number) { const map = this.map; const lines = this.getLinesToRemove(startLine, height); // no full lines detected if (!lines.length) { return Deferred.resolve(true); } this.flashLines.lines = lines; return this.flashLines.flash().then(() => { // shift the map for each line to remove for (let i = 0; i < lines.length; ++i) { map.shift(lines[i] + i, 1); } // add wall at each side of the new lines for (let i = 0; i < height; ++i) { for (let j = 0; j < map.numCols; ++j) { map.updateTile(j, i, 0, Tile.TYPE.AIR); } map.updateTile(0, i, 8, Tile.TYPE.WALL); map.updateTile(map.numCols - 1, i, 8, Tile.TYPE.WALL); } Dom('.athena-game').addClass('shake-vertical shake-constant'); setTimeout(() => { Dom('.athena-game').removeClass('shake-vertical shake-constant'); }, 300); this.increaseScore(lines.length); this.updateLevel(); }); } pause(isRunning: boolean) { this.pauseString.visible = !isRunning; AM.play("pause"); } } export default Grid;
the_stack
import { Component } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ViewController, NavParams, AlertController, ActionSheetController, LoadingController, PopoverController } from 'ionic-angular'; import { Myki } from '../../models/myki'; import { MykiProvider } from '../../providers/myki'; import { ConfigProvider } from '../../providers/config'; import { FarePricesPage } from '../fare-prices/fare-prices'; import * as $ from "jquery"; import '../../libs/jquery.payment.js'; import moment from 'moment'; import { CreditCard } from '../../models/creditCard'; import { SocialSharing } from '@ionic-native/social-sharing'; @Component({ selector: 'page-topup', templateUrl: 'topup.html' }) export class TopupPage { public state: TopUpState = TopUpState.Form public topupOptions: Myki.TopupOptions = new Myki.TopupOptions() public loadingTopUp: boolean = false; public loadingPay: boolean = false; public formTopupMoney: FormGroup; public formTopupPass: FormGroup; public formTopupPayCC: FormGroup; public formTopupPayReminder: FormGroup; public topupOrder: Myki.TopupOrder = new Myki.TopupOrder() public transactionReference: string; public topupMoneyCustom: boolean = false; public topupPassCustom: boolean = false; public canSaveCreditCard: boolean = false; public hasSavedCreditCard: boolean = false; constructor( public viewCtrl: ViewController, public navParams: NavParams, public mykiProvider: MykiProvider, public configProvider: ConfigProvider, public alertCtrl: AlertController, public formBuilder: FormBuilder, public actionSheetCtrl: ActionSheetController, public loadingCtrl: LoadingController, public popoverCtrl: PopoverController, public socialSharing: SocialSharing ) { // get topup type from navigation parameter this.topupOptions.topupType = navParams.get('type') // initialize form groups this.formTopupMoney = formBuilder.group({ moneyAmount: ['', [ Validators.required, this.validateMoneyAmount ]] }) this.formTopupPass = formBuilder.group({ // field validation passDuration: ['', [ Validators.required, this.validatePassDuration ]], zoneFrom: ['', [ Validators.required ]], zoneTo: ['', [ Validators.required ]], }, { // form validators validator: this.validateZones() }) this.formTopupPayCC = formBuilder.group({ card: ['', [ this.validateCCNumber ]], expiry: ['', [ this.validateCCExpiry ]], cvc: ['', [ Validators.required ]], }, { validator: this.validateCreditCard() }) /* Disabled because myki is so fucked no matter what receipt option you choose or what email you enter, it will always the receipt to the account email Who cares about free choice right? */ /* this.formTopupPayReminder = formBuilder.group({ reminderType: ['', [ Validators.required ]], reminderEmail: [''], reminderMobile: [''], }, { // group validators validator: this.validateReminder() }) */ } ionViewDidLoad() { // defaults this.topupOptions.moneyAmount = 10 this.topupOptions.passDuration = 7 this.topupOptions.zoneFrom = 1 this.topupOptions.zoneTo = 2 this.topupOptions.reminderType = Myki.TopupReminderType.Email // check if we can save credit card this.configProvider.hasSecureStorage().then(result => { if (result) { this.canSaveCreditCard = true; // check saved credit card this.configProvider.creditCardGet().then( card => { // if no card stored, early exit if (!card) return; // load saved credit card this.topupOptions.creditCard = card // we probably want to save details again this.topupOptions.saveCreditCard = true // set we have a saved credit card state (changes UI) this.hasSavedCreditCard = true; }, error => { // no saved credit card // no op } ) } }); // initialize top up this.loadingTopUp = true; this.mykiProvider.topupCardLoad(this.topupOptions).then( result => { // log event (<any>window).FirebasePlugin.logEvent("begin_checkout", {}) this.loadingTopUp = false }, error => { // show error let alert = this.alertCtrl.create({ title: 'Error loading top up', subTitle: 'Top up functionality is not available. Please check the myki website.', buttons: ['OK'], enableBackdropDismiss: false, }) alert.present() // close modal this.viewCtrl.dismiss() } ) // set up payment fields $('ion-input.ccNumber input').payment('formatCardNumber') $('ion-input.ccExpiry input').payment('formatCardExpiry') $('ion-input.ccCVC input').payment('formatCardCVC') // handle credit card ENTER behavior $("ion-input.ccNumber input").on('keydown', (e) => { if (e.which == 13) { // focus to expiry $("ion-input.ccExpiry input").focus() } }) // handle expiry ENTER behavior $("ion-input.ccExpiry input").on('keydown', (e) => { if (e.which == 13) { // focus to CVC $("ion-input.ccCVC input").focus() } }) } public close() { this.viewCtrl.dismiss() } public title() { return `Top up ${this.topupOptions.topupType === Myki.TopupType.Money ? 'money' : 'pass'}` } public isTopupMoney() { return this.topupOptions.topupType === Myki.TopupType.Money } public isTopupPass() { return this.topupOptions.topupType === Myki.TopupType.Pass } public topupMoneyIs(amount: number) { return this.topupOptions.moneyAmount === amount } public topupMoneySet(amount: number) { this.topupOptions.moneyAmount = amount } public topupPassExpiryDate() { return moment().add(this.topupOptions.passDuration, 'days'); } public customTopupMoney() { this.topupMoneyCustom = true; $("input[name=moneyAmount]").focus() } public topupPassIs(duration: number) { return this.topupOptions.passDuration === duration } public topupPassSet(duration: number) { this.topupOptions.passDuration = duration } public customTopupPass() { this.topupPassCustom = true; $("input[name=passDuration]").focus() } public zoneFromOptions = { title: 'From zone', }; public zoneToOptions = { title: 'To zone', }; public zoneSelect() { // currently max zones 13 https://static.ptv.vic.gov.au/siteassets/PDFs/Maps/Network-maps/Regional-Network-Map_myki-zones_connections.pdf return Array.apply(null, { length: 13 }).map(function (value, index) { return (index + 1); }); } // open fare prices popover public farePrices(event) { let popover = this.popoverCtrl.create(FarePricesPage); popover.present({ ev: event }); } public canOrder() { return (this.isTopupMoney() && this.formTopupMoney.valid) || (this.isTopupPass() && this.formTopupPass.valid) } public order() { // if either of the forms are invalid if ( (this.isTopupMoney() && !this.formTopupMoney.valid) || (this.isTopupPass() && !this.formTopupPass.valid) ) { // show error let alert = this.alertCtrl.create({ title: 'Top up error', subTitle: 'Please correct the top up errors', buttons: ['OK'], enableBackdropDismiss: false, }) alert.present() } // go to pay state this.loadingPay = true; // add loading this.state = TopUpState.Pay // set the page state // submit the order this.mykiProvider.topupCardOrder(this.topupOptions).then( result => { this.loadingPay = false; // remove loading this.topupOrder = result; // store the top up order we get back // log event (<any>window).FirebasePlugin.logEvent("add_to_cart", { "item_category": this.topupOptions.topupType.toString(), "item_id": `topup-${this.topupOptions.topupType}`, "item_name": this.topupOrder.description, "quantity": 1, "price": this.topupOrder.amount, "currency": "AUD", "value": this.topupOrder.amount }) }, error => { // show error let alert = this.alertCtrl.create({ title: 'Error ordering top up', subTitle: 'Please check your top up options', buttons: ['OK'], enableBackdropDismiss: false }) alert.present() // reset state this.state = TopUpState.Form } ) } public stateForm() { return this.state === TopUpState.Form } public statePay() { return this.state === TopUpState.Pay } public stateSuccess() { return this.state === TopUpState.Success } public canPay() { return (this.formTopupPayCC.valid //&& this.formTopupPayReminder.valid ) } public pay() { let actionSheet = this.actionSheetCtrl.create({ title: 'Confirm top up', buttons: [ { text: `Pay $${this.topupOrder.amount}`, role: 'destructive', handler: () => { // start paying process this.confirmPay() } }, { text: 'Cancel', role: 'cancel', } ] }); actionSheet.present(); } private confirmPay() { let loading = this.loadingCtrl.create({ spinner: 'crescent', content: 'Paying...' }); loading.present(); this.mykiProvider.topupCardPay(this.topupOptions).then( result => { // log event (<any>window).FirebasePlugin.logEvent("ecommerce_purchase", { "currency": "AUD", "value": this.topupOrder.amount }) // successfully topped up loading.dismiss() // dismiss loading throbber this.state = TopUpState.Success // set the page state this.transactionReference = result // update transaction reference // determine if we need to save credit card details if (this.topupOptions.saveCreditCard) { // save credit card this.configProvider.creditCardSave(this.topupOptions.creditCard); } else { // we might want to forget credit card // let's just do it anyway this.configProvider.creditCardForget(); } // if top up is a myki pass and balance is low, give a warning if (this.topupOptions.topupType === Myki.TopupType.Pass) { let alert = this.alertCtrl.create({ title: 'Myki pass might take up to 24 hours to activate', message: 'Myki appears to be slow to process online pass top ups, sometimes up to 24 hours.<br><br>Reminder to activate your myki pass, you need a positive myki money balance.', buttons: ['OK'], enableBackdropDismiss: false, }) alert.present() } }, error => { // error with payment // myki's site shits the fan and doesn't allow the user to do anything with the top up now // to workaround it we're going to set up a new myki topup with the same options we already have this.mykiProvider.topupCardLoad(this.topupOptions).then(() => { return this.mykiProvider.topupCardOrder(this.topupOptions) }).catch(() => { // something went wrong when we're reloading the top up // time to give up and send user back to the home screen loading.dismiss() // dismiss loading throbber let alert = this.alertCtrl.create({ title: 'Error topping up', subTitle: 'An error occured while submitting your top up.', message: 'myki/PTV may be having server issues. Try again later.', buttons: ['OK'], enableBackdropDismiss: false, }) alert.present() this.close() // close modal throw new Error() // throwing so we're not continuing the promise }).then(() => { loading.dismiss() // show error let alert = this.alertCtrl.create({ title: 'Error topping up', subTitle: 'Your credit card may have been declined by myki/PTV', message: 'Verify your credit card details.<br><br>myki/PTV does not seem to accept international credit cards or debit cards to top up online, you have to use a machine.<br><br>Declined transactions may be deducted from your bank account temporarily and are usually automatically refunded within 5 business days.', buttons: ['OK'], enableBackdropDismiss: false, }) alert.present() }).catch(() => { // noop handled earlier }) } ) } public isReminderEmail() { return this.topupOptions.reminderType === Myki.TopupReminderType.Email } public isReminderMobile() { return this.topupOptions.reminderType === Myki.TopupReminderType.Mobile } public changeSavedCreditCard() { this.hasSavedCreditCard = false this.topupOptions.creditCard = new CreditCard() } public shareTopup() { this.socialSharing.share("I just used the free MyPal app to top up my myki on the go", "MyPal myki app", "", "https://longzheng.github.io/mypal-ionic/") } private validatePassDuration(control: FormControl) { let duration = control.value; if ( isNaN(duration) || duration < 7 || (duration > 7 && duration < 28) || duration > 365 ) return { invalidPassDuration: true } return null } private validateMoneyAmount(control: FormControl) { let amount = control.value; if ( isNaN(amount) || amount % 1 !== 0 || amount < 10 || amount > 250 ) return { invalidMoneyAmount: true } return null } private validateZones() { return (group: FormGroup): any => { let zoneFrom = parseInt(group.controls['zoneFrom'].value) let zoneTo = parseInt(group.controls['zoneTo'].value) if (zoneFrom > zoneTo) return { invalidZones: true } if (zoneTo === 1) return { zoneToInvalid: true } return null } } private validateCCNumber(control: FormControl) { if (!$.payment.validateCardNumber(control.value)) return { invalidNumber: true } return null } private validateCCExpiry(control: FormControl) { let expiry = $.payment.cardExpiryVal(control.value !== undefined ? control.value : '') // can't validate undefined, so pass in empty string if (!$.payment.validateCardExpiry(expiry.month.toString(), expiry.year.toString())) return { invalidExpiry: true } return null } private validateCreditCard() { return (group: FormGroup): any => { let cardNumber = group.controls['card'].value let cardCVC = group.controls['cvc'].value let cardType = $.payment.cardType(cardNumber) if (cardNumber && !(cardType === 'visa' || cardType === 'mastercard')) return { invalidCardType: true } if (!$.payment.validateCardCVC(cardCVC, cardType)) return { invalidCVC: true } return null } } private validateReminder() { return (group: FormGroup) => { let reminderType = group.controls['reminderType'].value let reminderEmail = group.controls['reminderEmail'].value let reminderMobile = group.controls['reminderMobile'].value // If reminder is email if (reminderType === Myki.TopupReminderType.Email) if (!reminderEmail) // If not filled, return required error return { emailRequired: true } else // If filled, validate email return Validators.email(group.controls['reminderEmail']) if (reminderType === Myki.TopupReminderType.Mobile && !reminderMobile) return { mobileRequired: true } return null } } } export enum TopUpState { Form, Pay, Success }
the_stack
import * as secp from "noble-secp256k1"; import { HDKey } from "../../src/hdkey"; import { hexToBytes, toHex } from "../../src/utils"; import { deepStrictEqual, throws } from "./assert"; // https://github.com/cryptocoinjs/hdkey/blob/42637e381bdef0c8f785b14f5b66a80dad969514/test/fixtures/hdkey.json const fixtures = [ { seed: "000102030405060708090a0b0c0d0e0f", path: "m", public: "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", private: "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi" }, { seed: "000102030405060708090a0b0c0d0e0f", path: "m/0'", public: "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw", private: "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7" }, { seed: "000102030405060708090a0b0c0d0e0f", path: "m/0'/1", public: "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ", private: "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs" }, { seed: "000102030405060708090a0b0c0d0e0f", path: "m/0'/1/2'", public: "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5", private: "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM" }, { seed: "000102030405060708090a0b0c0d0e0f", path: "m/0'/1/2'/2", public: "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV", private: "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334" }, { seed: "000102030405060708090a0b0c0d0e0f", path: "m/0'/1/2'/2/1000000000", public: "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy", private: "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m", public: "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", private: "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m/0", public: "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH", private: "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m/0/2147483647'", public: "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a", private: "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m/0/2147483647'/1", public: "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon", private: "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m/0/2147483647'/1/2147483646'", public: "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL", private: "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc" }, { seed: "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", path: "m/0/2147483647'/1/2147483646'/2", public: "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt", private: "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j" } ]; describe("hdkey", () => { it("Should derive private key correctly", () => { const seed = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542"; const hdkey = HDKey.fromMasterSeed(hexToBytes(seed)); const childkey = hdkey.derive("m/0/2147483647'/1"); deepStrictEqual( childkey.privateExtendedKey, "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef" ); }); it("Should derive public key correctly", () => { const seed = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542"; const hdkey = HDKey.fromMasterSeed(hexToBytes(seed)); const expected = hdkey.derive("m/0/2147483647'/1"); const parentkey = hdkey.derive("m/0/2147483647'"); parentkey.wipePrivateData(); const childkey = parentkey.derive("m/1"); deepStrictEqual(childkey.publicExtendedKey, expected.publicExtendedKey); }); // Ported from https://github.com/cryptocoinjs/hdkey/blob/42637e381bdef0c8f785b14f5b66a80dad969514/test/hdkey.test.js describe("+ fromMasterSeed", () => { for (const f of fixtures) { it("should properly derive the chain path: " + f.path, () => { const hdkey = HDKey.fromMasterSeed(hexToBytes(f.seed)); const childkey = hdkey.derive(f.path); deepStrictEqual(childkey.privateExtendedKey, f.private); deepStrictEqual(childkey.publicExtendedKey, f.public); }); describe("> " + f.path + " toJSON() / fromJSON()", () => { it("should return an object read for JSON serialization", () => { const hdkey = HDKey.fromMasterSeed(hexToBytes(f.seed)); const childkey = hdkey.derive(f.path); const obj = { xpriv: f.private, xpub: f.public }; deepStrictEqual(childkey.toJSON(), obj); const newKey = HDKey.fromJSON(obj); deepStrictEqual(newKey.privateExtendedKey, f.private); deepStrictEqual(newKey.publicExtendedKey, f.public); }); }); } }); describe("- privateKey", () => { it("should throw an error if incorrect key size", () => { const hdkey = new HDKey(); throws(() => { hdkey.privateKey = new Uint8Array([1, 2, 3, 4]); }); }); }); describe("- publicKey", () => { it("should throw an error if incorrect key size", () => { throws(() => { const hdkey = new HDKey(); hdkey.publicKey = new Uint8Array([1, 2, 3, 4]); }); }); it("should not throw if key is 33 bytes (compressed)", () => { const pub = secp.getPublicKey(secp.utils.randomPrivateKey(), true); deepStrictEqual(pub.length, 33); const hdkey = new HDKey(); hdkey.publicKey = pub; }); it("should not throw if key is 65 bytes (not compressed)", () => { const pub = secp.getPublicKey(secp.utils.randomPrivateKey(), false); deepStrictEqual(pub.length, 65); const hdkey = new HDKey(); hdkey.publicKey = pub; }); }); describe("+ fromExtendedKey()", () => { describe("> when private", () => { it("should parse it", () => { // m/0/2147483647'/1/2147483646'/2 const key = "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"; const hdkey = HDKey.fromExtendedKey(key); deepStrictEqual(hdkey.versions.private, 0x0488ade4); deepStrictEqual(hdkey.versions.public, 0x0488b21e); deepStrictEqual(hdkey.depth, 5); deepStrictEqual(hdkey.parentFingerprint, 0x31a507b8); deepStrictEqual(hdkey.index, 2); deepStrictEqual( toHex(hdkey.chainCode!), "9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271" ); deepStrictEqual( toHex(hdkey.privateKey!), "bb7d39bdb83ecf58f2fd82b6d918341cbef428661ef01ab97c28a4842125ac23" ); deepStrictEqual( toHex(hdkey.publicKey!), "024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c" ); deepStrictEqual( toHex(hdkey.identifier!), "26132fdbe7bf89cbc64cf8dafa3f9f88b8666220" ); }); }); describe("> when public", () => { it("should parse it", () => { // m/0/2147483647'/1/2147483646'/2 const key = "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"; const hdkey = HDKey.fromExtendedKey(key); deepStrictEqual(hdkey.versions.private, 0x0488ade4); deepStrictEqual(hdkey.versions.public, 0x0488b21e); deepStrictEqual(hdkey.depth, 5); deepStrictEqual(hdkey.parentFingerprint, 0x31a507b8); deepStrictEqual(hdkey.index, 2); deepStrictEqual( toHex(hdkey.chainCode!), "9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271" ); deepStrictEqual(hdkey.privateKey, null); deepStrictEqual( toHex(hdkey.publicKey!), "024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c" ); deepStrictEqual( toHex(hdkey.identifier!), "26132fdbe7bf89cbc64cf8dafa3f9f88b8666220" ); }); }); }); describe("> when signing", () => { it("should work", () => { const key = "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"; const hdkey = HDKey.fromExtendedKey(key); const ma = new Uint8Array(32); const mb = new Uint8Array(32).fill(8); const a = hdkey.sign(ma); const b = hdkey.sign(mb); deepStrictEqual( toHex(a), "6ba4e554457ce5c1f1d7dbd10459465e39219eb9084ee23270688cbe0d49b52b7905d5beb28492be439a3250e9359e0390f844321b65f1a88ce07960dd85da06" ); deepStrictEqual( toHex(b), "dfae85d39b73c9d143403ce472f7c4c8a5032c13d9546030044050e7d39355e47a532e5c0ae2a25392d97f5e55ab1288ef1e08d5c034bad3b0956fbbab73b381" ); // TODO: noble-secp256k1 incompat // assert.equal(hdkey.verify(ma, a), true); deepStrictEqual(hdkey.verify(mb, b), true); deepStrictEqual( hdkey.verify(new Uint8Array(32), new Uint8Array(64)), false ); deepStrictEqual(hdkey.verify(ma, b), false); deepStrictEqual(hdkey.verify(mb, a), false); throws(() => hdkey.verify(new Uint8Array(99), a)); throws(() => hdkey.verify(ma, new Uint8Array(99))); }); }); describe("> when deriving public key", () => { it("should work", () => { const key = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"; const hdkey = HDKey.fromExtendedKey(key); const path = "m/3353535/2223/0/99424/4/33"; const derivedHDKey = hdkey.derive(path); const expected = "xpub6JdKdVJtdx6sC3nh87pDvnGhotXuU5Kz6Qy7Piy84vUAwWSYShsUGULE8u6gCivTHgz7cCKJHiXaaMeieB4YnoFVAsNgHHKXJ2mN6jCMbH1"; deepStrictEqual(derivedHDKey.publicExtendedKey, expected); }); }); describe("> when private key integer is less than 32 bytes", () => { it("should work", () => { const seed = "000102030405060708090a0b0c0d0e0f"; const masterKey = HDKey.fromMasterSeed(hexToBytes(seed)); const newKey = masterKey.derive("m/44'/6'/4'"); const expected = "xprv9ymoag6W7cR6KBcJzhCM6qqTrb3rRVVwXKzwNqp1tDWcwierEv3BA9if3ARHMhMPh9u2jNoutcgpUBLMfq3kADDo7LzfoCnhhXMRGX3PXDx"; deepStrictEqual(newKey.privateExtendedKey, expected); }); }); describe("HARDENED_OFFSET", () => { it("should be set", () => { deepStrictEqual(!!HDKey.HARDENED_OFFSET, true); }); }); describe("> when private key has leading zeros", () => { it("will include leading zeros when hashing to derive child", () => { const key = "xprv9s21ZrQH143K3ckY9DgU79uMTJkQRLdbCCVDh81SnxTgPzLLGax6uHeBULTtaEtcAvKjXfT7ZWtHzKjTpujMkUd9dDb8msDeAfnJxrgAYhr"; const hdkey = HDKey.fromExtendedKey(key); deepStrictEqual( toHex(hdkey.privateKey!), "00000055378cf5fafb56c711c674143f9b0ee82ab0ba2924f19b64f5ae7cdbfd" ); const derived = hdkey.derive("m/44'/0'/0'/0/0'"); deepStrictEqual( toHex(derived.privateKey!), "3348069561d2a0fb925e74bf198762acc47dce7db27372257d2d959a9e6f8aeb" ); }); }); describe("> when private key is null", () => { it("privateExtendedKey should return null and not throw", () => { const seed = "000102030405060708090a0b0c0d0e0f"; const masterKey = HDKey.fromMasterSeed(hexToBytes(seed)); deepStrictEqual(!!masterKey.privateExtendedKey, true, "xpriv is truthy"); (masterKey as any).privateKey = undefined; throws(() => masterKey.privateExtendedKey); }); }); describe(" - when the path given to derive contains only the master extended key", () => { const hdKeyInstance = HDKey.fromMasterSeed(hexToBytes(fixtures[0].seed)); it("should return the same hdkey instance", () => { deepStrictEqual(hdKeyInstance.derive("m"), hdKeyInstance); deepStrictEqual(hdKeyInstance.derive("M"), hdKeyInstance); deepStrictEqual(hdKeyInstance.derive("m'"), hdKeyInstance); deepStrictEqual(hdKeyInstance.derive("M'"), hdKeyInstance); }); }); describe(" - when the path given to derive does not begin with master extended key", () => { it("should throw an error", () => { throws(() => HDKey.prototype.derive("123")); }); }); describe("- after wipePrivateData()", () => { it("should not have private data", () => { const hdkey = HDKey.fromMasterSeed( hexToBytes(fixtures[6].seed) ).wipePrivateData(); deepStrictEqual(hdkey.privateKey, null); throws(() => hdkey.privateExtendedKey); throws(() => hdkey.sign(new Uint8Array(32))); const childKey = hdkey.derive("m/0"); deepStrictEqual(childKey.publicExtendedKey, fixtures[7].public); deepStrictEqual(childKey.privateKey, null); throws(() => childKey.privateExtendedKey); }); it("should have correct data", () => { // m/0/2147483647'/1/2147483646'/2 const key = "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"; const hdkey = HDKey.fromExtendedKey(key).wipePrivateData(); deepStrictEqual(hdkey.versions.private, 0x0488ade4); deepStrictEqual(hdkey.versions.public, 0x0488b21e); deepStrictEqual(hdkey.depth, 5); deepStrictEqual(hdkey.parentFingerprint, 0x31a507b8); deepStrictEqual(hdkey.index, 2); deepStrictEqual( toHex(hdkey.chainCode!), "9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271" ); deepStrictEqual( toHex(hdkey.publicKey!), "024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c" ); deepStrictEqual( toHex(hdkey.identifier!), "26132fdbe7bf89cbc64cf8dafa3f9f88b8666220" ); }); it("should be able to verify signatures", () => { const fullKey = HDKey.fromMasterSeed(hexToBytes(fixtures[0].seed)); // using JSON methods to clone before mutating const wipedKey = HDKey.fromJSON(fullKey.toJSON()).wipePrivateData(); const hash = new Uint8Array(32).fill(8); deepStrictEqual(!!wipedKey.verify(hash, fullKey.sign(hash)), true); }); it("should not throw if called on hdkey without private data", () => { const hdkey = HDKey.fromExtendedKey(fixtures[0].public); hdkey.wipePrivateData(); deepStrictEqual(hdkey.publicExtendedKey, fixtures[0].public); }); }); it("should throw on derive of wrong indexes", () => { const hdkey = HDKey.fromExtendedKey(fixtures[0].public); const invalid = [ "m/0/ 1 /2", "m/0/1.5/2", "m/0/331e100/2", "m/0/3e/2", "m/0/'/2" ]; for (const t of invalid) { throws(() => hdkey.derive(t)); } }); });
the_stack
import { IAugmentedJQuery, ICompileService, IQService, IPromise, IScope, ITimeoutService } from 'angular'; import * as ng1 from 'angular'; import { ngTableModule } from '../../index'; import { NgTableParams, ParamValuesPartial, SettingsPartial, SortingValues } from '../../src/core'; import { ColumnDef, FilterTemplateDef, FilterTemplateDefMap, SelectOption } from '../../src/browser' describe('ng-table', () => { interface Person { id?: number; name?: string; age: number; money?: number; } interface INgTableChildScope extends IScope { params: NgTableParams<any>; $columns: ColumnDef[]; } interface CustomizedScope extends IScope { $$childHead: INgTableChildScope; model: { exportedCols?: ColumnDef[]; }; ageFilter: FilterTemplateDefMap; ageExpandedFilter: { [name: string]: FilterTemplateDef }; ageTitle: string | { (): string }; captureColumn: ($columnDef: ColumnDef) => any; getCustomClass($column: ColumnDef): string; getFilter($column: ColumnDef): FilterTemplateDefMap; isAgeVisible: boolean; nameTitle(): string; money: () => IPromise<SelectOption[]>; moneyTitle(): string; showAge: boolean; showFilterRow: boolean; showMoney: boolean; showName: boolean; tableParams: NgTableParams<Person>; usernameFilter: FilterTemplateDefMap; usernameExpandedFilter: { [name: string]: FilterTemplateDef }; } const dataset = [ { id: 1, name: "Moroni", age: 50, money: -10 }, { id: 2, name: "Tiancum", age: 43, money: 120 }, { id: 3, name: "Jacob", age: 27, money: 5.5 }, { id: 4, name: "Nephi", age: 29, money: -54 }, { id: 5, name: "Enos", age: 34, money: 110 }, { id: 6, name: "Tiancum", age: 43, money: 1000 }, { id: 7, name: "Jacob", age: 27, money: -201 }, { id: 8, name: "Nephi", age: 29, money: 100 }, { id: 9, name: "Enos", age: 34, money: -52.5 }, { id: 10, name: "Tiancum", age: 43, money: 52.1 }, { id: 11, name: "Jacob", age: 27, money: 110 }, { id: 12, name: "Nephi", age: 29, money: -55 }, { id: 13, name: "Enos", age: 34, money: 551 }, { id: 14, name: "Tiancum", age: 43, money: -1410 }, { id: 15, name: "Jacob", age: 27, money: 410 }, { id: 16, name: "Nephi", age: 29, money: 100 }, { id: 17, name: "Enos", age: 34, money: -100 } ]; beforeAll(() => expect(ngTableModule).toBeDefined()); beforeEach(ng1.mock.module('ngTable')); let scope: CustomizedScope; let $compile: ICompileService; beforeEach(inject(($rootScope: IScope, _$compile_: ICompileService) => { scope = $rootScope.$new(true) as CustomizedScope; $compile = _$compile_; scope.model = {}; })); function createNgTableParams<T>(initialParams?: ParamValuesPartial<T>, settings?: SettingsPartial<T> | null): NgTableParams<T>; function createNgTableParams<T>(settings?: SettingsPartial<T>): NgTableParams<T>; function createNgTableParams<T>(settings?: any): NgTableParams<T> { let initialParams: ParamValuesPartial<T> | undefined; if (arguments.length === 2) { initialParams = arguments[0]; settings = arguments[1]; } settings = ng1.extend({}, settings); settings.filterOptions = ng1.extend({}, { filterDelay: 0 }, settings.filterOptions); const tableParams = new NgTableParams(initialParams, settings); spyOn(tableParams.settings(), 'getData').and.callThrough(); return tableParams; } function createTable(htmlTemplate: string, params?: NgTableParams<Person>) { params = params || createNgTableParams<Person>(); const tableElm = ng1.element(htmlTemplate); $compile(tableElm)(scope); scope.$digest(); scope.tableParams = params; scope.$digest(); return { params, tableElm }; } describe('basics', () => { let tableElm: IAugmentedJQuery; beforeEach(inject(($q: IQService) => { const html = `<div> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td data-header-title="'Sort by Name'" data-title="nameTitle()" filter="{ 'name': 'text' }" sortable="'name'" data-header-class="getCustomClass($column)" ng-if="showName"> {{user.name}} </td> <td x-data-header-title="'Sort by Age'" x-data-title="ageTitle()" sortable="'age'" x-data-header-class="getCustomClass($column)" ng-if="showAge"> {{user.age}} </td> <td header-title="'Sort by Money'" title="moneyTitle()" filter="{ 'action': 'select' }" filter-data="money($column)" header-class="getCustomClass($column)" ng-if="showMoney"> {{user.money}} </td> </tr> </table> </div>`; scope.nameTitle = () => 'Name of person'; scope.ageTitle = () => 'Age'; scope.moneyTitle = () => 'Money'; scope.showName = true; scope.showAge = true; scope.showMoney = true; scope.ageTitle = () => 'Age'; scope.moneyTitle = () => 'Money'; scope.getCustomClass = ($column) => { if ($column.title().indexOf('Money') !== -1) { return 'moneyHeaderClass'; } else { return 'customClass'; } }; scope.money = (/*$column*/) => { let selectOptions = [{ 'id': 10, 'title': '10' }]; return $q.when(selectOptions); }; ({ tableElm } = createTable(html)); })); it('should create table header', () => { const thead = tableElm.find('thead'); expect(thead.length).toBe(1); const rows = thead.find('tr'); expect(rows.length).toBe(2); const titles = ng1.element(rows[0]).find('th'); expect(titles.length).toBe(3); expect(ng1.element(titles[0]).text().trim()).toBe('Name of person'); expect(ng1.element(titles[1]).text().trim()).toBe('Age'); expect(ng1.element(titles[2]).text().trim()).toBe('Money'); expect(ng1.element(rows[1]).hasClass('ng-table-filters')).toBeTruthy(); const filters = ng1.element(rows[1]).find('th'); expect(filters.length).toBe(3); expect(ng1.element(filters[0]).hasClass('filter')).toBeTruthy(); expect(ng1.element(filters[1]).hasClass('filter')).toBeTruthy(); expect(ng1.element(filters[2]).hasClass('filter')).toBeTruthy(); }); it('should create table header classes', () => { const thead = tableElm.find('thead'); const rows = thead.find('tr'); const titles = ng1.element(rows[0]).find('th'); expect(ng1.element(titles[0]).hasClass('header')).toBe(true); expect(ng1.element(titles[1]).hasClass('header')).toBe(true); expect(ng1.element(titles[2]).hasClass('header')).toBe(true); expect(ng1.element(titles[0]).hasClass('sortable')).toBe(true); expect(ng1.element(titles[1]).hasClass('sortable')).toBe(true); expect(ng1.element(titles[2]).hasClass('sortable')).toBe(false); expect(ng1.element(titles[0]).hasClass('customClass')).toBe(true); expect(ng1.element(titles[1]).hasClass('customClass')).toBe(true); expect(ng1.element(titles[2]).hasClass('moneyHeaderClass')).toBe(true); const filterCells = ng1.element(rows[1]).find('th'); expect(ng1.element(filterCells[0]).hasClass('filter')).toBe(true); expect(ng1.element(filterCells[1]).hasClass('filter')).toBe(true); expect(ng1.element(filterCells[2]).hasClass('filter')).toBe(true); expect(ng1.element(filterCells[0]).hasClass('customClass')).toBe(true); expect(ng1.element(filterCells[1]).hasClass('customClass')).toBe(true); expect(ng1.element(filterCells[2]).hasClass('moneyHeaderClass')).toBe(true); }); it('should create table header titles', () => { const thead = tableElm.find('thead'); const rows = thead.find('tr'); const titles = ng1.element(rows[0]).find('th'); expect(ng1.element(titles[0]).attr('title').trim()).toBe('Sort by Name'); expect(ng1.element(titles[1]).attr('title').trim()).toBe('Sort by Age'); expect(ng1.element(titles[2]).attr('title').trim()).toBe('Sort by Money'); }); it('should show scope data', () => { const tbody = tableElm.find('tbody'); expect(tbody.length).toBe(1); let rows = tbody.find('tr'); expect(rows.length).toBe(0); const params = new NgTableParams({ count: 10 // count per page }, { dataset: dataset }); scope.tableParams = params; scope.$digest(); rows = tbody.find('tr'); expect(rows.length).toBe(10); scope.tableParams.page(2); scope.$digest(); rows = tbody.find('tr'); expect(rows.length).toBe(7); params.total(20); scope.$digest(); rows = tbody.find('tr'); expect(rows.length).toBe(7); }); it('should show data-title-text', () => { const tbody = tableElm.find('tbody'); const params = new NgTableParams({}, { dataset: dataset }); scope.tableParams = params; scope.$digest(); const filterRow = ng1.element(tableElm.find('thead').find('tr')[1]); const filterCells = filterRow.find('th'); expect(ng1.element(filterCells[0]).attr('data-title-text').trim()).toBe('Name of person'); expect(ng1.element(filterCells[1]).attr('data-title-text').trim()).toBe('Age'); expect(ng1.element(filterCells[2]).attr('data-title-text').trim()).toBe('Money'); const dataRows = tableElm.find('tbody').find('tr'); const dataCells = ng1.element(dataRows[0]).find('td'); expect(ng1.element(dataCells[0]).attr('data-title-text').trim()).toBe('Name of person'); expect(ng1.element(dataCells[1]).attr('data-title-text').trim()).toBe('Age'); expect(ng1.element(dataCells[2]).attr('data-title-text').trim()).toBe('Money'); }); it('should show/hide columns', () => { const tbody = tableElm.find('tbody'); scope.tableParams = new NgTableParams({}, { dataset: dataset }); scope.$digest(); const headerRow = ng1.element(tableElm.find('thead').find('tr')[0]); expect(headerRow.find('th').length).toBe(3); const filterRow = ng1.element(tableElm.find('thead').find('tr')[1]); expect(filterRow.find('th').length).toBe(3); const dataRow = ng1.element(tableElm.find('tbody').find('tr')[0]); expect(dataRow.find('td').length).toBe(3); scope.showName = false; scope.$digest(); expect(headerRow.find('th').length).toBe(2); expect(filterRow.find('th').length).toBe(2); expect(dataRow.find('td').length).toBe(2); expect(ng1.element(headerRow.find('th')[0]).text().trim()).toBe('Age'); expect(ng1.element(headerRow.find('th')[1]).text().trim()).toBe('Money'); expect(ng1.element(filterRow.find('th')[0]).find('input').length).toBe(0); expect(ng1.element(filterRow.find('th')[1]).find('select').length).toBe(1); }); }); describe('title-alt', () => { let tableElm: IAugmentedJQuery; beforeEach(() => { const html = `<table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="'Name of person'" title-alt="'Name'">{{user.name}}</td> <td title="'Age of person'" data-title-alt="'Age'">{{user.age}}</td> <td title="'Money earned'" x-data-title-alt="'£'">{{user.money}}</td> </tr> </table>`; const params = new NgTableParams({}, { dataset: dataset }); ({ tableElm } = createTable(html, params)); }); it('should show as data-title-text', () => { const filterRow = ng1.element(tableElm.find('thead').find('tr')[1]); const filterCells = filterRow.find('th'); expect(ng1.element(filterCells[0]).attr('data-title-text').trim()).toBe('Name'); expect(ng1.element(filterCells[1]).attr('data-title-text').trim()).toBe('Age'); expect(ng1.element(filterCells[2]).attr('data-title-text').trim()).toBe('£'); const dataRows = tableElm.find('tbody').find('tr'); const dataCells = ng1.element(dataRows[0]).find('td'); expect(ng1.element(dataCells[0]).attr('data-title-text').trim()).toBe('Name'); expect(ng1.element(dataCells[1]).attr('data-title-text').trim()).toBe('Age'); expect(ng1.element(dataCells[2]).attr('data-title-text').trim()).toBe('£'); }); }); describe('sorting', () => { const tableWithSortableAgeColumnTpl = `<table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="'Age'" sortable="'age'">{{user.age}}</td> </tr> </table>` it('should add $column definition to context of sortable expression', () => { let columnDef: ColumnDef | undefined; scope.captureColumn = function ($column) { columnDef = $column; return 'age' }; const html = `<table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="'Age'" sortable="captureColumn($column)">{{user.age}}</td> </tr> </table>)`; createTable(html); expect(columnDef).toBeDefined(); }); it('should apply initial sort', () => { let actualSort: SortingValues = {}; let params = createNgTableParams<Person>({ sorting: { age: 'desc' } }, { getData: function (params) { actualSort = params.sorting(); let results: Person[] = []; return results; } }); createTable(tableWithSortableAgeColumnTpl, params); expect(actualSort['age']).toBe('desc'); }); it('when sorting changes should trigger reload of table', () => { const { params } = createTable(tableWithSortableAgeColumnTpl); (params.settings().getData as jasmine.Spy).calls.reset(); params.sorting()['age'] = 'desc'; scope.$digest(); expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(1); params.sorting()['age'] = 'asc'; scope.$digest(); expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(2); // setting the same sort order should not trigger reload params.sorting({ age: 'asc' }); scope.$digest(); expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(2); }); it('when tapping column header should sort table by that column', () => { // given const { params, tableElm } = createTable(tableWithSortableAgeColumnTpl); (params.settings().getData as jasmine.Spy).calls.reset(); const columnHeader = tableElm[0].querySelector('.ng-table-sort-header > th') as HTMLTableHeaderCellElement; // when columnHeader.click(); columnHeader.click(); // then expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(2); }); }); describe('paging', () => { let tableElm: IAugmentedJQuery; beforeEach(() => { const html = `<table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="'Age'">{{user.age}}</td> </tr> </table>`; ({ tableElm } = createTable(html)); }); function verifyPageWas(expectedPage: number) { let getDataFunc = scope.tableParams.settings().getData as jasmine.Spy; expect(getDataFunc.calls.argsFor(0)[0].page()).toBe(expectedPage); } it('should use initial NgTableParams constructor value', () => { const params = createNgTableParams<Person>({ page: 2 }, null); scope.tableParams = params; scope.$digest(); verifyPageWas(2); expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should use initial NgTableParams constructor value combined with filter', () => { const params = createNgTableParams<Person>({ page: 2, filter: { age: 5 } }, null); scope.tableParams = params; scope.$digest(); verifyPageWas(2); expect((params.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('changing page # should trigger reload of data', () => { const params = createNgTableParams<Person>({ page: 3 }, null); scope.tableParams = params; scope.$digest(); verifyPageWas(3); (params.settings().getData as jasmine.Spy).calls.reset(); scope.tableParams.page(5); scope.$digest(); verifyPageWas(5); }); }); describe('filters', () => { let $capturedColumn: ColumnDef; beforeEach(inject(() => { // stash a reference to $column definition so that its available in asserts scope.captureColumn = function ($column) { $capturedColumn = $column; }; })); describe('filter specified as alias', () => { let tableElm: IAugmentedJQuery, tp: NgTableParams<Person>; beforeEach(() => { // 'text' is a shortcut alias for the template ng-table/filters/text scope.usernameFilter = { username: 'text' }; const params = createNgTableParams<Person>({ filterOptions: { filterDelay: 10 } }); const html = `<div> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td header-class="captureColumn($column)" title="'Name'" filter="usernameFilter"> {{user.name}} </td> </tr> </table> </div>`; ({ params: tp, tableElm } = createTable(html, params)); }); it('should render named filter template', () => { const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.length).toBe(1); expect(inputs.eq(0).attr('type')).toBe('text'); expect(inputs.eq(0).attr('ng-model')).not.toBeUndefined(); expect(inputs.eq(0).attr('name')).toBe('username'); }); it('should databind ngTableParams.filter to filter input', () => { scope.tableParams.filter()['username'] = 'my name is...'; scope.$digest(); const input = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(input.val()).toBe('my name is...'); }); it('should make filter def available on $column', () => { expect($capturedColumn).toBeDefined(); expect($capturedColumn.filter).toBeDefined(); expect($capturedColumn.filter()['username']).toBe('text'); }); it('when filter changes should trigger reload of table', inject(function ($timeout: ITimeoutService) { (tp.settings().getData as jasmine.Spy).calls.reset(); tp.filter()['username'] = 'new value'; scope.$digest(); $timeout.flush(); // trigger delayed filter tp.filter()['username'] = 'another value'; scope.$digest(); $timeout.flush(); // trigger delayed filter expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(2); // same value - should not trigger reload tp.filter()['username'] = 'another value'; scope.$digest(); try { $timeout.flush(); // trigger delayed filter } catch (ex) { } expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(2); })); it('when filter changes should reset page number to 1', inject(function ($timeout: ITimeoutService) { // trigger initial load of data so that subsequent changes to filter will trigger reset of page # tp.filter()['username'] = 'initial value'; scope.$digest(); $timeout.flush(); // trigger delayed filter // set page to something other than 1 tp.page(5); expect(tp.page()).toBe(5); // checking assumptions // when tp.filter()['username'] = 'new value'; scope.$digest(); $timeout.flush(); // trigger delayed filter expect(tp.page()).toBe(1); })); }); describe('filter specified with url', () => { let tableElm: IAugmentedJQuery; beforeEach(() => { const html = `<div> <script type="text/ng-template" id="ng-table/filters/customNum.html"> <input type="number" id="{{name}}"/> </script> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td header-class="captureColumn($column)" title="'Age'" filter="{ 'age': 'ng-table/filters/customNum.html' }">{{user.age}}</td> </tr> </table> </div>`; ({ tableElm } = createTable(html)); }); it('should render filter template specified by url', () => { const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.length).toBe(1); expect(inputs.eq(0).attr('type')).toBe('number'); expect(inputs.eq(0).attr('id')).toBe('age'); }); }); describe('multiple filter inputs', () => { let tableElm: IAugmentedJQuery; beforeEach(() => { const html = `<div> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td header-class="captureColumn($column)" title="'Name'" filter="{ 'name': 'text', 'age': 'text' }"> {{user.name}} </td> </tr> </table> </div>`; ({ tableElm } = createTable(html)); }); it('should render filter template for each key/value pair ordered by key', () => { const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.length).toBe(2); expect(inputs.eq(0).attr('type')).toBe('text'); expect(inputs.eq(0).attr('ng-model')).not.toBeUndefined(); expect(inputs.eq(1).attr('type')).toBe('text'); expect(inputs.eq(1).attr('ng-model')).not.toBeUndefined(); }); it('should databind ngTableParams.filter to filter inputs', () => { scope.tableParams.filter()['name'] = 'my name is...'; scope.tableParams.filter()['age'] = '10'; scope.$digest(); const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.eq(0).val()).toBe('my name is...'); expect(inputs.eq(1).val()).toBe('10'); }); it('should make filter def available on $column', () => { expect($capturedColumn).toBeDefined(); expect($capturedColumn.filter).toBeDefined(); expect($capturedColumn.filter()['name']).toBe('text'); expect($capturedColumn.filter()['age']).toBe('text'); }); }); describe('dynamic filter', () => { let tableElm: IAugmentedJQuery, ageFilter: FilterTemplateDefMap; beforeEach(() => { ageFilter = { age: 'text' }; scope.getFilter = function (colDef) { if (colDef.id === 0) { return { username: 'text' }; } else if (colDef.id === 1) { return ageFilter; } else { return {}; } }; const html = `<div> <script type="text/ng-template" id="ng-table/filters/number.html"> <input type="number" name="{{name}}"/> </script> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="'Name'" filter="getFilter($column)">{{user.name}}</td> <td title="'Age'" filter="getFilter($column)">{{user.age}}</td> </tr> </table> </div>`; ({ tableElm } = createTable(html)); }); it('should render named filter template', () => { const usernameInput = tableElm.find('thead').find('tr').eq(1).find('th').eq(0).find('input'); expect(usernameInput.attr('type')).toBe('text'); expect(usernameInput.attr('name')).toBe('username'); const ageInput = tableElm.find('thead').find('tr').eq(1).find('th').eq(1).find('input'); expect(ageInput.attr('type')).toBe('text'); expect(ageInput.attr('name')).toBe('age'); }); it('should databind ngTableParams.filter to filter input', () => { scope.tableParams.filter()['username'] = 'my name is...'; scope.tableParams.filter()['age'] = '10'; scope.$digest(); const usernameInput = tableElm.find('thead').find('tr').eq(1).find('th').eq(0).find('input'); expect(usernameInput.val()).toBe('my name is...'); const ageInput = tableElm.find('thead').find('tr').eq(1).find('th').eq(1).find('input'); expect(ageInput.val()).toBe('10'); }); it('should render new template as filter changes', () => { ageFilter['age'] = 'number'; scope.$digest(); const ageInput = tableElm.find('thead').find('tr').eq(1).find('th').eq(1).find('input'); expect(ageInput.attr('type')).toBe('number'); expect(ageInput.attr('name')).toBe('age'); }); }); describe('filter with placeholder value and alias', () => { let tableElm: IAugmentedJQuery, tp: NgTableParams<Person>; beforeEach(() => { const html = `<div> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td header-class="captureColumn($column)" title="'Name'" filter="usernameExpandedFilter"> {{user.name}} </td> </tr> </table> </div>`; // 'text' is a shortcut alias for the template ng-table/filters/text scope.usernameExpandedFilter = { username: { id: 'text', placeholder: 'User name' } }; ({ params: tp, tableElm } = createTable(html)); }); it('should render named filter template with placeholder value', () => { const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.length).toBe(1); expect(inputs.eq(0).attr('type')).toBe('text'); expect(inputs.eq(0).attr('ng-model')).not.toBeUndefined(); expect(inputs.eq(0).attr('name')).toBe('username'); expect(inputs.eq(0).attr('placeholder')).toBe('User name'); }); it('should databind placeholder value to filter input', () => { scope.usernameExpandedFilter['username'].placeholder = 'Name of user'; scope.$digest(); const input = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(input.attr('placeholder')).toBe('Name of user'); }); it('should make filter def available on $column', () => { expect($capturedColumn).toBeDefined(); expect($capturedColumn.filter).toBeDefined(); expect($capturedColumn.filter()).toBe(scope.usernameExpandedFilter); }); }); describe('filter with placeholder value and url', () => { let tableElm: IAugmentedJQuery, tp: NgTableParams<Person>; beforeEach(() => { const html = `<div> <table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td header-class="captureColumn($column)" title="'Age'" filter="ageExpandedFilter">{{user.age}}</td> </tr> </table> </div>`; scope.ageExpandedFilter = { age: { id: 'ng-table/filters/number.html', placeholder: 'User age' } }; ({ params: tp, tableElm } = createTable(html)); }); it('should render named filter template with placeholder value', () => { const inputs = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(inputs.length).toBe(1); expect(inputs.eq(0).attr('type')).toBe('number'); expect(inputs.eq(0).attr('ng-model')).not.toBeUndefined(); expect(inputs.eq(0).attr('name')).toBe('age'); expect(inputs.eq(0).attr('placeholder')).toBe('User age'); }); it('should databind placeholder value to filter input', () => { scope.ageExpandedFilter['age'].placeholder = 'Age of user'; scope.$digest(); const input = tableElm.find('thead').find('tr').eq(1).find('th').find('input'); expect(input.attr('placeholder')).toBe('Age of user'); }); it('should make filter def available on $column', () => { expect($capturedColumn).toBeDefined(); expect($capturedColumn.filter).toBeDefined(); expect($capturedColumn.filter()).toBe(scope.ageExpandedFilter); }); }); }); describe('show-filter', () => { let tableElm: IAugmentedJQuery; beforeEach(() => { const html = `<div> <table ng-table="tableParams" show-filter="showFilterRow"> <tr ng-repeat="user in $data"> <td title="'Age'" filter="{ age: 'number'}">{{user.age}}</td> </tr> </table> </div>`; scope.showFilterRow = true; ({ tableElm } = createTable(html)); }); it('when true, should display filter row', () => { const filterRow = tableElm.find('thead').find('tr').eq(1); expect(filterRow.hasClass('ng-table-filters')).toBe(true); expect(filterRow.hasClass('ng-hide')).toBe(false); }); it('when false, should hide filter row', () => { // given scope.showFilterRow = false; // when scope.$digest(); // then const filterRow = tableElm.find('thead').find('tr').eq(1); expect(filterRow.hasClass('ng-table-filters')).toBe(true); expect(filterRow.hasClass('ng-hide')).toBe(true); }); }); describe('$columns', () => { let tableElm: IAugmentedJQuery, params: NgTableParams<Person>; beforeEach(() => { const html = `<div> <table ng-table="tableParams" ng-table-columns-binding="model.exportedCols"> <tr ng-repeat="user in $data"> <td title="ageTitle" ng-if="isAgeVisible" filter="ageFilter">{{user.age}}</td> <td title="'Name'" groupable="'name'" sortable="'name'">{{user.name}}</td> </tr> </table> </div>`; scope.ageFilter = { age: 'text' }; scope.isAgeVisible = true; scope.ageTitle = 'Age'; ({ params, tableElm } = createTable(html)); }); it('should make $columns available on the scope created for ng-table', () => { // check that the scope is indeed the one created for out NgTableParams expect(scope.$$childHead.params).toBe(params); expect(scope.$$childHead.$columns).toBeDefined(); }); it('should NOT polute the outer scope with a reference to $columns ', () => { expect(scope['$columns']).toBeUndefined(); }); it('ng-table-columns-binding should make $columns externally available', () => { expect(scope.model.exportedCols).toBeDefined(); }); it('$scolumns should contain a column definition for each `td` element', () => { expect(scope.model.exportedCols!.length).toBe(2); }); it('each column definition should have getters for each column attribute', () => { const ageCol = scope.model.exportedCols![0]; expect(ageCol.title()).toBe('Age'); expect(ageCol.show()).toBe(true); expect(ageCol.filter()).toBe(scope.ageFilter); expect(ageCol.class()).toBe(''); expect(ageCol.filterData).toBeUndefined(); expect(ageCol.groupable()).toBe(false); expect(ageCol.headerTemplateURL()).toBe(false); expect(ageCol.headerTitle()).toBe(''); expect(ageCol.sortable()).toBe(false); expect(ageCol.titleAlt()).toBe(''); const nameCol = scope.model.exportedCols![1]; expect(nameCol.title()).toBe('Name'); expect(nameCol.show()).toBe(true); expect(nameCol.filter()).toBe(false); expect(nameCol.class()).toBe(''); expect(nameCol.filterData).toBeUndefined(); expect(nameCol.groupable()).toBe('name'); expect(nameCol.headerTemplateURL()).toBe(false); expect(nameCol.headerTitle()).toBe(''); expect(nameCol.sortable()).toBe('name'); expect(nameCol.titleAlt()).toBe(''); }); it('each column attribute should be assignable', () => { const ageCol = scope.model.exportedCols![0]; ageCol.title.assign(scope.$$childHead, 'Age of person'); expect(ageCol.title()).toBe('Age of person'); expect(scope.ageTitle).toBe('Age of person'); ageCol.show.assign(scope.$$childHead, false); expect(ageCol.show()).toBe(false); expect(scope.isAgeVisible).toBe(false); const newFilter: FilterTemplateDefMap = { age: 'select' }; ageCol.filter.assign(scope.$$childHead, newFilter); expect(ageCol.filter()).toBe(newFilter); expect(scope.ageFilter).toBe(newFilter); ageCol.class.assign(scope.$$childHead, 'amazing'); expect(ageCol.class()).toBe('amazing'); ageCol.groupable.assign(scope.$$childHead, 'age'); expect(ageCol.groupable()).toBe('age'); ageCol.headerTemplateURL.assign(scope.$$childHead, 'some.html'); expect(ageCol.headerTemplateURL()).toBe('some.html'); ageCol.headerTitle.assign(scope.$$childHead, 'wow'); expect(ageCol.headerTitle()).toBe('wow'); ageCol.sortable.assign(scope.$$childHead, 'incredible'); expect(ageCol.sortable()).toBe('incredible'); ageCol.titleAlt.assign(scope.$$childHead, 'really'); expect(ageCol.titleAlt()).toBe('really'); const nameCol = scope.model.exportedCols![1]; nameCol.groupable.assign(scope.$$childHead, false); expect(nameCol.groupable()).toBe(false); nameCol.sortable.assign(scope.$$childHead, false); expect(nameCol.sortable()).toBe(false); }); it('each column attribute should be settable', () => { const ageCol = scope.model.exportedCols![0]; ageCol.title('Age of person'); expect(ageCol.title()).toBe('Age of person'); expect(scope.ageTitle).toBe('Age of person'); ageCol.show(false); expect(ageCol.show()).toBe(false); expect(scope.isAgeVisible).toBe(false); const newFilter: FilterTemplateDefMap = { age: 'select' }; ageCol.filter(newFilter); expect(ageCol.filter()).toBe(newFilter); expect(scope.ageFilter).toBe(newFilter); ageCol.class('amazing'); expect(ageCol.class()).toBe('amazing'); ageCol.groupable('age'); expect(ageCol.groupable()).toBe('age'); ageCol.headerTemplateURL('some.html'); expect(ageCol.headerTemplateURL()).toBe('some.html'); ageCol.headerTitle('wow'); expect(ageCol.headerTitle()).toBe('wow'); ageCol.sortable('incredible'); expect(ageCol.sortable()).toBe('incredible'); ageCol.titleAlt('really'); expect(ageCol.titleAlt()).toBe('really'); const nameCol = scope.model.exportedCols![1]; nameCol.groupable(false); expect(nameCol.groupable()).toBe(false); nameCol.sortable(false); expect(nameCol.sortable()).toBe(false); }); }); describe('groups', () => { let $capturedColumn: ColumnDef; beforeEach(inject(() => { // stash a reference to $column definition so that its available in asserts scope.captureColumn = function ($column) { $capturedColumn = $column; }; })); describe('two groupable columns', () => { let tableElm: IAugmentedJQuery, thead: HTMLElement, tp: NgTableParams<Person>; beforeEach(() => { const html = `<div> <table ng-table="tableParams"> <tr class="ng-table-group" ng-repeat-start="group in $groups"></tr> <tr ng-repeat-end="user in group.data"> <td title="'Name'" groupable="'name'">{{user.name}}</td> <td title="'Age'" groupable="'age'">{{user.age}}</td> <td title="'Money'">{{user.money}}</td> </tr> </table> </div>`; ({ params: tp, tableElm: tableElm } = createTable(html)); thead = tableElm.find('thead')[0]; }); it('should not render group row until group assigned', () => { const groupRow = thead.querySelector('.ng-table-group-header'); expect(groupRow).toBeNull(); }); it('should render group row once group assigned', () => { tp.group('name'); scope.$digest(); const groupRow = thead.querySelector('.ng-table-group-header'); expect(groupRow).not.toBeNull(); }); describe('with group assigned', () => { let groupRow: Element; beforeEach(() => { tp.group('name'); scope.$digest(); groupRow = thead.querySelector('.ng-table-group-header')!; }); it('group row should span the width of the visible columns', () => { expect(groupRow.querySelector('th')!.getAttribute('colspan')).toBe('2'); }); it('should display column name of assigned group', () => { expect(groupRow.querySelector('a > strong')!.textContent).toBe('Name'); }); it('clicking on group row should open group list selector', () => { // when groupRow.querySelector('a')!.click(); // then const groupSelectorList = groupRow.querySelector('.list-group'); expect(groupSelectorList).not.toBeNull(); }); it('group list selector should include an item for each groupable column', () => { // when groupRow.querySelector('a')!.click(); // then const items = groupRow.querySelector('.list-group')!.querySelectorAll('a'); expect(items.length).toBe(2); expect(items.item(0).querySelector('strong')!.textContent).toBe('Name'); expect(items.item(1).querySelector('strong')!.textContent).toBe('Age'); }); it('assigned group should be marked as selected', () => { // when groupRow.querySelector('a')!.click(); // then const nameGroup = groupRow.querySelector('.list-group')!.querySelector('a')!; expect(nameGroup).not.toBeNull(); expect(nameGroup.querySelector('.sort-indicator')).not.toBeNull(); }); it('changing assigned group should be be updated in group row', () => { // when tp.group('age'); scope.$digest(); // then expect(groupRow.querySelector('a > strong')!.textContent).toBe('Age'); }); it('tapping item in group list selector should change assigned group', () => { // when groupRow.querySelector('a')!.click(); groupRow.querySelector('.list-group')!.querySelectorAll('a')[1].click(); // then const assignedGroup = tp.group(); expect(Object.keys(assignedGroup)).toEqual(['age']); }); it('tapping existing selected item should change group sort order', () => { // check assumptions expect(tp.group()['name']).toBe('asc'); // when groupRow.querySelector('a')!.click(); groupRow.querySelector('.list-group')!.querySelectorAll('a')[0].click(); // then const assignedGroup = tp.group(); expect(assignedGroup['name']).toBe('desc'); }); it('tapping close button should hide the group row', () => { // when groupRow.querySelector('a')!.querySelector('button')!.click(); // then expect(groupRow.classList.contains('ng-hide')).toBe(true); }); describe('tapping close button', () => { let toggleButton: HTMLButtonElement; beforeEach(() => { toggleButton = groupRow.querySelector('a')!.querySelectorAll('button')[1]; }); it('should toggle isExpanded group option', () => { toggleButton.click(); expect(tp.settings().groupOptions.isExpanded).toBe(false); toggleButton.click(); expect(tp.settings().groupOptions.isExpanded).toBe(true); }); it('should trigger table reload', () => { (tp.settings().getData as jasmine.Spy).calls.reset(); toggleButton.click(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); }); }); }); }); describe('internals', () => { let tableElm: IAugmentedJQuery, $timeout: ITimeoutService; beforeEach(inject((_$timeout_: ITimeoutService) => { $timeout = _$timeout_; const html = `<table ng-table="tableParams"> <tr ng-repeat="user in $data"> <td title="\'Age\'">{{user.age}}</td> </tr> </table>`; ({ tableElm } = createTable(html)); })); it('should reload when binding a new tableParams to scope', () => { const tp = createNgTableParams<Person>(); scope.tableParams = tp; scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload 1 time when binding a new tableParams that has an initial settings dataset field', () => { const tp = createNgTableParams({ dataset: [{ age: 1 }] }); scope.tableParams = tp; scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload 1 time when binding a new tableParams with initial filter that has an initial settings dataset field', () => { const tp = createNgTableParams({ filter: { age: 1 } }, { dataset: [{ age: 1 }] }); scope.tableParams = tp; scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload when binding a new tableParams to scope multiple times', () => { const tp1 = createNgTableParams<Person>(); scope.tableParams = tp1; scope.$digest(); expect((tp1.settings().getData as jasmine.Spy).calls.count()).toBe(1); const tp2 = createNgTableParams<Person>(); scope.tableParams = tp2; scope.$digest(); expect((tp2.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload 1 time when binding a new settings dataset value and changing the filter', () => { // given const tp = createNgTableParams({ filterOptions: { filterDelay: 100 }, dataset: [{ age: 1 }, { age: 2 }] }); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 1 }); tp.settings({ dataset: [{ age: 1 }, { age: 11 }, { age: 22 }] }); scope.$digest(); $timeout.flush(); // trigger the delayed reload expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload 1 time when multiple filter changes are debounced', () => { // given const tp = createNgTableParams({ filterOptions: { filterDelay: 100 }, dataset: [{ age: 1 }, { age: 2 }] }); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 1 }); scope.$digest(); tp.filter({ age: 2 }); scope.$digest(); $timeout.flush(); // trigger the delayed reload expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload 1 time when initial load fails', inject(function ($q: IQService) { // given const tp = createNgTableParams<Person>({ getData: () => { return $q.reject('BANG!'); } }); // when scope.tableParams = tp; scope.$digest(); // then expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); })); it('should reload 1 time with page reset to 1 when binding a new settings dataset value and changing the filter', () => { const settings = { counts: [1], dataset: [{ age: 1 }, { age: 2 }], filterOptions: { filterDelay: 100 } }; const tp = createNgTableParams({ count: 1, page: 2 }, settings); scope.tableParams = tp; scope.$digest(); expect(tp.page()).toBe(2); // checking assumptions (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 1 }); tp.settings({ dataset: [{ age: 1 }, { age: 11 }, { age: 22 }] }); scope.$digest(); $timeout.flush(); // trigger the delayed reload expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); expect(tp.page()).toBe(1); }); it('changing filter, orderBy, or page and then calling reload should not invoke getData twice', () => { const tp = createNgTableParams<Person>(); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 5 }); tp.reload(); scope.$digest(); // then expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('change to filter that fails to load should not cause infinite reload loop', inject(function ($q: IQService) { const tp = createNgTableParams({ getData: function (): IPromise<any> | Person[] { if ((tp.settings().getData as jasmine.Spy).calls.count() > 1) { return $q.reject('BANG!'); } return [{ age: 1 }] } }); scope.tableParams = tp; scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); // checking assumptions expect(tp.isDataReloadRequired()).toBe(false); // checking assumptions // when tp.filter({ age: 5 }); expect(tp.isDataReloadRequired()).toBe(true); // checking assumptions scope.$digest(); // then expect(tp.isDataReloadRequired()).toBe(false); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(2); })); it('changing filter, orderBy, or page in a callback to reload should re-invoke getData 1 time only', () => { const tp = createNgTableParams<Person>(); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 5 }); tp.reload().then(() => { tp.sorting({ age: 'desc' }); // note: better to call tp.reload() here rather than rely on a watch firing later to do it for us // that way the second reload is chained to the first and returned as a single promise }); scope.$digest(); // then // ie calls.count() === (1 x reload) + (1 x sorting) expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(2); }); it('changing filter, orderBy, or page then reload in a callback to reload should re-invoke getData 1 time only', () => { // todo: refactor the watches in ngTableController to handle this case const tp = createNgTableParams<Person>(); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 5 }); tp.reload().then(() => { tp.sorting({ age: 'desc' }); return tp.reload(); }); scope.$digest(); // then // ie calls.count() === (1 x reload) + (1 x sorting) expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(2); }); it('should not reload when filter value is assigned the same value', () => { // given const tp = createNgTableParams<Person>({ filter: { age: 10 } }, {}); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 10 }); scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(0); }); it('should reload when filter value changes', () => { // given const tp = createNgTableParams<Person>({ filter: { age: 10 } }, {}); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.filter({ age: 12 }); scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); it('should reload when new dataset supplied', () => { // given const initialDataset = [ { age: 1 }, { age: 2 } ]; const tp = createNgTableParams<Person>(); scope.tableParams = tp; scope.$digest(); (tp.settings().getData as jasmine.Spy).calls.reset(); // when tp.settings({ dataset: [{ age: 10 }, { age: 11 }, { age: 12 }] }); scope.$digest(); expect((tp.settings().getData as jasmine.Spy).calls.count()).toBe(1); }); }); });
the_stack
import ExpGolomb from '../../util/exp-golumb'; let bitOffset = 0; export type SPSProps = { profile_idc: number; profile_compatibility: number; level_idc: number; sps_id: number; log2_max_frame_num_minus4: number; pic_order_cnt_type: number; log2_max_pic_order_cnt_lsb_minus4: number; width: number; height: number; pixelRatio: [number, number]; payload: Uint8Array; video_format: number; fps: number; fixedFPS: boolean; }; /** * 7.3.2.1.1.1 Scaling list syntax * @param scalingList * @param size */ function scaling_list(scalingList, size) { let lastScale = 8; let nextScale = 8; let delta_scale; for (var j = 0; j < size; j++) { if (nextScale != 0) { delta_scale = ExpGolomb.readUEV(scalingList, bitOffset); bitOffset += delta_scale.bitLength; nextScale = (lastScale + delta_scale.value + 256) % 256; } lastScale = scalingList[j]; } } /** * decode (SPS)Sequence parameter set * @param payload */ export function decodeSPS(payload: Uint8Array): SPSProps { bitOffset = 0; let profile_idc = payload[0]; let profile_compatibility = payload[1]; let level_idc = payload[2]; let golombBuffer = payload.subarray(3); let //separate_colour_plane_flag = 0, // qpprime_y_zero_transform_bypass_flag = 0, seq_scaling_matrix_present_flag = 0; let lmpoclmUEV; let //delta_pic_order_always_zero_flag = 0, ofnrpSEV, ofttbfSEV, nrfipoccUEV; let pixelRatio: [number, number] = [1, 1], pixelScale = 1; let video_format: number; let fps = 0, num_units_in_tick: number, time_scale: number, fixed_frame_rate_flag: boolean = true; // seq_parameter_set_id let spsUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += spsUEV.bitLength; if ( profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || profile_idc == 244 || profile_idc == 44 || profile_idc == 83 || profile_idc == 86 || profile_idc == 118 || profile_idc == 128 ) { // chroma_format_idc let chromaFIUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += chromaFIUEV.bitLength; if (chromaFIUEV.value == 3) { // separate_colour_plane_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; } // bit_depth_luma_minus8 let bitdlmUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += bitdlmUEV.bitLength; // bit_depth_chroma_minus8 let bitdcmUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += bitdcmUEV.bitLength; // qpprime_y_zero_transform_bypass_flag // qpprime_y_zero_transform_bypass_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; // seq_scaling_matrix_present_flag seq_scaling_matrix_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (seq_scaling_matrix_present_flag) { for (let i = 0; i < (chromaFIUEV.value != 3 ? 8 : 12); i++) { let seq_scaling_list_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (seq_scaling_list_present_flag) { if (i < 6) { scaling_list(golombBuffer, 16); } else { scaling_list(golombBuffer, 64); } } } } } // log2_max_frame_num_minus4 let lmfnmUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += lmfnmUEV.bitLength; // pic_order_cnt_type let poctUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); let pic_order_cnt_type = poctUEV.value; bitOffset += poctUEV.bitLength; if (pic_order_cnt_type === 0) { // log2_max_pic_order_cnt_lsb_minus4 lmpoclmUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += lmpoclmUEV.bitLength; } else if (pic_order_cnt_type === 1) { // delta_pic_order_always_zero_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; // offset_for_non_ref_pic ofnrpSEV = ExpGolomb.readSEV(golombBuffer, bitOffset); bitOffset += ofnrpSEV.bitLength; // offset_for_top_to_bottom_field ofttbfSEV = ExpGolomb.readSEV(golombBuffer, bitOffset); bitOffset += ofttbfSEV.bitLength; // num_ref_frames_in_pic_order_cnt_cycle nrfipoccUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += nrfipoccUEV.bitLength; // let offset_for_ref_frames = []; for (let i = 0, item; i < nrfipoccUEV.value; i++) { item = ExpGolomb.readSEV(golombBuffer, bitOffset); bitOffset += item.bitLength; // offset_for_ref_frames.push(item); } } // max_num_ref_frames // 指定参考帧队列可能达到的最大长度,解码器依照这个句法元素的值开辟存储区,这个存储区用于存放已解码的参考帧, // H.264 规定最多可用 16 个参考帧,本句法元素的值最大为 16。值得注意的是这个长度以帧为单位,如果在场模式下,应该相应地扩展一倍 let mnrfUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += mnrfUEV.bitLength; // gaps_in_frame_num_value_allowed_flag // let gaps_in_frame_num_value_allowed_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; // pic_width_in_mbs_minus1 let picWidthUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += picWidthUEV.bitLength; // pic_height_in_map_units_minus1 let picHeightUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += picHeightUEV.bitLength; // frame_mbs_only_flag // 本句法元素等于 1 时, 表示本序列中所有图像的编码模式都是帧编码; // 本句法元素等于 0 时, 表示本序列中图像的编码模式可能是帧,也可能是场或帧场自适应,某个图像具体是哪一种要由其他句法元素决定。 let frame_mbs_only_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (!frame_mbs_only_flag) { // mb_adaptive_frame_field_flag (Unused, Unnecessary to read it.) // ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; } // direct_8x8_inference_flag, 用于指明 B 片的直接 和 skip 模式下运动矢量的预测方法 // let direct_8x8_inference_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; // frame_cropping_flag, 用于指明解码器是否要将图像裁剪后输出,如果是的话,后面紧跟着的四个句法元素分别指出左右、上下裁剪的宽度 let frame_cropping_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; let cropLeft = 0, cropRight = 0, cropTop = 0, cropBottom = 0; if (frame_cropping_flag) { let fcloUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += fcloUEV.bitLength; cropLeft = fcloUEV.value; let fcroUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += fcroUEV.bitLength; cropRight = fcroUEV.value; let fctoUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += fctoUEV.bitLength; cropTop = fctoUEV.value; let fcboUEV = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += fcboUEV.bitLength; cropBottom = fcboUEV.value; } // vui_parameters_present_flag let vui_parameters_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (vui_parameters_present_flag) { // Annex E, E.1.1 VUI parameters syntax // VUI 用以表征视频格式等额外信息 // aspect_ratio, video_format let aspect_ratio_info_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (aspect_ratio_info_present_flag) { const aspectRatioIdc = ExpGolomb.readByte(golombBuffer, bitOffset); bitOffset += 8; switch (aspectRatioIdc) { case 1: pixelRatio = [1, 1]; break; case 2: pixelRatio = [12, 11]; break; case 3: pixelRatio = [10, 11]; break; case 4: pixelRatio = [16, 11]; break; case 5: pixelRatio = [40, 33]; break; case 6: pixelRatio = [24, 11]; break; case 7: pixelRatio = [20, 11]; break; case 8: pixelRatio = [32, 11]; break; case 9: pixelRatio = [80, 33]; break; case 10: pixelRatio = [18, 11]; break; case 11: pixelRatio = [15, 11]; break; case 12: pixelRatio = [64, 33]; break; case 13: pixelRatio = [160, 99]; break; case 14: pixelRatio = [4, 3]; break; case 15: pixelRatio = [3, 2]; break; case 16: pixelRatio = [2, 1]; break; case 255: { let width0 = ExpGolomb.readByte(golombBuffer, bitOffset); bitOffset += 8; let width1 = ExpGolomb.readByte(golombBuffer, bitOffset); bitOffset += 8; let height0 = ExpGolomb.readByte(golombBuffer, bitOffset); bitOffset += 8; let height1 = ExpGolomb.readByte(golombBuffer, bitOffset); bitOffset += 8; pixelRatio = [(width0 << 8) | width1, (height0 << 8) | height1]; break; } } if (pixelRatio) { pixelScale = pixelRatio[0] / pixelRatio[1]; } if (aspectRatioIdc === 255) { // sar_width bitOffset += 16; // sar_height bitOffset += 16; } } let overscan_info_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (overscan_info_present_flag) { bitOffset += 1; // overscan_appropriate_flag; } let video_signal_type_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (video_signal_type_present_flag) { /* Table E-2 – Meaning of video_format video_format Meaning 0 Component 1 PAL 2 NTSC 3 SECAM 4 MAC 5 Unspecified video format 6 Reserved 7 Reserved */ video_format = ExpGolomb.readBit(golombBuffer, bitOffset, 3); bitOffset += 3; // switch (video_format) { // } // let video_full_range_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; let colour_description_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (colour_description_present_flag) { // colour_primaries u(8) // transfer_characteristics u(8) // matrix_coefficients u(8) bitOffset += 24; } } let chroma_loc_info_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (chroma_loc_info_present_flag) { let chroma_sample_loc_type_top_field = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += chroma_sample_loc_type_top_field.bitLength; let chroma_sample_loc_type_bottom_field = ExpGolomb.readUEV(golombBuffer, bitOffset); bitOffset += chroma_sample_loc_type_bottom_field.bitLength; } let timing_info_present_flag = ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; if (timing_info_present_flag) { num_units_in_tick = ExpGolomb.readBit(golombBuffer, bitOffset, 32); bitOffset += 32; time_scale = ExpGolomb.readBit(golombBuffer, bitOffset, 32); bitOffset += 32; fixed_frame_rate_flag = !!ExpGolomb.readBit(golombBuffer, bitOffset); bitOffset += 1; fps = time_scale / (num_units_in_tick * 2); } // There is left VUI other's parameters to be decoded ... // For now, it is useless, so don't pass them. } // let FrameHeightInMbs = (2 - frame_mbs_only_flag) * (picHeightUEV.value + 1); // PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits return { payload: golombBuffer, profile_idc, profile_compatibility, level_idc, sps_id: spsUEV.value, // ue(v) log2_max_frame_num_minus4: poctUEV.value, // ue(v) pic_order_cnt_type, // ue(v) log2_max_pic_order_cnt_lsb_minus4: lmpoclmUEV ? lmpoclmUEV.value : 0, // ue(v) width: Math.ceil(((picWidthUEV.value + 1) * 16 - cropLeft * 2 - cropRight * 2) * pixelScale), // PicWidthInSamplesL = PicWidthInMbs * 16 height: (2 - frame_mbs_only_flag) * (picHeightUEV.value + 1) * 16 - cropTop * 2 - cropBottom * 2, pixelRatio, video_format, fps, fixedFPS: fixed_frame_rate_flag }; }
the_stack
var LOCAL_PERSISTENCE_KEY = "localStorageFilePersistence"; var FOLDER = "folder"; import $q = require("q") import decl = require("./vfsDecl") export function getInstance():decl.LocalStorageFileSystem{ var localStorage:decl.LocalStorage = new decl.LocalStorage(); var localStorageHelper:decl.LocalStorageHelper = (function (LOCAL_PERSISTENCE_KEY) { return { forEach: function(fn) { for (var key in localStorage) { if (localStorage.hasOwnProperty(key)) { // A key is a local storage file system entry if it starts //with LOCAL_PERSISTENCE_KEY + '.' if (key.indexOf(LOCAL_PERSISTENCE_KEY + '.') === 0) { fn(JSON.parse(localStorage.getItem(key))); } } } }, has: function(path) { var has = false; path = path || '/'; this.forEach(function(entry) { if (entry.path.toLowerCase() === path.toLowerCase()){ has = true; } }); return has; }, set: function(path, content) { localStorage.setItem( LOCAL_PERSISTENCE_KEY + '.' + path, JSON.stringify(content) ); }, get: function(path) { return JSON.parse(localStorage.getItem(LOCAL_PERSISTENCE_KEY + '.' + path)); }, remove: function(path) { localStorage.removeItem(LOCAL_PERSISTENCE_KEY + '.' + path); }, clear:function(){ localStorage.clear(); } }; })(LOCAL_PERSISTENCE_KEY); var localStorageFileSystem:decl.LocalStorageFileSystem = (function (/*$window,*/ $q, /*$prompt,*/ $timeout, localStorageHelper, FOLDER) { function fileNotFoundMessage(path) { return 'file with path="' + path + '" does not exist'; } function addChildren(entry, fn) { if (entry.type === FOLDER) { entry.children = fn(entry.path); } } function findFolder(path) { var entries = []; localStorageHelper.forEach(function (entry) { if (entry.path.toLowerCase() === path.toLowerCase()) { addChildren(entry, findFiles); entries.push(entry); } }); return entries.length > 0 ? entries[0] : null; } function findFiles(path) { if (path.lastIndexOf('/') !== path.length - 1) { path += '/'; } var entries = []; localStorageHelper.forEach(function (entry) { if (entry.path.toLowerCase() !== path.toLowerCase() && extractParentPath(entry.path) + '/' === path) { addChildren(entry, findFiles); entries.push(entry); } }); return entries; } /** * * Save in localStorage entries. * * File structure are objects that contain the following attributes: * * path: The full path (including the filename). * * content: The content of the file (only valid for files). * * isFolder: A flag that indicates whether is a folder or file. */ var service:any = {}; var delay = 25; service.supportsFolders = true; function validatePath(path):any { if (path.indexOf('/') !== 0) { return {valid: false, reason: 'Path should start with "/"'}; } return {valid: true}; } function isValidParent(path) { var parent = extractParentPath(path); if (!localStorageHelper.has(parent) && parent !== '') { return false; } return true; } function hasChildrens(path) { var has = false; localStorageHelper.forEach(function (entry) { if (entry.path.indexOf(path + '/') === 0) { has = true; } }); return has; } function extractNameFromPath(path) { var pathInfo = validatePath(path); if (!pathInfo.valid) { throw 'Invalid Path!'; } // When the path is ended in '/' if (path.lastIndexOf('/') === path.length - 1) { path = path.slice(0, -1); } return path.slice(path.lastIndexOf('/') + 1); } function extractParentPath(path) { var pathInfo = validatePath(path); if (!pathInfo.valid) { throw 'Invalid Path!'; } // When the path is ended in '/' if (path.lastIndexOf('/') === path.length - 1) { path = path.slice(0, -1); } return path.slice(0, path.lastIndexOf('/')); } /** * List files found in a given path. */ service.directory = function (path) { var deferred = $q.defer(); $timeout(function () { var isValidPath = validatePath(path); if (!isValidPath.valid) { deferred.reject(isValidPath.reason); return deferred.promise; } if (!localStorageHelper.has('/')) { localStorageHelper.set(path, { path: '/', name: '', type: 'folder', meta: { 'created': Math.round(new Date().getTime()/1000.0) } }); } deferred.resolve(findFolder(path)); }, delay); return deferred.promise; }; /** * Persist a file to an existing folder. */ service.save = function (path, content) { var deferred = $q.defer(); $timeout(function () { var name = extractNameFromPath(path); var entry = localStorageHelper.get(path); if (!isValidParent(path)){ deferred.reject(new Error('Parent folder does not exists: ' + path)); return deferred.promise; } var file = {}; if (entry) { if (entry.type === FOLDER) { deferred.reject('file has the same name as a folder'); return deferred.promise; } entry.content = content; entry.meta.lastUpdated = Math.round(new Date().getTime()/1000.0); file = entry; } else { file = { path: path, name: name, content: content, type: 'file', meta: { 'created': Math.round(new Date().getTime()/1000.0) } }; } localStorageHelper.set(path, file); deferred.resolve(null); }, delay); return deferred.promise; }; /** * Create the folders contained in a path. */ service.createFolder = function (path) { var deferred = $q.defer(); var isValidPath = validatePath(path); if (!isValidPath.valid) { deferred.reject(isValidPath.reason); return deferred.promise; } if (localStorageHelper.has(path)) { deferred.reject(new Error('Folder already exists: ' + path)); return deferred.promise; } var parent = extractParentPath(path); if (!localStorageHelper.has(parent)) { deferred.reject(new Error('Parent folder does not exists: ' + path)); return deferred.promise; } $timeout(function () { localStorageHelper.set(path, { path: path, name: extractNameFromPath(path), type: 'folder', meta: { 'created': Math.round(new Date().getTime()/1000.0) } }); deferred.resolve(null); }, delay); return deferred.promise; }; /** * Loads the content of a file. */ service.load = function (path) { var deferred = $q.defer(); $timeout(function () { var entry = localStorageHelper.get(path); if (entry && entry.type === 'file') { deferred.resolve(localStorageHelper.get(path).content); } else { deferred.reject(fileNotFoundMessage(path)); } }, delay); return deferred.promise; }; /** * Removes a file or directory. */ service.remove = function (path) { var deferred = $q.defer(); $timeout(function () { var entry = localStorageHelper.get(path); if (entry && entry.type === FOLDER && hasChildrens(path)) { deferred.reject('folder not empty'); return deferred.promise; } localStorageHelper.remove(path); deferred.resolve(null); }, delay); return deferred.promise; }; /** * Renames a file or directory */ service.rename = function (source, destination) { var deferred = $q.defer(); $timeout(function () { var sourceEntry = localStorageHelper.get(source); if (!sourceEntry) { deferred.reject('Source file or folder does not exists.'); return deferred.promise; } var destinationEntry = localStorageHelper.get(destination); if (destinationEntry) { deferred.reject('File or folder already exists.'); return deferred.promise; } if (!isValidParent(destination)) { deferred.reject('Destination folder does not exist.'); return deferred.promise; } sourceEntry.path = destination; sourceEntry.name = extractNameFromPath(destination); localStorageHelper.remove(destination); localStorageHelper.remove(source); localStorageHelper.set(destination, sourceEntry); if (sourceEntry.type === FOLDER) { // if (!isValidPath(destination)) { // deferred.reject('Destination is not a valid folder'); // return deferred.promise; // } //move all child items localStorageHelper.forEach(function (entry) { if (entry.path.toLowerCase() !== source.toLowerCase() && entry.path.indexOf(source) === 0) { var newPath = destination + entry.path.substring(source.length); localStorageHelper.remove(entry.path); entry.path = newPath; localStorageHelper.set(newPath, entry); } }); } deferred.resolve(null); }, delay); return deferred.promise; }; service.clear = function(){ localStorageHelper.clear(); } // service.exportFiles = function exportFiles() { // var jszip = new $window.JSZip(); // localStorageHelper.forEach(function (item) { // // Skip root folder // if (item.path === '/') { // return; // } // // // Skip meta files // if (item.name.slice(-5) === '.meta') { // return; // } // // var path = item.path.slice(1); // Remove starting slash // item.type === 'folder' ? jszip.folder(path) : jszip.file(path, item.content); // }); // // var fileName = $prompt('Please enter a ZIP file name:', 'api.zip'); // fileName && $window.saveAs(jszip.generate({type: 'blob'}), fileName); // }; return service; })(/*$window,*/ $q, /*$prompt,*/ setTimeout, localStorageHelper, FOLDER); return localStorageFileSystem; }
the_stack
import { ethers, network } from 'hardhat'; import { BigNumber, Signer } from 'ethers'; import { expect, use } from 'chai'; import { solidity } from 'ethereum-waffle'; import { CurrencyManager } from '@requestnetwork/currency'; import { TestERC20__factory, TestERC20, FakeSwapRouter__factory, FakeSwapRouter, AggregatorMock__factory, Erc20ConversionProxy, ERC20SwapToConversion, ChainlinkConversionPath, } from '../../src/types'; import { chainlinkConversionPath as chainlinkConvArtifact, erc20ConversionProxy as erc20ConversionProxyArtifact, erc20SwapConversionArtifact, } from '../../src/lib'; use(solidity); describe('contract: ERC20SwapToConversion', () => { let from: string; let to: string; let builder: string; let adminSigner: Signer; let signer: Signer; const currencyManager = CurrencyManager.getDefault(); const USDhash = currencyManager.fromSymbol('USD')!.hash; const exchangeRateOrigin = Math.floor(Date.now() / 1000); const referenceExample = '0xaaaa'; let paymentNetworkErc20: TestERC20; let spentErc20: TestERC20; let erc20ConversionProxy: Erc20ConversionProxy; let swapConversionProxy: ERC20SwapToConversion; let initialFromBalance: BigNumber; let fakeSwapRouter: FakeSwapRouter; let chainlinkConversion: ChainlinkConversionPath; let defaultSwapRouterAddress: string; let requestSwapFees = BigNumber.from(5); const fiatDecimal = BigNumber.from('100000000'); const erc20Decimal = BigNumber.from('1000000000000000000'); const erc20Liquidity = erc20Decimal.mul(100); before(async () => { [, from, to, builder] = (await ethers.getSigners()).map((s) => s.address); [adminSigner, signer] = await ethers.getSigners(); chainlinkConversion = chainlinkConvArtifact.connect(network.name, adminSigner); erc20ConversionProxy = erc20ConversionProxyArtifact.connect(network.name, adminSigner); swapConversionProxy = erc20SwapConversionArtifact.connect(network.name, adminSigner); await swapConversionProxy.updateConversionPathAddress(chainlinkConversion.address); await swapConversionProxy.updateRequestSwapFees(requestSwapFees); }); beforeEach(async () => { paymentNetworkErc20 = await new TestERC20__factory(adminSigner).deploy(erc20Decimal.mul(10000)); spentErc20 = await new TestERC20__factory(adminSigner).deploy(erc20Decimal.mul(1000)); // deploy fake chainlink conversion path, for 1 USD = 3 paymentNetworkERC20 const aggTest = await new AggregatorMock__factory(adminSigner).deploy(300000000, 8, 60); await chainlinkConversion.updateAggregator( USDhash, paymentNetworkErc20.address, aggTest.address, ); // Deploy a fake router and feed it with 200 payment ERC20 + 100 requested ERC20 // The fake router fakes 2 payment ERC20 = 1 requested ERC20 fakeSwapRouter = await new FakeSwapRouter__factory(adminSigner).deploy(); await spentErc20.transfer(fakeSwapRouter.address, erc20Liquidity); await paymentNetworkErc20.transfer(fakeSwapRouter.address, erc20Liquidity.mul(2)); defaultSwapRouterAddress = await swapConversionProxy.swapRouter(); await swapConversionProxy.setRouter(fakeSwapRouter.address); await swapConversionProxy.approveRouterToSpend(spentErc20.address); await swapConversionProxy.approvePaymentProxyToSpend( paymentNetworkErc20.address, erc20ConversionProxy.address, ); swapConversionProxy = await swapConversionProxy.connect(signer); // give payer some token await spentErc20.transfer(from, erc20Decimal.mul(600)); spentErc20 = TestERC20__factory.connect(spentErc20.address, signer); initialFromBalance = await spentErc20.balanceOf(from); await spentErc20.approve(swapConversionProxy.address, initialFromBalance); }); afterEach(async () => { swapConversionProxy = swapConversionProxy.connect(adminSigner); await swapConversionProxy.setRouter(defaultSwapRouterAddress); // The contract should never keep any fund const contractPaymentCcyBalance = await paymentNetworkErc20.balanceOf( swapConversionProxy.address, ); const contractRequestCcyBalance = await spentErc20.balanceOf(swapConversionProxy.address); expect(contractPaymentCcyBalance.toNumber()).to.equals(0); expect(contractRequestCcyBalance.toNumber()).to.equals(0); }); const expectPayerBalanceUnchanged = async () => { const finalFromBalance = await spentErc20.balanceOf(from); expect(finalFromBalance.toString()).to.equals(initialFromBalance.toString()); }; it('converts, swaps and pays the request', async function () { // Simulate request payment for 10 (fiat) + 1 (fiat) fee, in paymentNetworkErc20 await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, fiatDecimal.mul(10), erc20Decimal.mul(70), [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin + 1000, // _uniswapDeadline. 100 -> 1000: Too low value may lead to error (network dependent) 0, // _chainlinkMaxRateTimespan ), ) .to.emit(erc20ConversionProxy, 'TransferWithConversionAndReference') .withArgs( fiatDecimal.mul(10).toString(), ethers.utils.getAddress(USDhash), ethers.utils.keccak256(referenceExample), fiatDecimal.mul(1).toString(), '0', ) .to.emit(erc20ConversionProxy, 'TransferWithReferenceAndFee') .withArgs( ethers.utils.getAddress(paymentNetworkErc20.address), ethers.utils.getAddress(to), erc20Decimal.mul(10).mul(3).toString(), ethers.utils.keccak256(referenceExample), erc20Decimal.mul(1).mul(3).toString(), ethers.utils.getAddress(builder), ); const requestSwapFeesAmountInPaymentNetworkErc20 = erc20Decimal // Request amount to pay (10 + 1 (fee) USD) .mul(11) // USD to expected token ( * 3) .mul(3) // Compute the swap fees ( 0.5 %) - in expected token .mul(requestSwapFees) .div(1000); // Compute the swap fees ( * 2) - in payent token const requestSwapFeesAmountInSpentToken = requestSwapFeesAmountInPaymentNetworkErc20.mul(2); const finalBuilderBalance = await paymentNetworkErc20.balanceOf(builder); const finalIssuerBalance = await paymentNetworkErc20.balanceOf(to); const finalPayerBalance = await spentErc20.balanceOf(from); // 66 = (10 + 1) (USD) * 3 (ExpectedToken) * 2 (SpentToken) expect( initialFromBalance.sub(finalPayerBalance).toString(), 'payer balance is wrong', ).to.equals(erc20Decimal.mul(66).add(requestSwapFeesAmountInSpentToken).toString()); expect(finalBuilderBalance.toString(), 'builder balance is wrong').to.equals( erc20Decimal.mul(3).add(requestSwapFeesAmountInPaymentNetworkErc20).toString(), ); expect(finalIssuerBalance.toString(), 'issuer balance is wrong').to.equals( erc20Decimal.mul(30).toString(), ); }); it('does not pay anyone if I swap 0', async function () { await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, 0, 0, [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, 0, builder, exchangeRateOrigin + 1000, // _uniswapDeadline. 100 -> 1000: Too low value may lead to error (network dependent) 0, // _chainlinkMaxRateTimespan ), ) .to.emit(erc20ConversionProxy, 'TransferWithConversionAndReference') .withArgs( '0', ethers.utils.getAddress(USDhash), ethers.utils.keccak256(referenceExample), '0', '0', ) .to.emit(erc20ConversionProxy, 'TransferWithReferenceAndFee') .withArgs( ethers.utils.getAddress(paymentNetworkErc20.address), ethers.utils.getAddress(to), '0', ethers.utils.keccak256(referenceExample), '0', builder, ); const finalBuilderBalance = await paymentNetworkErc20.balanceOf(builder); const finalIssuerBalance = await paymentNetworkErc20.balanceOf(to); expect(finalBuilderBalance.toNumber()).to.equals(0); expect(finalIssuerBalance.toNumber()).to.equals(0); }); it('cannot swap with a too low maximum spent', async function () { await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, fiatDecimal.mul(10), erc20Decimal.mul(50), // Too low [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin + 1000, // _uniswapDeadline. 100 -> 1000: Too low value may lead to error (network dependent) 0, // _chainlinkMaxRateTimespan ), ).to.be.revertedWith('UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); await expectPayerBalanceUnchanged(); }); it('cannot swap with a past deadline', async function () { await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, fiatDecimal.mul(10), erc20Decimal.mul(50), [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin - 15, // past _uniswapDeadline 0, // _chainlinkMaxRateTimespan ), ).to.be.revertedWith('UniswapV2Router: EXPIRED'); await expectPayerBalanceUnchanged(); }); it('cannot swap more tokens than liquidity', async function () { const tooHighAmount = 100; expect(erc20Liquidity.lt(initialFromBalance), 'Test irrelevant with low balance').to.be.true; expect( erc20Liquidity.lt(erc20Decimal.mul(tooHighAmount).mul(3)), 'Test irrelevant with low amount', ).to.be.true; await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, fiatDecimal.mul(tooHighAmount), initialFromBalance, [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin + 1000, // _uniswapDeadline. 100 -> 1000: Too low value may lead to error (network dependent) 0, // _chainlinkMaxRateTimespan ), ).to.be.revertedWith('UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); await expectPayerBalanceUnchanged(); }); it('cannot swap more tokens than allowance', async function () { await spentErc20.approve(swapConversionProxy.address, erc20Decimal.mul(60)); await expect( swapConversionProxy.swapTransferWithReference( erc20ConversionProxy.address, to, fiatDecimal.mul(10), erc20Decimal.mul(66), [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin + 100, // _unisapDeadline 0, // _chainlinkMaxRateTimespan ), ).to.be.revertedWith('Could not transfer payment token from swapper-payer'); await expectPayerBalanceUnchanged(); }); it('Should not swap with a bad proxy address', async function () { // Simulate request payment for 10 (fiat) + 1 (fiat) fee, in paymentNetworkErc20 await expect( swapConversionProxy.swapTransferWithReference( chainlinkConversion.address, // random address that is not a conversion proxy to, fiatDecimal.mul(10), erc20Decimal.mul(70), [spentErc20.address, paymentNetworkErc20.address], // _uniswapPath [USDhash, paymentNetworkErc20.address], // _chainlinkPath referenceExample, fiatDecimal.mul(1), builder, exchangeRateOrigin + 1000, // _uniswapDeadline. 100 -> 1000: Too low value may lead to error (network dependent) 0, // _chainlinkMaxRateTimespan ), ).to.be.revertedWith('Invalid payment proxy'); }); });
the_stack
import { mat4, vec2, vec3 } from 'gl-matrix'; import { Camera, Canvas, Context, DefaultFramebuffer, EventProvider, GeosphereGeometry, Invalidate, Navigation, PlaneGeometry, Program, Renderer, Shader, Texture2D, Wizard, } from 'webgl-operate'; import { Example } from './example'; /* spellchecker: enable */ // tslint:disable:max-classes-per-file export class AreaLightRenderer extends Renderer { protected _camera: Camera; protected _navigation: Navigation; protected _plane: PlaneGeometry; protected _lightSphere: GeosphereGeometry; protected _roughness: number; protected _lightPosition: vec3; protected _albedoTexture: Texture2D; protected _roughnessTexture: Texture2D; protected _metallicTexture: Texture2D; protected _normalTexture: Texture2D; protected _program: Program; protected _uViewProjection: WebGLUniformLocation; protected _uModel: WebGLUniformLocation; protected _uEye: WebGLUniformLocation; protected _uRoughness: WebGLUniformLocation; protected _lightProgram: Program; protected _uViewProjectionLight: WebGLUniformLocation; protected _defaultFBO: DefaultFramebuffer; /** * Initializes and sets up buffer, cube geometry, camera and links shaders with program. * @param context - valid context to create the object for. * @param identifier - meaningful name for identification of this instance. * @param eventProvider - required for mouse interaction * @returns - whether initialization was successful */ protected onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { this._defaultFBO = new DefaultFramebuffer(context, 'DefaultFBO'); this._defaultFBO.initialize(); this._defaultFBO.bind(); const gl = context.gl; this._roughness = 0.5; this._plane = new PlaneGeometry(context, 'Plane'); this._plane.initialize(); this._plane.scale = vec2.fromValues(3.0, 3.0); this._lightSphere = new GeosphereGeometry(context, 'LightSphere', 0.25); this._lightSphere.initialize(); this._lightPosition = vec3.fromValues(0.0, 0.5, 0.0); const vert = new Shader(context, gl.VERTEX_SHADER, 'mesh.vert'); vert.initialize(require('./data/mesh.vert')); const frag = new Shader(context, gl.FRAGMENT_SHADER, 'arealight/mesh.frag'); frag.initialize(require('./data/arealight/mesh.frag')); this._program = new Program(context, 'AreaLightProgram'); this._program.initialize([vert, frag], false); this._program.attribute('a_vertex', this._plane.vertexLocation); this._program.attribute('a_texCoord', this._plane.texCoordLocation); this._program.link(); this._program.bind(); this._uViewProjection = this._program.uniform('u_viewProjection'); this._uModel = this._program.uniform('u_model'); this._uEye = this._program.uniform('u_eye'); this._uRoughness = this._program.uniform('u_roughness'); gl.uniform1i(this._program.uniform('u_albedoTexture'), 0); gl.uniform1i(this._program.uniform('u_roughnessTexture'), 1); gl.uniform1i(this._program.uniform('u_metallicTexture'), 2); gl.uniform1i(this._program.uniform('u_normalTexture'), 3); gl.uniformMatrix4fv(this._program.uniform('u_model'), gl.FALSE, this._plane.transformation); // Program for rendering the light source const lightFrag = new Shader(context, gl.FRAGMENT_SHADER, 'light.frag'); lightFrag.initialize(require('./data/arealight/light.frag')); this._lightProgram = new Program(context, 'LightProgram'); this._lightProgram.initialize([vert, lightFrag], false); this._lightProgram.attribute('a_vertex', this._lightSphere.vertexLocation); this._lightProgram.link(); this._lightProgram.bind(); const m = mat4.create(); gl.uniformMatrix4fv(this._lightProgram.uniform('u_model'), gl.FALSE, mat4.translate(m, m, this._lightPosition)); this._uViewProjectionLight = this._lightProgram.uniform('u_viewProjection'); /** * Textures taken from https://3dtextures.me/2018/11/19/metal-001/ and modified */ this._albedoTexture = new Texture2D(context, 'AlbedoTexture'); this._albedoTexture.initialize(1, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._albedoTexture.wrap(gl.REPEAT, gl.REPEAT); this._albedoTexture.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._albedoTexture.maxAnisotropy(Texture2D.MAX_ANISOTROPY); this._albedoTexture.fetch('/examples/data/imagebasedlighting/Metal_001_basecolor.png').then(() => { const gl = context.gl; this._program.bind(); gl.uniform1i(this._program.uniform('u_textured'), true); this.invalidate(true); }); this._roughnessTexture = new Texture2D(context, 'RoughnessTexture'); this._roughnessTexture.initialize(1, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._roughnessTexture.wrap(gl.REPEAT, gl.REPEAT); this._roughnessTexture.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._roughnessTexture.maxAnisotropy(Texture2D.MAX_ANISOTROPY); this._roughnessTexture.fetch('/examples/data/imagebasedlighting/Metal_001_roughness.png'); this._metallicTexture = new Texture2D(context, 'MetallicTexture'); this._metallicTexture.initialize(1, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._metallicTexture.wrap(gl.REPEAT, gl.REPEAT); this._metallicTexture.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._metallicTexture.maxAnisotropy(Texture2D.MAX_ANISOTROPY); this._metallicTexture.fetch('/examples/data/imagebasedlighting/Metal_001_metallic.png'); this._normalTexture = new Texture2D(context, 'NormalTexture'); this._normalTexture.initialize(1, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE); this._normalTexture.wrap(gl.REPEAT, gl.REPEAT); this._normalTexture.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._normalTexture.maxAnisotropy(Texture2D.MAX_ANISOTROPY); this._normalTexture.fetch('/examples/data/imagebasedlighting/Metal_001_normal.png'); this._camera = new Camera(); this._camera.center = vec3.fromValues(0.0, 0.0, 0.0); this._camera.up = vec3.fromValues(0.0, 1.0, 0.0); this._camera.eye = vec3.fromValues(0.0, 2.0, 3.0); this._camera.near = 1.0; this._camera.far = 8.0; this._navigation = new Navigation(callback, eventProvider); this._navigation.camera = this._camera; return true; } /** * Uninitializes buffers, geometry and program. */ protected onUninitialize(): void { super.uninitialize(); this._plane.uninitialize(); this._lightSphere.uninitialize(); this._program.uninitialize(); this._defaultFBO.uninitialize(); } protected onDiscarded(): void { this._altered.alter('canvasSize'); this._altered.alter('clearColor'); this._altered.alter('frameSize'); this._altered.alter('multiFrameNumber'); } /** * This is invoked in order to check if rendering of a frame is required by means of implementation specific * evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation, * frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have * changed or the renderer was invalidated @see{@link invalidate}. * @returns whether to redraw */ protected onUpdate(): boolean { this._navigation.update(); return this._altered.any || this._camera.altered; } /** * This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and * camera-updates. */ protected onPrepare(): void { if (this._altered.canvasSize) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; this._camera.viewport = this._canvasSize; } if (this._altered.clearColor) { this._defaultFBO.clearColor(this._clearColor); } this._altered.reset(); this._camera.altered = false; } protected onFrame(): void { const gl = this._context.gl; this._defaultFBO.bind(); this._defaultFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, true, false); gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.enable(gl.DEPTH_TEST); this._albedoTexture.bind(gl.TEXTURE0); this._roughnessTexture.bind(gl.TEXTURE1); this._metallicTexture.bind(gl.TEXTURE2); this._normalTexture.bind(gl.TEXTURE3); this._program.bind(); gl.uniformMatrix4fv(this._uViewProjection, gl.GL_FALSE, this._camera.viewProjection); gl.uniform3fv(this._uEye, this._camera.eye); gl.uniform1f(this._uRoughness, this._roughness); this._plane.bind(); this._plane.draw(); this._plane.unbind(); this._albedoTexture.unbind(gl.TEXTURE0); this._roughnessTexture.unbind(gl.TEXTURE1); this._metallicTexture.unbind(gl.TEXTURE2); this._normalTexture.unbind(gl.TEXTURE3); this._program.unbind(); // Render light source this._lightProgram.bind(); gl.uniformMatrix4fv(this._uViewProjectionLight, gl.GL_FALSE, this._camera.viewProjection); this._lightSphere.bind(); this._lightSphere.draw(); this._lightSphere.unbind(); this._lightProgram.unbind(); gl.cullFace(gl.BACK); gl.disable(gl.CULL_FACE); } protected onSwap(): void { } } export class AreaLightExample extends Example { private _canvas: Canvas; private _renderer: AreaLightRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { this._canvas = new Canvas(element, { antialias: false }); this._canvas.controller.multiFrameNumber = 1; this._canvas.framePrecision = Wizard.Precision.byte; this._canvas.frameScale = [1.0, 1.0]; this._renderer = new AreaLightRenderer(); this._canvas.renderer = this._renderer; return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): AreaLightRenderer { return this._renderer; } }
the_stack
import { Action } from '@ngrx/store'; // import type function import { type } from '../../shared/ngrx/type'; // import models import { AuthTokenInfo } from './models/auth-token-info.model'; import { AuthMethod } from './models/auth.method'; import { AuthStatus } from './models/auth-status.model'; export const AuthActionTypes = { AUTHENTICATE: type('dspace/auth/AUTHENTICATE'), AUTHENTICATE_ERROR: type('dspace/auth/AUTHENTICATE_ERROR'), AUTHENTICATE_SUCCESS: type('dspace/auth/AUTHENTICATE_SUCCESS'), AUTHENTICATED: type('dspace/auth/AUTHENTICATED'), AUTHENTICATED_ERROR: type('dspace/auth/AUTHENTICATED_ERROR'), AUTHENTICATED_SUCCESS: type('dspace/auth/AUTHENTICATED_SUCCESS'), CHECK_AUTHENTICATION_TOKEN: type('dspace/auth/CHECK_AUTHENTICATION_TOKEN'), CHECK_AUTHENTICATION_TOKEN_COOKIE: type('dspace/auth/CHECK_AUTHENTICATION_TOKEN_COOKIE'), RETRIEVE_AUTH_METHODS: type('dspace/auth/RETRIEVE_AUTH_METHODS'), RETRIEVE_AUTH_METHODS_SUCCESS: type('dspace/auth/RETRIEVE_AUTH_METHODS_SUCCESS'), RETRIEVE_AUTH_METHODS_ERROR: type('dspace/auth/RETRIEVE_AUTH_METHODS_ERROR'), REDIRECT_TOKEN_EXPIRED: type('dspace/auth/REDIRECT_TOKEN_EXPIRED'), REDIRECT_AUTHENTICATION_REQUIRED: type('dspace/auth/REDIRECT_AUTHENTICATION_REQUIRED'), REFRESH_TOKEN: type('dspace/auth/REFRESH_TOKEN'), REFRESH_TOKEN_SUCCESS: type('dspace/auth/REFRESH_TOKEN_SUCCESS'), REFRESH_TOKEN_ERROR: type('dspace/auth/REFRESH_TOKEN_ERROR'), RETRIEVE_TOKEN: type('dspace/auth/RETRIEVE_TOKEN'), ADD_MESSAGE: type('dspace/auth/ADD_MESSAGE'), RESET_MESSAGES: type('dspace/auth/RESET_MESSAGES'), LOG_OUT: type('dspace/auth/LOG_OUT'), LOG_OUT_ERROR: type('dspace/auth/LOG_OUT_ERROR'), LOG_OUT_SUCCESS: type('dspace/auth/LOG_OUT_SUCCESS'), SET_REDIRECT_URL: type('dspace/auth/SET_REDIRECT_URL'), RETRIEVE_AUTHENTICATED_EPERSON: type('dspace/auth/RETRIEVE_AUTHENTICATED_EPERSON'), RETRIEVE_AUTHENTICATED_EPERSON_SUCCESS: type('dspace/auth/RETRIEVE_AUTHENTICATED_EPERSON_SUCCESS'), RETRIEVE_AUTHENTICATED_EPERSON_ERROR: type('dspace/auth/RETRIEVE_AUTHENTICATED_EPERSON_ERROR'), REDIRECT_AFTER_LOGIN_SUCCESS: type('dspace/auth/REDIRECT_AFTER_LOGIN_SUCCESS'), SET_USER_AS_IDLE: type('dspace/auth/SET_USER_AS_IDLE'), UNSET_USER_AS_IDLE: type('dspace/auth/UNSET_USER_AS_IDLE') }; /* tslint:disable:max-classes-per-file */ /** * Authenticate. * @class AuthenticateAction * @implements {Action} */ export class AuthenticateAction implements Action { public type: string = AuthActionTypes.AUTHENTICATE; payload: { email: string; password: string }; constructor(email: string, password: string) { this.payload = { email, password }; } } /** * Checks if user is authenticated. * @class AuthenticatedAction * @implements {Action} */ export class AuthenticatedAction implements Action { public type: string = AuthActionTypes.AUTHENTICATED; payload: AuthTokenInfo; constructor(token: AuthTokenInfo) { this.payload = token; } } /** * Authenticated check success. * @class AuthenticatedSuccessAction * @implements {Action} */ export class AuthenticatedSuccessAction implements Action { public type: string = AuthActionTypes.AUTHENTICATED_SUCCESS; payload: { authenticated: boolean; authToken: AuthTokenInfo; userHref: string }; constructor(authenticated: boolean, authToken: AuthTokenInfo, userHref: string) { this.payload = { authenticated, authToken, userHref }; } } /** * Authenticated check error. * @class AuthenticatedErrorAction * @implements {Action} */ export class AuthenticatedErrorAction implements Action { public type: string = AuthActionTypes.AUTHENTICATED_ERROR; payload: Error; constructor(payload: Error) { this.payload = payload; } } /** * Authentication error. * @class AuthenticationErrorAction * @implements {Action} */ export class AuthenticationErrorAction implements Action { public type: string = AuthActionTypes.AUTHENTICATE_ERROR; payload: Error; constructor(payload: Error) { this.payload = payload; } } /** * Authentication success. * @class AuthenticationSuccessAction * @implements {Action} */ export class AuthenticationSuccessAction implements Action { public type: string = AuthActionTypes.AUTHENTICATE_SUCCESS; payload: AuthTokenInfo; constructor(token: AuthTokenInfo) { this.payload = token; } } /** * Check if token is already present upon initial load. * @class CheckAuthenticationTokenAction * @implements {Action} */ export class CheckAuthenticationTokenAction implements Action { public type: string = AuthActionTypes.CHECK_AUTHENTICATION_TOKEN; } /** * Check Authentication Token Error. * @class CheckAuthenticationTokenCookieAction * @implements {Action} */ export class CheckAuthenticationTokenCookieAction implements Action { public type: string = AuthActionTypes.CHECK_AUTHENTICATION_TOKEN_COOKIE; } /** * Sign out. * @class LogOutAction * @implements {Action} */ export class LogOutAction implements Action { public type: string = AuthActionTypes.LOG_OUT; constructor(public payload?: any) { } } /** * Sign out error. * @class LogOutErrorAction * @implements {Action} */ export class LogOutErrorAction implements Action { public type: string = AuthActionTypes.LOG_OUT_ERROR; payload: Error; constructor(payload: Error) { this.payload = payload; } } /** * Sign out success. * @class LogOutSuccessAction * @implements {Action} */ export class LogOutSuccessAction implements Action { public type: string = AuthActionTypes.LOG_OUT_SUCCESS; constructor(public payload?: any) { } } /** * Redirect to login page when authentication is required. * @class RedirectWhenAuthenticationIsRequiredAction * @implements {Action} */ export class RedirectWhenAuthenticationIsRequiredAction implements Action { public type: string = AuthActionTypes.REDIRECT_AUTHENTICATION_REQUIRED; payload: string; constructor(message: string) { this.payload = message; } } /** * Redirect to login page when token is expired. * @class RedirectWhenTokenExpiredAction * @implements {Action} */ export class RedirectWhenTokenExpiredAction implements Action { public type: string = AuthActionTypes.REDIRECT_TOKEN_EXPIRED; payload: string; constructor(message: string) { this.payload = message; } } /** * Refresh authentication token. * @class RefreshTokenAction * @implements {Action} */ export class RefreshTokenAction implements Action { public type: string = AuthActionTypes.REFRESH_TOKEN; payload: AuthTokenInfo; constructor(token: AuthTokenInfo) { this.payload = token; } } /** * Refresh authentication token success. * @class RefreshTokenSuccessAction * @implements {Action} */ export class RefreshTokenSuccessAction implements Action { public type: string = AuthActionTypes.REFRESH_TOKEN_SUCCESS; payload: AuthTokenInfo; constructor(token: AuthTokenInfo) { this.payload = token; } } /** * Refresh authentication token error. * @class RefreshTokenErrorAction * @implements {Action} */ export class RefreshTokenErrorAction implements Action { public type: string = AuthActionTypes.REFRESH_TOKEN_ERROR; } /** * Retrieve authentication token. * @class RetrieveTokenAction * @implements {Action} */ export class RetrieveTokenAction implements Action { public type: string = AuthActionTypes.RETRIEVE_TOKEN; } /** * Add uthentication message. * @class AddAuthenticationMessageAction * @implements {Action} */ export class AddAuthenticationMessageAction implements Action { public type: string = AuthActionTypes.ADD_MESSAGE; payload: string; constructor(message: string) { this.payload = message; } } /** * Reset error. * @class ResetAuthenticationMessagesAction * @implements {Action} */ export class ResetAuthenticationMessagesAction implements Action { public type: string = AuthActionTypes.RESET_MESSAGES; } // // Next three Actions are used by dynamic login methods /** * Action that triggers an effect fetching the authentication methods enabled ant the backend * @class RetrieveAuthMethodsAction * @implements {Action} */ export class RetrieveAuthMethodsAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTH_METHODS; payload: AuthStatus; constructor(authStatus: AuthStatus) { this.payload = authStatus; } } /** * Get Authentication methods enabled at the backend * @class RetrieveAuthMethodsSuccessAction * @implements {Action} */ export class RetrieveAuthMethodsSuccessAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTH_METHODS_SUCCESS; payload: AuthMethod[]; constructor(authMethods: AuthMethod[] ) { this.payload = authMethods; } } /** * Set password as default authentication method on error * @class RetrieveAuthMethodsErrorAction * @implements {Action} */ export class RetrieveAuthMethodsErrorAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTH_METHODS_ERROR; } /** * Change the redirect url. * @class SetRedirectUrlAction * @implements {Action} */ export class SetRedirectUrlAction implements Action { public type: string = AuthActionTypes.SET_REDIRECT_URL; payload: string; constructor(url: string) { this.payload = url; } } /** * Start loading for a hard redirect * @class StartHardRedirectLoadingAction * @implements {Action} */ export class RedirectAfterLoginSuccessAction implements Action { public type: string = AuthActionTypes.REDIRECT_AFTER_LOGIN_SUCCESS; payload: string; constructor(url: string) { this.payload = url; } } /** * Retrieve the authenticated eperson. * @class RetrieveAuthenticatedEpersonAction * @implements {Action} */ export class RetrieveAuthenticatedEpersonAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTHENTICATED_EPERSON; payload: string; constructor(user: string) { this.payload = user ; } } /** * Set the authenticated eperson in the state. * @class RetrieveAuthenticatedEpersonSuccessAction * @implements {Action} */ export class RetrieveAuthenticatedEpersonSuccessAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTHENTICATED_EPERSON_SUCCESS; payload: string; constructor(userId: string) { this.payload = userId ; } } /** * Set the authenticated eperson in the state. * @class RetrieveAuthenticatedEpersonSuccessAction * @implements {Action} */ export class RetrieveAuthenticatedEpersonErrorAction implements Action { public type: string = AuthActionTypes.RETRIEVE_AUTHENTICATED_EPERSON_ERROR; payload: Error; constructor(payload: Error) { this.payload = payload ; } } /** * Set the current user as being idle. * @class SetUserAsIdleAction * @implements {Action} */ export class SetUserAsIdleAction implements Action { public type: string = AuthActionTypes.SET_USER_AS_IDLE; } /** * Unset the current user as being idle. * @class UnsetUserAsIdleAction * @implements {Action} */ export class UnsetUserAsIdleAction implements Action { public type: string = AuthActionTypes.UNSET_USER_AS_IDLE; } /* tslint:enable:max-classes-per-file */ /** * Actions type. * @type {AuthActions} */ export type AuthActions = AuthenticateAction | AuthenticatedAction | AuthenticatedErrorAction | AuthenticatedSuccessAction | AuthenticationErrorAction | AuthenticationSuccessAction | CheckAuthenticationTokenAction | CheckAuthenticationTokenCookieAction | RedirectWhenAuthenticationIsRequiredAction | RedirectWhenTokenExpiredAction | AddAuthenticationMessageAction | RefreshTokenAction | RefreshTokenErrorAction | RefreshTokenSuccessAction | ResetAuthenticationMessagesAction | RetrieveAuthMethodsAction | RetrieveAuthMethodsSuccessAction | RetrieveAuthMethodsErrorAction | RetrieveTokenAction | RetrieveAuthenticatedEpersonAction | RetrieveAuthenticatedEpersonErrorAction | RetrieveAuthenticatedEpersonSuccessAction | SetRedirectUrlAction | RedirectAfterLoginSuccessAction | SetUserAsIdleAction | UnsetUserAsIdleAction;
the_stack
import * as realFS from 'fs'; import * as memfs from 'memfs'; import { builtinModules } from 'module'; import path from 'path'; import dedent from 'ts-dedent'; import * as unionfs from 'unionfs'; import util from 'util'; import { v4 as uuid4 } from 'uuid'; import webpack from 'webpack'; import { DefaultLogger, Logger } from '../logger'; export const allowedBuiltinModules = ['assert']; export const disallowedBuiltinModules = builtinModules.filter((module) => !allowedBuiltinModules.includes(module)); export function moduleMatches(userModule: string, modules: string[]): boolean { return modules.some((module) => userModule === module || userModule.startsWith(`${module}/`)); } /** * Builds a V8 Isolate by bundling provided Workflows using webpack. * * @param workflowsPath all Workflows found in path will be put in the bundle * @param workflowInterceptorModules list of interceptor modules to register on Workflow creation */ export class WorkflowCodeBundler { private foundProblematicModules = new Set<string>(); public readonly logger: Logger; public readonly workflowsPath: string; public readonly workflowInterceptorModules: string[]; protected readonly payloadConverterPath?: string; protected readonly ignoreModules: string[]; constructor({ logger, workflowsPath, payloadConverterPath, workflowInterceptorModules, ignoreModules, }: BundleOptions) { this.logger = logger ?? new DefaultLogger('INFO'); this.workflowsPath = workflowsPath; this.payloadConverterPath = payloadConverterPath; this.workflowInterceptorModules = workflowInterceptorModules ?? []; this.ignoreModules = ignoreModules ?? []; } /** * @return a string representation of the bundled Workflow code */ public async createBundle(): Promise<string> { const vol = new memfs.Volume(); const ufs = new unionfs.Union(); /** * readdir and exclude sourcemaps and d.ts files */ function readdir(...args: Parameters<typeof realFS.readdir>) { // Help TS a bit because readdir has multiple signatures const callback: (err: NodeJS.ErrnoException | null, files: string[]) => void = args.pop() as any; const newArgs: Parameters<typeof realFS.readdir> = [ ...args, (err: Error | null, files: string[]) => { if (err !== null) { callback(err, []); return; } callback( null, files.filter((f) => /\.[jt]s$/.test(path.extname(f)) && !f.endsWith('.d.ts')) ); }, ] as any; return realFS.readdir(...newArgs); } // Cast because the type definitions are inaccurate const memoryFs = memfs.createFsFromVolume(vol); ufs.use(memoryFs as any).use({ ...realFS, readdir: readdir as any }); const distDir = '/dist'; const entrypointPath = this.makeEntrypointPath(ufs, this.workflowsPath); this.genEntrypoint(vol, entrypointPath); await this.bundle(ufs, memoryFs, entrypointPath, distDir); // Cast because the type definitions are inaccurate return memoryFs.readFileSync(path.join(distDir, 'main.js'), 'utf8') as string; } protected makeEntrypointPath(fs: typeof unionfs.ufs, workflowsPath: string): string { const stat = fs.statSync(workflowsPath); if (stat.isFile()) { // workflowsPath is a file; make the entrypoint a sibling of that file const { root, dir, name } = path.parse(workflowsPath); return path.format({ root, dir, base: `${name}-entrypoint-${uuid4()}.js` }); } else { // workflowsPath is a directory; make the entrypoint a sibling of that directory const { root, dir, base } = path.parse(workflowsPath); return path.format({ root, dir, base: `${base}-entrypoint-${uuid4()}.js` }); } } /** * Creates the main entrypoint for the generated webpack library. * * Exports all detected Workflow implementations and some workflow libraries to be used by the Worker. */ protected genEntrypoint(vol: typeof memfs.vol, target: string): void { const interceptorImports = [...new Set(this.workflowInterceptorModules)] .map((v) => `import(/* webpackMode: "eager" */ ${JSON.stringify(v)})`) .join(', \n'); const code = dedent` import * as api from '@temporalio/workflow/lib/worker-interface.js'; // Bundle all Workflows and interceptor modules for lazy evaluation api.overrideGlobals(); api.setImportFuncs({ importWorkflows: () => { return import(/* webpackMode: "eager" */ ${JSON.stringify(this.workflowsPath)}); }, importInterceptors: () => { return Promise.all([ ${interceptorImports} ]); } }); export { api }; `; try { vol.mkdirSync(path.dirname(target), { recursive: true }); } catch (err: any) { if (err.code !== 'EEXIST') throw err; } vol.writeFileSync(target, code); } /** * Run webpack */ protected async bundle( inputFilesystem: typeof unionfs.ufs, outputFilesystem: memfs.IFs, entry: string, distDir: string ): Promise<void> { const captureProblematicModules: webpack.Configuration['externals'] = async ( data, _callback ): Promise<undefined> => { // Ignore the "node:" prefix if any. const module: string = data.request?.startsWith('node:') ? data.request.slice('node:'.length) : data.request ?? ''; if (moduleMatches(module, disallowedBuiltinModules) && !moduleMatches(module, this.ignoreModules)) { this.foundProblematicModules.add(module); } return undefined; }; const compiler = webpack({ resolve: { // https://webpack.js.org/configuration/resolve/#resolvemodules modules: [path.resolve(__dirname, 'module-overrides'), 'node_modules'], extensions: ['.ts', '.js'], alias: { __temporal_custom_payload_converter$: this.payloadConverterPath ?? false, ...Object.fromEntries([...this.ignoreModules, ...disallowedBuiltinModules].map((m) => [m, false])), }, }, externals: captureProblematicModules, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: { loader: require.resolve('swc-loader'), options: { jsc: { target: 'es2017', parser: { syntax: 'typescript', decorators: true, }, }, }, }, }, ], }, entry: [entry], mode: 'development', // Recommended choice for development builds with high quality SourceMaps devtool: 'eval-source-map', output: { path: distDir, filename: 'main.js', library: '__TEMPORAL__', }, }); // Cast to any because the type declarations are inaccurate compiler.inputFileSystem = inputFilesystem as any; // Don't use ufs due to a strange bug on Windows: // https://github.com/temporalio/sdk-typescript/pull/554 compiler.outputFileSystem = outputFilesystem as any; try { await new Promise<void>((resolve, reject) => { compiler.run((err, stats) => { if (stats !== undefined) { const hasError = stats.hasErrors(); // To debug webpack build: // const lines = stats.toString({ preset: 'verbose' }).split('\n'); const lines = stats.toString({ chunks: false, colors: true, errorDetails: true }).split('\n'); for (const line of lines) { this.logger[hasError ? 'error' : 'info'](line); } if (hasError) { reject( new Error( "Webpack finished with errors, if you're unsure what went wrong, visit our troubleshooting page at https://docs.temporal.io/typescript/troubleshooting#webpack-errors" ) ); } if (this.foundProblematicModules.size) { const err = new Error( `Your Workflow code (or a library used by your Workflow code) is importing the following built-in Node modules:\n` + Array.from(this.foundProblematicModules) .map((module) => ` - '${module}'\n`) .join('') + `Workflow code doesn't have access to built-in Node modules (in order to help enforce determinism). If you are certain ` + `these modules will not be used at runtime, then you may add their names to 'WorkerOptions.bundlerOptions.ignoreModules' in order to ` + `dismiss this warning. However, if your code execution actually depends on these modules, then you must change the code ` + `or remove the library.\n` + `See https://typescript.temporal.io/api/interfaces/worker.workeroptions/#bundleroptions for details.` ); reject(err); } } if (err) { reject(err); } else { resolve(); } }); }); } finally { await util.promisify(compiler.close).bind(compiler)(); } } } /** * Options for bundling Workflow code using Webpack */ export interface BundleOptions { /** * Path to look up workflows in, any function exported in this path will be registered as a Workflows when the bundle is loaded by a Worker. */ workflowsPath: string; /** * List of modules to import Workflow interceptors from * * Modules should export an `interceptors` variable of type {@link WorkflowInterceptorsFactory}. */ workflowInterceptorModules?: string[]; /** * Optional logger for logging Webpack output */ logger?: Logger; /** * Path to a module with a `payloadConverter` named export. * `payloadConverter` should be an instance of a class that extends {@link DataConverter}. */ payloadConverterPath?: string; /** * List of modules to be excluded from the Workflows bundle. * * Use this option when your Workflow code references an import that cannot be used in isolation, * e.g. a Node.js built-in module. Modules listed here **MUST** not be used at runtime. * * > NOTE: This is an advanced option that should be used with care. */ ignoreModules?: string[]; } export async function bundleWorkflowCode(options: BundleOptions): Promise<{ code: string }> { const bundler = new WorkflowCodeBundler(options); return { code: await bundler.createBundle() }; }
the_stack
import { RpcClient } from '@taquito/rpc'; import { retry, tap } from 'rxjs/operators'; import { Protocols } from '../src/constants'; import { Context } from '../src/context'; describe('Configurations for the confirmation methods and streamer', () => { let mockRpcClient: any; let context: Context; beforeAll(() => { mockRpcClient = { getConstants: jest.fn() }; context = new Context(mockRpcClient); }); it('Context is initialized with default config values except for the confirmationPollingIntervalSecond property', () => { expect(context.config.confirmationPollingIntervalSecond).toBeUndefined(); expect(context.config.confirmationPollingTimeoutSecond).toEqual(180); expect(context.config.defaultConfirmationCount).toEqual(1); expect(context.config.streamerPollingIntervalMilliseconds).toEqual(20000); expect(context.config.shouldObservableSubscriptionRetry).toBeFalsy(); expect(context.config.observableSubscriptionRetryFunction.prototype).toEqual(retry().prototype); }); it('Calling the getConfirmationPollingInterval should set the confirmationPollingIntervalSecond based on RPC constants', async (done) => { mockRpcClient.getConstants.mockResolvedValue({ "time_between_blocks": [ "30", "20" ], "endorsers_per_block": 32, "minimal_block_delay": 15, "initial_endorsers": 24, "delay_per_missing_endorsement": "4" }); await context.getConfirmationPollingInterval(); expect(context.config.confirmationPollingIntervalSecond).toEqual(5); expect(context.config.confirmationPollingTimeoutSecond).toEqual(180); expect(context.config.defaultConfirmationCount).toEqual(1); expect(context.config.streamerPollingIntervalMilliseconds).toEqual(20000); expect(context.config.shouldObservableSubscriptionRetry).toBeFalsy(); expect(context.config.observableSubscriptionRetryFunction.prototype).toEqual(retry().prototype); done() }); it('Configurations for the confirmation methods and streamer are customizable via the config setter', () => { context.config = { confirmationPollingIntervalSecond: 10, confirmationPollingTimeoutSecond: 300, defaultConfirmationCount: 2, streamerPollingIntervalMilliseconds: 10000, shouldObservableSubscriptionRetry: true, observableSubscriptionRetryFunction: tap() } expect(context.config.confirmationPollingIntervalSecond).toEqual(10); expect(context.config.confirmationPollingTimeoutSecond).toEqual(300); expect(context.config.defaultConfirmationCount).toEqual(2); expect(context.config.streamerPollingIntervalMilliseconds).toEqual(10000); expect(context.config.shouldObservableSubscriptionRetry).toBeTruthy(); expect(context.config.observableSubscriptionRetryFunction.prototype).toEqual(tap().prototype); }); it('Configurations for the confirmation methods and streamer can be partially customized using the setPartialConfig method', () => { context.setPartialConfig({ defaultConfirmationCount: 3, streamerPollingIntervalMilliseconds: 4000 }); expect(context.config.confirmationPollingIntervalSecond).toEqual(10); expect(context.config.defaultConfirmationCount).toEqual(3); expect(context.config.streamerPollingIntervalMilliseconds).toEqual(4000); expect(context.config.shouldObservableSubscriptionRetry).toBeTruthy(); expect(context.config.observableSubscriptionRetryFunction.prototype).toEqual(tap().prototype); }); }) describe('Taquito context class', () => { let mockRpcClient: any; beforeEach(() => { mockRpcClient = { getConstants: jest.fn() }; }); it('getConfirmationPollingInterval should return polling interval for sandbox environment', async () => { mockRpcClient.getConstants.mockResolvedValue({ "proof_of_work_nonce_size": 8, "nonce_length": 32, "max_anon_ops_per_block": 132, "max_operation_data_length": 16384, "max_proposals_per_delegate": 20, "preserved_cycles": 3, "blocks_per_cycle": 2048, "blocks_per_commitment": 16, "blocks_per_roll_snapshot": 128, "blocks_per_voting_period": 4096, "time_between_blocks": [ "2", "3" ], "endorsers_per_block": 32, "hard_gas_limit_per_operation": "1040000", "hard_gas_limit_per_block": "10400000", "proof_of_work_threshold": "70368744177663", "tokens_per_roll": "8000000000", "michelson_maximum_type_size": 1000, "seed_nonce_revelation_tip": "125000", "origination_size": 257, "block_security_deposit": "512000000", "endorsement_security_deposit": "64000000", "baking_reward_per_endorsement": [ "1250000", "187500" ], "endorsement_reward": [ "1250000", "833333" ], "cost_per_byte": "250", "hard_storage_limit_per_operation": "60000", "test_chain_duration": "61440", "quorum_min": 2000, "quorum_max": 7000, "min_proposal_quorum": 500, "initial_endorsers": 1, "delay_per_missing_endorsement": "1" }); const pollingInterval = await new Context(mockRpcClient).getConfirmationPollingInterval(); expect(pollingInterval).toBe(2/3); }); it('getConfirmationPollingInterval should return polling interval for production environment', async () => { mockRpcClient.getConstants.mockResolvedValue({ "proof_of_work_nonce_size": 8, "nonce_length": 32, "max_anon_ops_per_block": 132, "max_operation_data_length": 16384, "max_proposals_per_delegate": 20, "preserved_cycles": 3, "blocks_per_cycle": 2048, "blocks_per_commitment": 16, "blocks_per_roll_snapshot": 128, "blocks_per_voting_period": 4096, "time_between_blocks": [ "30", "20" ], "endorsers_per_block": 32, "hard_gas_limit_per_operation": "1040000", "hard_gas_limit_per_block": "10400000", "proof_of_work_threshold": "70368744177663", "tokens_per_roll": "8000000000", "michelson_maximum_type_size": 1000, "seed_nonce_revelation_tip": "125000", "origination_size": 257, "block_security_deposit": "512000000", "endorsement_security_deposit": "64000000", "baking_reward_per_endorsement": [ "1250000", "187500" ], "minimal_block_delay": 15, "endorsement_reward": [ "1250000", "833333" ], "cost_per_byte": "250", "hard_storage_limit_per_operation": "60000", "test_chain_duration": "61440", "quorum_min": 2000, "quorum_max": 7000, "min_proposal_quorum": 500, "initial_endorsers": 24, "delay_per_missing_endorsement": "4" }); const pollingInterval = await new Context(mockRpcClient).getConfirmationPollingInterval(); expect(pollingInterval).toBe(5); }); it('getConfirmationPollingInterval should return polling interval when rpc call to get constants file fails', async () => { mockRpcClient.getConstants.mockImplementation(() => { throw new Error(); }); const pollingInterval = await new Context(mockRpcClient).getConfirmationPollingInterval(); expect(pollingInterval).toBe(5); }); }); describe('registerProviderDecorator', () => { let rpcClient: RpcClient; let context: Context; beforeAll(() => { rpcClient = new RpcClient('url1'); context = new Context(rpcClient); }); it('Add a decorator to the context that replace the RpcClient', () => { // The decorator is a function that receives a context as parameter, replaces the RpcClient on it and returns the context const setNewRpcClient = (context: Context) => { context.rpc = new RpcClient('url2'); return context; } // save the decorator on the context context.registerProviderDecorator(setNewRpcClient); // call the withExtensions method to access a cloned context with the applied decorator expect(context.rpc.getRpcUrl()).toEqual('url1'); expect(context.withExtensions().rpc.getRpcUrl()).toEqual('url2'); }); it('Add multiple decorators on the context', () => { // The decorator 1 is a function that receives a context as parameter, replaces the RpcClient on it and returns the context const setNewRpcClient = (context: Context) => { context.rpc = new RpcClient('url2'); return context; }; context.registerProviderDecorator(setNewRpcClient); // The decorator 2 is a function that receives a context as parameter, replaces the proto on it and returns the context const setNewProto = (context: Context) => { context.proto = Protocols.PtGRANADs; return context; } context.registerProviderDecorator(setNewProto); // call the withExtensions method to access a cloned context with the applied decorator expect(context.rpc.getRpcUrl()).toEqual('url1'); expect(context.withExtensions().rpc.getRpcUrl()).toEqual('url2'); expect(context.proto).toBeUndefined(); expect(context.withExtensions().proto).toEqual(Protocols.PtGRANADs); }); })
the_stack
import { ArticleDisplay, ArticleDesign, ArticleSpecial, ArticlePillar, } from '@guardian/libs'; import type { ArticleFormat } from '@guardian/libs'; import { neutral, text, specialReport, opinion, news, sport, brandAltBackground, border, brand, brandAlt, lifestyle, culture, labs, } from '@guardian/source-foundations'; // Here is the one place where we use `pillarPalette` import { pillarPalette_DO_NOT_USE as pillarPalette } from '@root/src/lib/pillars'; const WHITE = neutral[100]; const BLACK = neutral[7]; const blogsGrayBackgroundPalette = (format: ArticleFormat): string => { switch (format.theme) { case ArticlePillar.News: case ArticlePillar.Lifestyle: case ArticlePillar.Sport: return pillarPalette[format.theme].main; default: return pillarPalette[format.theme].dark; } }; const textHeadline = (format: ArticleFormat): string => { switch (format.display) { case ArticleDisplay.Immersive: if (format.theme === ArticleSpecial.SpecialReport) return WHITE; switch (format.design) { case ArticleDesign.PrintShop: return BLACK; default: return WHITE; } case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: { if ( format.theme === ArticleSpecial.SpecialReport && format.design !== ArticleDesign.Interview ) return specialReport[100]; switch (format.design) { case ArticleDesign.Review: case ArticleDesign.Recipe: case ArticleDesign.Feature: return pillarPalette[format.theme].dark; case ArticleDesign.Interview: case ArticleDesign.LiveBlog: return WHITE; default: return BLACK; } } default: return BLACK; } }; const textSeriesTitle = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; switch (format.display) { case ArticleDisplay.Immersive: return WHITE; case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: switch (format.design) { case ArticleDesign.LiveBlog: switch (format.theme) { case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: case ArticlePillar.Lifestyle: case ArticlePillar.Culture: case ArticlePillar.Opinion: default: return WHITE; } case ArticleDesign.DeadBlog: return blogsGrayBackgroundPalette(format); case ArticleDesign.MatchReport: return BLACK; default: return pillarPalette[format.theme].main; } default: return BLACK; } }; const textSectionTitle = textSeriesTitle; const textByline = (format: ArticleFormat): string => { if ( format.design === ArticleDesign.LiveBlog || format.design === ArticleDesign.DeadBlog ) return blogsGrayBackgroundPalette(format); if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; switch (format.display) { case ArticleDisplay.Immersive: return WHITE; case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: switch (format.design) { case ArticleDesign.Interview: return BLACK; default: return pillarPalette[format.theme].main; } default: return pillarPalette[format.theme].main; } }; const textHeadlineByline = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; if (format.theme === ArticleSpecial.Labs) return BLACK; return pillarPalette[format.theme].main; }; const textStandfirst = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; return BLACK; }; const textTwitterHandle = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return text.supporting; }; const textCaption = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return specialReport[100]; if (format.theme === ArticleSpecial.Labs) return neutral[20]; switch (format.design) { case ArticleDesign.PhotoEssay: return pillarPalette[format.theme].dark; default: return text.supporting; } }; const textCaptionLink = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return pillarPalette[format.theme].main; }; const textSubMeta = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[100]; if (format.design === ArticleDesign.DeadBlog) return blogsGrayBackgroundPalette(format); return pillarPalette[format.theme].main; }; const textSubMetaLabel = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return text.supporting; }; const textSubMetaLink = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return text.supporting; }; const textSyndicationButton = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[100]; return text.supporting; }; const textArticleLink = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[400]; switch (format.theme) { case ArticlePillar.Opinion: case ArticlePillar.Culture: return pillarPalette[format.theme].dark; default: return pillarPalette[format.theme].main; } }; const textDisclaimerLink = (format: ArticleFormat): string => pillarPalette[format.theme].dark; const textWitnessIcon = (format: ArticleFormat): string => pillarPalette[format.theme].main; const textWitnessTitle = (format: ArticleFormat): string => pillarPalette[format.theme].main; const textWitnessAuthor = (format: ArticleFormat): string => pillarPalette[format.theme].main; const textPullQuote = (format: ArticleFormat): string => { return pillarPalette[format.theme].dark; }; const textStandfirstLink = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[400]; switch (format.theme) { case ArticlePillar.Opinion: case ArticlePillar.Culture: return pillarPalette[format.theme].dark; default: return pillarPalette[format.theme].main; } }; const textBranding = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; return pillarPalette[format.theme].main; }; const textArticleLinkHover = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[100]; switch (format.theme) { case ArticlePillar.Opinion: case ArticlePillar.Culture: return pillarPalette[format.theme].dark; default: return pillarPalette[format.theme].main; } }; const textCardHeadline = (format: ArticleFormat): string => { if (format.display === ArticleDisplay.Immersive) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return WHITE; switch (format.design) { case ArticleDesign.Feature: case ArticleDesign.Interview: return pillarPalette[format.theme].dark; case ArticleDesign.Media: return WHITE; case ArticleDesign.LiveBlog: switch (format.theme) { case ArticleSpecial.Labs: return BLACK; case ArticlePillar.News: case ArticlePillar.Sport: case ArticlePillar.Opinion: case ArticlePillar.Culture: case ArticlePillar.Lifestyle: default: return WHITE; } default: return BLACK; } }; const textCardStandfirst = textCardHeadline; const textCardKicker = (format: ArticleFormat): string => { if ( format.theme === ArticleSpecial.SpecialReport && (format.design === ArticleDesign.Comment || format.design === ArticleDesign.Letter) ) // TODO: Pull this in from source as opinion[550] // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; if (format.theme === ArticleSpecial.SpecialReport) return brandAlt[400]; switch (format.design) { case ArticleDesign.LiveBlog: switch (format.theme) { case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: return WHITE; case ArticlePillar.Culture: return culture[600]; case ArticlePillar.Lifestyle: return lifestyle[500]; case ArticleSpecial.Labs: default: return BLACK; } case ArticleDesign.Media: switch (format.theme) { case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: // TODO: Pull this in from source as opinion[550] // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; case ArticlePillar.Lifestyle: case ArticlePillar.Culture: default: return pillarPalette[format.theme][500]; } default: return pillarPalette[format.theme].main; } }; const textCardFooter = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.Comment: case ArticleDesign.Letter: switch (format.theme) { case ArticleSpecial.SpecialReport: // TODO: Pull this in from souce once we see it here: // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; default: return neutral[60]; } case ArticleDesign.LiveBlog: switch (format.theme) { case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: return WHITE; case ArticlePillar.Culture: return culture[600]; case ArticlePillar.Lifestyle: return lifestyle[500]; case ArticleSpecial.SpecialReport: return brandAlt[400]; case ArticleSpecial.Labs: default: return BLACK; } case ArticleDesign.Media: switch (format.theme) { case ArticleSpecial.SpecialReport: return brandAlt[400]; case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: // TODO: Pull this in from source as opinion[550] // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; case ArticlePillar.Lifestyle: case ArticlePillar.Culture: default: return pillarPalette[format.theme][500]; } default: switch (format.theme) { case ArticleSpecial.SpecialReport: return brandAltBackground.primary; default: return neutral[60]; } } }; const textLinkKicker = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const backgroundArticle = (format: ArticleFormat): string => { if ( format.design === ArticleDesign.LiveBlog || format.design === ArticleDesign.DeadBlog ) return neutral[97]; // Order matters. We want comment special report pieces to have the opinion background if (format.design === ArticleDesign.Letter) return opinion[800]; if (format.design === ArticleDesign.Comment) return opinion[800]; if (format.design === ArticleDesign.Editorial) return opinion[800]; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[800]; // Note, check theme rather than design here if ( format.theme === ArticleSpecial.Labs && format.display !== ArticleDisplay.Immersive ) return neutral[97]; return 'transparent'; }; const backgroundSeriesTitle = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return brandAltBackground.primary; switch (format.display) { case ArticleDisplay.Immersive: return pillarPalette[format.theme].main; case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: default: return 'transparent'; } }; const backgroundSectionTitle = (format: ArticleFormat): string => { switch (format.display) { case ArticleDisplay.Immersive: return pillarPalette[format.theme].main; case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: default: return 'transparent'; } }; const backgroundAvatar = (format: ArticleFormat): string => { switch (format.theme) { case ArticleSpecial.SpecialReport: return specialReport[800]; case ArticlePillar.Opinion: return pillarPalette[ArticlePillar.Opinion].main; default: return pillarPalette[format.theme].bright; } }; const backgroundCard = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; switch (format.design) { case ArticleDesign.Editorial: case ArticleDesign.Letter: case ArticleDesign.Comment: return opinion[800]; case ArticleDesign.Media: return neutral[20]; case ArticleDesign.LiveBlog: switch (format.theme) { case ArticleSpecial.Labs: return labs[400]; case ArticlePillar.News: case ArticlePillar.Sport: case ArticlePillar.Opinion: case ArticlePillar.Lifestyle: case ArticlePillar.Culture: default: return pillarPalette[format.theme][300]; } default: return neutral[97]; } }; const backgroundHeadline = (format: ArticleFormat): string => { switch (format.display) { case ArticleDisplay.Immersive: if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return BLACK; case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: case ArticleDisplay.Standard: if (format.design === ArticleDesign.Interview) return BLACK; return 'transparent'; default: return 'transparent'; } }; const backgroundHeadlineByline = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return brandAltBackground.primary; return 'transparent'; }; const backgroundBullet = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return pillarPalette[format.theme].main; }; const backgroundBulletStandfirst = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.DeadBlog: return neutral[60]; default: return neutral[86]; // default previously defined in Standfirst.tsx } }; const backgroundHeader = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.LiveBlog: return pillarPalette[format.theme][400]; default: return backgroundArticle(format); } }; const backgroundStandfirst = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.LiveBlog: return pillarPalette[format.theme][300]; case ArticleDesign.DeadBlog: return neutral[93]; default: return backgroundArticle(format); } }; const backgroundImageTitle = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const backgroundSpeechBubble = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const fillCommentCount = (format: ArticleFormat): string => { if ( format.design === ArticleDesign.LiveBlog || format.design === ArticleDesign.DeadBlog ) return neutral[46]; if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return pillarPalette[format.theme].main; }; const fillCommentCountUntilDesktop = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; return fillCommentCount(format); }; const fillShareIcon = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[300]; return pillarPalette[format.theme].main; }; const fillShareCountIcon = (): string => { return neutral[46]; }; const fillShareCountIconUntilDesktop = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; return fillShareCountIcon(); }; const fillShareIconGrayBackground = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.LiveBlog: case ArticleDesign.DeadBlog: return blogsGrayBackgroundPalette(format); default: return pillarPalette[format.theme].dark; } }; const fillCaptionCamera = (format: ArticleFormat): string => textCaption(format); const fillBlockquoteIcon = (format: ArticleFormat): string => pillarPalette[format.theme].main; const fillCardIcon = (format: ArticleFormat): string => { // Setting Card clock colour for immersive cards to all be dark grey if (format.display === ArticleDisplay.Immersive) return neutral[60]; switch (format.design) { case ArticleDesign.Comment: case ArticleDesign.Letter: switch (format.theme) { case ArticleSpecial.SpecialReport: // TODO: Pull this in from source once we see it here: // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; default: return neutral[46]; } return lifestyle[500]; case ArticleDesign.LiveBlog: switch (format.theme) { case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: return WHITE; case ArticlePillar.Culture: return culture[600]; case ArticlePillar.Lifestyle: return lifestyle[500]; case ArticleSpecial.SpecialReport: return brandAlt[400]; case ArticleSpecial.Labs: default: return BLACK; } case ArticleDesign.Media: switch (format.theme) { case ArticleSpecial.SpecialReport: return brandAlt[400]; case ArticlePillar.News: return news[600]; case ArticlePillar.Sport: return sport[600]; case ArticlePillar.Opinion: // TODO: Pull this in from source as opinion[550] // https://theguardian.design/2a1e5182b/p/492a30-light-palette return '#ff9941'; case ArticlePillar.Lifestyle: case ArticlePillar.Culture: default: return pillarPalette[format.theme][500]; } default: switch (format.theme) { case ArticleSpecial.SpecialReport: return brandAltBackground.primary; default: return neutral[46]; } } }; const borderSyndicationButton = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return neutral[60]; return border.secondary; }; const borderSubNav = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const borderLiveBlock = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const borderArticleLink = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return neutral[60]; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[400]; return border.secondary; }; const borderStandfirstLink = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[400]; return border.secondary; }; const borderHeadline = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return '#9F2423'; if (format.design === ArticleDesign.DeadBlog) return '#CDCDCD'; return border.secondary; }; const borderStandfirst = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return '#8C2222'; if (format.design === ArticleDesign.DeadBlog) return '#BDBDBD'; return border.secondary; }; const matchTab = (): string => { return border.secondary; }; const activeMatchTab = (): string => { return sport[300]; }; const backgroundMatchNav = (): string => { return '#FFE500'; }; const borderArticleLinkHover = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; if (format.theme === ArticleSpecial.SpecialReport) return specialReport[100]; return pillarPalette[format.theme].main; }; const topBarCard = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.SpecialReport) return brandAltBackground.primary; return pillarPalette[format.theme].main; }; const hoverHeadlineByline = (format: ArticleFormat): string => { if (format.theme === ArticleSpecial.Labs) return BLACK; return pillarPalette[format.theme].dark; }; const textRichLink: (format: ArticleFormat) => string = (format) => { if (format) { return pillarPalette[format.theme].main; } return pillarPalette[ArticlePillar.News][400]; }; const hoverStandfirstLink = (format: ArticleFormat): string => { if (format.design === ArticleDesign.DeadBlog) return pillarPalette[format.theme].main; if (format.design === ArticleDesign.LiveBlog) { return pillarPalette[format.theme].dark; } if (format.theme === ArticleSpecial.SpecialReport) return specialReport[400]; return border.secondary; }; const borderRichLink: (format: ArticleFormat) => string = (format) => { if (format) { return pillarPalette[format.theme].main; } return pillarPalette[ArticlePillar.News][400]; }; const borderNavPillar: (format: ArticleFormat) => string = (format) => pillarPalette[format.theme].bright; const borderArticle: (format: ArticleFormat) => string = (format) => { if ( format.design === ArticleDesign.LiveBlog || format.design === ArticleDesign.DeadBlog ) return '#CDCDCD'; if (format.theme === ArticleSpecial.Labs) return neutral[60]; return border.secondary; }; const borderLines: (format: ArticleFormat) => string = (format) => { if (format.theme === ArticleSpecial.Labs) return border.primary; return border.secondary; }; const backgroundRichLink: (format: ArticleFormat) => string = (format) => { if (format) { return pillarPalette[format.theme].main; } return pillarPalette[ArticlePillar.News][400]; }; const fillRichLink: (format: ArticleFormat) => string = (format) => { if (format) { return pillarPalette[format.theme].main; } return pillarPalette[ArticlePillar.News][400]; }; const fillQuoteIcon: (format: ArticleFormat) => string = (format) => { if (format) { return pillarPalette[format.theme].main; } return pillarPalette[ArticlePillar.News][400]; }; const textPullQuoteAttribution = (format: ArticleFormat): string => fillQuoteIcon(format); const textSignInLink = (format: ArticleFormat): string => { return pillarPalette[format.theme].dark; }; const textCarouselTitle = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const textCalloutHeading = (): string => { return brand[500]; }; const textDropCap = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.Editorial: case ArticleDesign.Letter: case ArticleDesign.Comment: return format.theme === ArticlePillar.Opinion ? pillarPalette[format.theme].main : pillarPalette[format.theme].dark; default: return pillarPalette[format.theme].dark; } }; const textBlockquote = (format: ArticleFormat): string => { switch (format.design) { case ArticleDesign.LiveBlog: case ArticleDesign.DeadBlog: return BLACK; default: return neutral[46]; } }; const textNumberedTitle = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const textNumberedPosition = (): string => { return text.supporting; }; const textOverlayed = (): string => { return WHITE; }; const backgroundHeadlineTag = (format: ArticleFormat): string => pillarPalette[format.theme].dark; const backgroundCarouselDot = (format: ArticleFormat): string => { return pillarPalette[format.theme][400]; }; const backgroundCarouselDotFocus = (format: ArticleFormat): string => { return pillarPalette[format.theme].main; }; const backgroundMostViewedTab = (format: ArticleFormat): string => { return pillarPalette[format.theme].dark; }; const textPagination = (format: ArticleFormat): string => { return blogsGrayBackgroundPalette(format); }; const textShareCount = (): string => { return text.supporting; }; const textShareCountUntilDesktop = (format: ArticleFormat): string => { if (format.design === ArticleDesign.LiveBlog) return WHITE; return text.supporting; }; const borderPagination = (): string => { return neutral[86]; }; const hoverPagination = (format: ArticleFormat): string => { return blogsGrayBackgroundPalette(format); }; export const decidePalette = (format: ArticleFormat): Palette => { return { text: { headline: textHeadline(format), seriesTitle: textSeriesTitle(format), sectionTitle: textSectionTitle(format), byline: textByline(format), twitterHandle: textTwitterHandle(format), caption: textCaption(format), captionLink: textCaptionLink(format), subMeta: textSubMeta(format), subMetaLabel: textSubMetaLabel(format), subMetaLink: textSubMetaLink(format), syndicationButton: textSyndicationButton(format), articleLink: textArticleLink(format), articleLinkHover: textArticleLinkHover(format), cardHeadline: textCardHeadline(format), cardKicker: textCardKicker(format), linkKicker: textLinkKicker(format), cardStandfirst: textCardStandfirst(format), cardFooter: textCardFooter(format), headlineByline: textHeadlineByline(format), standfirst: textStandfirst(format), standfirstLink: textStandfirstLink(format), branding: textBranding(format), disclaimerLink: textDisclaimerLink(format), signInLink: textSignInLink(format), richLink: textRichLink(format), pullQuote: textPullQuote(format), pullQuoteAttribution: textPullQuoteAttribution(format), witnessIcon: textWitnessIcon(format), witnessAuthor: textWitnessAuthor(format), witnessTitle: textWitnessTitle(format), carouselTitle: textCarouselTitle(format), calloutHeading: textCalloutHeading(), dropCap: textDropCap(format), blockquote: textBlockquote(format), numberedTitle: textNumberedTitle(format), numberedPosition: textNumberedPosition(), overlayedCaption: textOverlayed(), pagination: textPagination(format), shareCount: textShareCount(), shareCountUntilDesktop: textShareCountUntilDesktop(format), }, background: { article: backgroundArticle(format), seriesTitle: backgroundSeriesTitle(format), sectionTitle: backgroundSectionTitle(format), avatar: backgroundAvatar(format), card: backgroundCard(format), headline: backgroundHeadline(format), headlineByline: backgroundHeadlineByline(format), bullet: backgroundBullet(format), bulletStandfirst: backgroundBulletStandfirst(format), header: backgroundHeader(format), standfirst: backgroundStandfirst(format), richLink: backgroundRichLink(format), imageTitle: backgroundImageTitle(format), speechBubble: backgroundSpeechBubble(format), carouselDot: backgroundCarouselDot(format), carouselDotFocus: backgroundCarouselDotFocus(format), headlineTag: backgroundHeadlineTag(format), mostViewedTab: backgroundMostViewedTab(format), matchNav: backgroundMatchNav(), }, fill: { commentCount: fillCommentCount(format), commentCountUntilDesktop: fillCommentCountUntilDesktop(format), shareIcon: fillShareIcon(format), shareCountIcon: fillShareCountIcon(), shareCountIconUntilDesktop: fillShareCountIconUntilDesktop(format), shareIconGrayBackground: fillShareIconGrayBackground(format), cameraCaptionIcon: fillCaptionCamera(format), cardIcon: fillCardIcon(format), richLink: fillRichLink(format), quoteIcon: fillQuoteIcon(format), blockquoteIcon: fillBlockquoteIcon(format), }, border: { syndicationButton: borderSyndicationButton(format), subNav: borderSubNav(format), articleLink: borderArticleLink(format), articleLinkHover: borderArticleLinkHover(format), liveBlock: borderLiveBlock(format), standfirstLink: borderStandfirstLink(format), headline: borderHeadline(format), standfirst: borderStandfirst(format), richLink: borderRichLink(format), navPillar: borderNavPillar(format), article: borderArticle(format), lines: borderLines(format), matchTab: matchTab(), activeMatchTab: activeMatchTab(), pagination: borderPagination(), }, topBar: { card: topBarCard(format), }, hover: { headlineByline: hoverHeadlineByline(format), pagination: hoverPagination(format), standfirstLink: hoverStandfirstLink(format), }, }; };
the_stack
import * as findup from "findup-sync"; import * as fs from "fs"; import * as path from "path"; import { Position, Range, TextDocument, Uri } from "vscode"; import * as cachedEntities from "../features/cachedEntities"; import { getComponent, hasComponent } from "../features/cachedEntities"; import { MySet } from "../utils/collections"; import { isCfcFile } from "../utils/contextUtil"; import { DocumentPositionStateContext, DocumentStateContext } from "../utils/documentUtil"; import { resolveCustomMappingPaths, resolveRelativePath, resolveRootPath } from "../utils/fileUtil"; import { Attribute, Attributes, parseAttributes } from "./attribute"; import { DataType } from "./dataType"; import { DocBlockKeyValue, parseDocBlock } from "./docblock"; import { constructGetter, constructSetter, parseProperties, Properties, Property } from "./property"; import { ComponentFunctions, parseScriptFunctions, parseTagFunctions, UserFunction } from "./userFunction"; import { parseVariableAssignments, Variable } from "./variable"; export const COMPONENT_EXT: string = ".cfc"; export const COMPONENT_FILE_GLOB: string = "**/*" + COMPONENT_EXT; export const COMPONENT_TAG_PATTERN: RegExp = /((<cf)(component|interface)\b)([^>]*)/i; export const COMPONENT_SCRIPT_PATTERN: RegExp = /((\/\*\*((?:\*(?!\/)|[^*])*)\*\/\s+)?(component|interface)\b)([^{]*)/i; export const componentExtendsPathPrefix: RegExp = /\b(extends|implements)\s*=\s*(['"])?([^'"#\s]*?)$/i; export const componentDottedPathPrefix: RegExp = /\b(import|new)\s+(?:component\s*:\s*)?(['"])?([^('":;\n]*?)$/i; export const objectNewInstanceInitPrefix: RegExp = /\bnew\s+(?:component\s*:\s*)?(['"])?([^('":]+?)\1\($/i; export interface ReferencePattern { pattern: RegExp; refIndex: number; } export const objectReferencePatterns: ReferencePattern[] = [ // new object { pattern: /\bnew\s+(?:component\s*:\s*)?(['"])?([^('":]+?)\1\(/gi, refIndex: 2 }, // import { pattern: /\bimport\s+(['"])?([^'"]+?)\1(?:;|\n)/gi, refIndex: 2 }, // createObject { pattern: /\bcreateObject\s*\(\s*(['"])component\1\s*,\s*(['"])([^'"]+?)\2/gi, refIndex: 3 }, // cfobject or cfinvoke { pattern: /\bcomponent\s*(?:=|:)\s*(['"])([^'"]+?)\1/gi, refIndex: 2 }, // isInstanceOf { pattern: /\bisInstanceOf\s*\(\s*[\w$.]+\s*,\s*(['"])([^'"]+?)\1/gi, refIndex: 2 }, ]; // TODO: variableReferencePatterns const componentAttributeNames: MySet<string> = new MySet([ "accessors", "alias", "autoindex", "bindingname", "consumes", "displayname", "extends", "hint", "httpmethod", "implements", "indexable", "indexlanguage", "initmethod", "mappedsuperclass", "namespace", "output", "persistent", "porttypename", "produces", "rest", "restPath", "serializable", "serviceaddress", "serviceportname", "style", "wsdlfile", "wsVersion" ]); const booleanAttributes: MySet<string> = new MySet([ "accessors", "autoindex", "indexable", "mappedsuperclass", "output", "persistent", "rest", "serializable" ]); export interface Component { uri: Uri; name: string; isScript: boolean; isInterface: boolean; // should be a separate type, but chose this for the purpose of simplification declarationRange: Range; displayname: string; hint: string; accessors: boolean; initmethod?: string; // TODO: Investigate matching implements since interfaces can extend multiple interfaces extends?: Uri; extendsRange?: Range; implements?: Uri[]; implementsRanges?: Range[]; functions: ComponentFunctions; properties: Properties; variables: Variable[]; imports: string[]; } interface ComponentAttributes { accessors?: boolean; alias?: string; autoindex?: boolean; bindingname?: string; consumes?: string; displayname?: string; extends?: string; hint?: string; httpmethod?: string; implements?: string; indexable?: boolean; indexlanguage?: string; initmethod?: string; mappedsuperclass?: boolean; namespace?: string; output?: boolean; persistent?: boolean; porttypename?: string; produces?: string; rest?: boolean; restPath?: string; serializable?: boolean; serviceaddress?: string; serviceportname?: string; style?: string; wsdlfile?: string; wsVersion?: string; } export interface ComponentsByUri { [uri: string]: Component; // key is Uri.toString() } export interface ComponentsByName { [name: string]: ComponentsByUri; // key is Component name lowercased } /** * Determines whether the given document is a script-based component * @param document The document to check */ export function isScriptComponent(document: TextDocument): boolean { const componentTagMatch: RegExpExecArray = COMPONENT_TAG_PATTERN.exec(document.getText()); if (componentTagMatch) { return false; } return isCfcFile(document); } /** * Parses a component document and returns an object conforming to the Component interface * @param documentStateContext The context information for a TextDocument to be parsed */ export function parseComponent(documentStateContext: DocumentStateContext): Component | undefined { const document: TextDocument = documentStateContext.document; const documentText: string = document.getText(); const componentIsScript: boolean = documentStateContext.docIsScript; let componentMatch: RegExpExecArray; let head: string; let attributePrefix: string; let fullPrefix: string | undefined; let componentDoc: string | undefined; let checkTag: string | undefined; let componentType: string; let componentAttrs: string; if (!componentIsScript) { componentMatch = COMPONENT_TAG_PATTERN.exec(documentText); if (!componentMatch) { return undefined; } head = componentMatch[0]; attributePrefix = componentMatch[1]; checkTag = componentMatch[2]; componentType = componentMatch[3]; componentAttrs = componentMatch[4]; } else { componentMatch = COMPONENT_SCRIPT_PATTERN.exec(documentText); if (!componentMatch) { return undefined; } head = componentMatch[0]; attributePrefix = componentMatch[1]; fullPrefix = componentMatch[2]; componentDoc = componentMatch[3]; componentType = componentMatch[4]; componentAttrs = componentMatch[5]; } let declarationStartOffset: number = componentMatch.index; if (fullPrefix) { declarationStartOffset += fullPrefix.length; } if (checkTag) { declarationStartOffset += checkTag.length; } let componentAttributes: ComponentAttributes = {}; let component: Component = { uri: document.uri, name: path.basename(document.fileName, COMPONENT_EXT), isScript: componentIsScript, isInterface: componentType === "interface", declarationRange: new Range(document.positionAt(declarationStartOffset), document.positionAt(declarationStartOffset + componentType.length)), displayname: "", hint: "", extends: null, implements: null, accessors: false, functions: new ComponentFunctions(), properties: parseProperties(documentStateContext), variables: [], imports: [] }; if (componentDoc) { const parsedDocBlock: DocBlockKeyValue[] = parseDocBlock( document, new Range( document.positionAt(componentMatch.index + 3), document.positionAt(componentMatch.index + 3 + componentDoc.length) ) ); const docBlockAttributes: ComponentAttributes = processDocBlock(parsedDocBlock); Object.assign(componentAttributes, docBlockAttributes); parsedDocBlock.filter((docAttribute: DocBlockKeyValue) => { return docAttribute.key === "extends" && docAttribute.value; }).forEach((docAttribute: DocBlockKeyValue) => { component.extendsRange = new Range( docAttribute.valueRange.start, docAttribute.valueRange.end ); }); const implDocAttr = parsedDocBlock.find((docAttribute: DocBlockKeyValue) => { return docAttribute.key === "implements" && !!docAttribute.value; }); if (implDocAttr) { component.implementsRanges = []; const implInitialOffset = document.offsetAt(implDocAttr.valueRange.start); let implOffset: number = 0; implDocAttr.value.split(",").forEach((element: string) => { const whitespaceMatch: RegExpExecArray = /\s+/.exec(element); const whitespaceLen = whitespaceMatch ? whitespaceMatch[0].length : 0; const interfacePathWordRange: Range = document.getWordRangeAtPosition(document.positionAt(implInitialOffset + implOffset + whitespaceLen), /[$\w.]+/); component.implementsRanges.push(interfacePathWordRange); implOffset += element.length + 1; }); } } if (componentAttrs) { const componentAttributePrefixOffset: number = componentMatch.index + attributePrefix.length; const componentAttributeRange = new Range( document.positionAt(componentAttributePrefixOffset), document.positionAt(componentAttributePrefixOffset + componentAttrs.length) ); const parsedAttributes: Attributes = parseAttributes(document, componentAttributeRange, componentAttributeNames); const tagAttributes: ComponentAttributes = processAttributes(parsedAttributes); Object.assign(componentAttributes, tagAttributes); if (parsedAttributes.has("extends")) { const extendsAttr: Attribute = parsedAttributes.get("extends"); if (extendsAttr.value) { component.extendsRange = new Range( extendsAttr.valueRange.start, extendsAttr.valueRange.end ); } } if (parsedAttributes.has("implements")) { const implementsAttr: Attribute = parsedAttributes.get("implements"); if (implementsAttr.value) { component.implementsRanges = []; const implInitialOffset = document.offsetAt(implementsAttr.valueRange.start); let implOffset: number = 0; implementsAttr.value.split(",").forEach((element: string) => { const whitespaceMatch: RegExpExecArray = /\s+/.exec(element); const whitespaceLen = whitespaceMatch ? whitespaceMatch[0].length : 0; const interfacePathWordRange: Range = document.getWordRangeAtPosition(document.positionAt(implInitialOffset + implOffset + whitespaceLen), /[$\w.]+/); component.implementsRanges.push(interfacePathWordRange); implOffset += element.length + 1; }); } } } Object.getOwnPropertyNames(component).forEach((propName: string) => { // TODO: Is this just supposed to be checking for existence or also value? Because it is ignoring falsy property values too if (componentAttributes[propName]) { if (propName === "extends") { component.extends = componentPathToUri(componentAttributes.extends, document.uri); } else if (propName === "implements") { componentAttributes.implements.split(",").forEach((element: string) => { const implementsUri: Uri = componentPathToUri(element.trim(), document.uri); if (implementsUri) { if (!component.implements) { component.implements = []; } component.implements.push(implementsUri); } }); } else if (propName === "persistent" && componentAttributes.persistent) { component.accessors = true; } else { component[propName] = componentAttributes[propName]; } } }); documentStateContext.component = component; let componentFunctions = new ComponentFunctions(); let userFunctions: UserFunction[] = parseScriptFunctions(documentStateContext); userFunctions = userFunctions.concat(parseTagFunctions(documentStateContext)); let earliestFunctionRangeStart: Position = document.positionAt(documentText.length); userFunctions.forEach((compFun: UserFunction) => { if (compFun.location.range.start.isBefore(earliestFunctionRangeStart)) { earliestFunctionRangeStart = compFun.location.range.start; } componentFunctions.set(compFun.name.toLowerCase(), compFun); }); // Implicit functions if (component.accessors) { component.properties.forEach((prop: Property) => { // getters if (typeof prop.getter === "undefined" || prop.getter) { const getterKey = "get" + prop.name.toLowerCase(); if (!componentFunctions.has(getterKey)) { componentFunctions.set(getterKey, constructGetter(prop, component.uri)); } } // setters if (typeof prop.setter === "undefined" || prop.setter) { const setterKey = "set" + prop.name.toLowerCase(); if (!componentFunctions.has(setterKey)) { componentFunctions.set(setterKey, constructSetter(prop, component.uri)); } } }); } component.functions = componentFunctions; const componentDefinitionRange = new Range(document.positionAt(componentMatch.index + head.length), earliestFunctionRangeStart); component.variables = parseVariableAssignments(documentStateContext, componentIsScript, componentDefinitionRange); // TODO: Get imports return component; } /** * Parses a component document and returns an object conforming to the Component interface * @param documentPositionStateContext The context information for the TextDocument and position to be check */ export function isInComponentHead(documentPositionStateContext: DocumentPositionStateContext): boolean { const document: TextDocument = documentPositionStateContext.document; const documentText: string = documentPositionStateContext.sanitizedDocumentText; const componentPattern: RegExp = documentPositionStateContext.docIsScript ? COMPONENT_SCRIPT_PATTERN : COMPONENT_TAG_PATTERN; const componentMatch: RegExpExecArray = componentPattern.exec(documentText); if (!componentMatch) { return false; } const head: string = componentMatch[0]; if (!head) { return false; } const componentHeadRange = new Range(new Position(0, 0), document.positionAt(componentMatch.index + head.length)); return componentHeadRange.contains(documentPositionStateContext.position); } /** * Parses a documentation block for a component and returns an object conforming to the ComponentAttributes interface * @param docBlock The documentation block to be processed */ function processDocBlock(docBlock: DocBlockKeyValue[]): ComponentAttributes { let docBlockObj: ComponentAttributes = {}; docBlock.forEach((docElem: DocBlockKeyValue) => { const activeKey = docElem.key; if (booleanAttributes.has(activeKey)) { docBlockObj[activeKey] = DataType.isTruthy(docElem.value); } else { docBlockObj[activeKey] = docElem.value; } }); return docBlockObj; } /** * Processes a set of attributes for a component and returns an object conforming to the ComponentAttributes interface * @param attributes A set of attributes */ function processAttributes(attributes: Attributes): ComponentAttributes { let attributeObj: ComponentAttributes = {}; attributes.forEach((attr: Attribute, attrKey: string) => { if (booleanAttributes.has(attrKey)) { attributeObj[attrKey] = DataType.isTruthy(attr.value); } else { attributeObj[attrKey] = attr.value; } }); return attributeObj; } /** * Resolves a component in dot-path notation to a URI * @param dotPath A string for a component in dot-path notation * @param baseUri The URI from which the component path will be resolved */ export function componentPathToUri(dotPath: string, baseUri: Uri): Uri | undefined { if (!dotPath) { return undefined; } const cachedResult: Uri = cachedEntities.componentPathToUri(dotPath, baseUri); if (cachedResult) { return cachedResult; } const normalizedPath: string = dotPath.replace(/\./g, path.sep) + COMPONENT_EXT; /* Note If ColdFusion finds a directory that matches the first path element, but does not find a CFC under that directory, ColdFusion returns a not found error and does NOT search for another directory. This implementation does not do this. */ // relative to local directory const localPath: string = resolveRelativePath(baseUri, normalizedPath); if (fs.existsSync(localPath)) { return Uri.file(localPath); } // relative to web root const rootPath: string = resolveRootPath(baseUri, normalizedPath); if (rootPath && fs.existsSync(rootPath)) { return Uri.file(rootPath); } // custom mappings const customMappingPaths: string[] = resolveCustomMappingPaths(baseUri, normalizedPath); for (const mappedPath of customMappingPaths) { if (fs.existsSync(mappedPath)) { return Uri.file(mappedPath); } } return undefined; } /** * Returns just the name part for a component dot path * @param path Dot path to a component */ export function getComponentNameFromDotPath(path: string): string { return path.split(".").pop(); } /** * Finds the applicable Application file for the given file URI * @param baseUri The URI from which the Application file will be searched */ export function getApplicationUri(baseUri: Uri): Uri | undefined { if (baseUri.scheme !== "file") { return undefined; } let componentUri: Uri; const fileNamesGlob = "Application.@(cfc|cfm)"; const currentWorkingDir: string = path.dirname(baseUri.fsPath); const applicationFile: string = findup(fileNamesGlob, { cwd: currentWorkingDir }); if (applicationFile) { componentUri = Uri.file(applicationFile); } return componentUri; } /** * Finds the applicable Server file for the given file URI * @param baseUri The URI from which the Server file will be searched */ export function getServerUri(baseUri: Uri): Uri | undefined { let componentUri: Uri; const fileName = "Server.cfc"; const rootPath: string = resolveRootPath(baseUri, fileName); if (rootPath) { const rootUri: Uri = Uri.file(rootPath); if (hasComponent(rootUri)) { componentUri = rootUri; } } // TODO: custom mapping return componentUri; } /** * Checks whether `checkComponent` is a subcomponent or equal to `baseComponent` * @param checkComponent The candidate subcomponent * @param baseComponent The candidate base component */ export function isSubcomponentOrEqual(checkComponent: Component, baseComponent: Component): boolean { while (checkComponent) { if (checkComponent.uri.toString() === baseComponent.uri.toString()) { return true; } if (checkComponent.extends) { checkComponent = getComponent(checkComponent.extends); } else { checkComponent = undefined; } } return false; } /** * Checks whether `checkComponent` is a subcomponent of `baseComponent` * @param checkComponent The candidate subcomponent * @param baseComponent The candidate base component */ export function isSubcomponent(checkComponent: Component, baseComponent: Component): boolean { if (checkComponent.extends) { checkComponent = getComponent(checkComponent.extends); } else { return false; } while (checkComponent) { if (checkComponent.uri.toString() === baseComponent.uri.toString()) { return true; } if (checkComponent.extends) { checkComponent = getComponent(checkComponent.extends); } else { checkComponent = undefined; } } return false; }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [chime](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonchime.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Chime extends PolicyStatement { public servicePrefix = 'chime'; /** * Statement provider for service [chime](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonchime.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 accept the delegate invitation to share management of an Amazon Chime account with another AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toAcceptDelegate() { return this.to('AcceptDelegate'); } /** * Grants permission to activate users in an Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/manage-access.html */ public toActivateUsers() { return this.to('ActivateUsers'); } /** * Grants permission to add a domain to your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/claim-domain.html */ public toAddDomain() { return this.to('AddDomain'); } /** * Grants permission to add new or update existing Active Directory or Okta user groups associated with your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html */ public toAddOrUpdateGroups() { return this.to('AddOrUpdateGroups'); } /** * Grants permission to associate a phone number with an Amazon Chime user * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AssociatePhoneNumberWithUser.html */ public toAssociatePhoneNumberWithUser() { return this.to('AssociatePhoneNumberWithUser'); } /** * Grants permission to associate multiple phone numbers with an Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AssociatePhoneNumbersWithVoiceConnector.html */ public toAssociatePhoneNumbersWithVoiceConnector() { return this.to('AssociatePhoneNumbersWithVoiceConnector'); } /** * Grants permission to associate multiple phone numbers with an Amazon Chime Voice Connector Group * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AssociatePhoneNumbersWithVoiceConnectorGroup.html */ public toAssociatePhoneNumbersWithVoiceConnectorGroup() { return this.to('AssociatePhoneNumbersWithVoiceConnectorGroup'); } /** * Grants permission to associate the specified sign-in delegate groups with the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AssociateSigninDelegateGroupsWithAccount.html */ public toAssociateSigninDelegateGroupsWithAccount() { return this.to('AssociateSigninDelegateGroupsWithAccount'); } /** * Grants permission to authorize an Active Directory for your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toAuthorizeDirectory() { return this.to('AuthorizeDirectory'); } /** * Grants permission to create new attendees for an active Amazon Chime SDK meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchCreateAttendee.html */ public toBatchCreateAttendee() { return this.to('BatchCreateAttendee'); } /** * Grants permission to add multiple users to a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchCreateChannelMembership.html */ public toBatchCreateChannelMembership() { return this.to('BatchCreateChannelMembership'); } /** * Grants permission to batch add room members * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchCreateRoomMembership.html */ public toBatchCreateRoomMembership() { return this.to('BatchCreateRoomMembership'); } /** * Grants permission to move up to 50 phone numbers to the deletion queue * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchDeletePhoneNumber.html */ public toBatchDeletePhoneNumber() { return this.to('BatchDeletePhoneNumber'); } /** * Grants permission to suspend up to 50 users from a Team or EnterpriseLWA Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchSuspendUser.html */ public toBatchSuspendUser() { return this.to('BatchSuspendUser'); } /** * Grants permission to remove the suspension from up to 50 previously suspended users for the specified Amazon Chime EnterpriseLWA account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchUnsuspendUser.html */ public toBatchUnsuspendUser() { return this.to('BatchUnsuspendUser'); } /** * Grants permission to update phone number details within the UpdatePhoneNumberRequestItem object for up to 50 phone numbers * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchUpdatePhoneNumber.html */ public toBatchUpdatePhoneNumber() { return this.to('BatchUpdatePhoneNumber'); } /** * Grants permission to update user details within the UpdateUserRequestItem object for up to 20 users for the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_BatchUpdateUser.html */ public toBatchUpdateUser() { return this.to('BatchUpdateUser'); } /** * Grants permission to establish a web socket connection for app instance user to the messaging session endpoint * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_Connect.html */ public toConnect() { return this.to('Connect'); } /** * Grants permission to connect an Active Directory to your Amazon Chime Enterprise account * * Access Level: Write * * Dependent actions: * - ds:ConnectDirectory * * https://docs.aws.amazon.com/chime/latest/ag/active_directory.html */ public toConnectDirectory() { return this.to('ConnectDirectory'); } /** * Grants permission to create an Amazon Chime account under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateAccount.html */ public toCreateAccount() { return this.to('CreateAccount'); } /** * Grants permission to create a new SCIM access key for your Amazon Chime account and Okta configuration * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toCreateApiKey() { return this.to('CreateApiKey'); } /** * Grants permission to create an app instance under the AWS account * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateAppInstance.html */ public toCreateAppInstance() { return this.to('CreateAppInstance'); } /** * Grants permission to promote an AppInstanceUser to an AppInstanceAdmin * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateAppInstanceAdmin.html */ public toCreateAppInstanceAdmin() { return this.to('CreateAppInstanceAdmin'); } /** * Grants permission to create a user under an Amazon Chime AppInstance * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateAppInstanceUser.html */ public toCreateAppInstanceUser() { return this.to('CreateAppInstanceUser'); } /** * Grants permission to create a new attendee for an active Amazon Chime SDK meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateAttendee.html */ public toCreateAttendee() { return this.to('CreateAttendee'); } /** * Grants permission to create a bot for an Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateBot.html */ public toCreateBot() { return this.to('CreateBot'); } /** * Grants permission to add a bot to a chat room in your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateBotMembership.html */ public toCreateBotMembership() { return this.to('CreateBotMembership'); } /** * Grants permission to create a new Call Detail Record S3 bucket * * Access Level: Write * * Dependent actions: * - s3:CreateBucket * - s3:ListAllMyBuckets * * https://docs.aws.amazon.com/chime/latest/ag/manage-access.html */ public toCreateCDRBucket() { return this.to('CreateCDRBucket'); } /** * Grants permission to create a channel for an app instance under the AWS account * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateChannel.html */ public toCreateChannel() { return this.to('CreateChannel'); } /** * Grants permission to ban a user from a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateChannelBan.html */ public toCreateChannelBan() { return this.to('CreateChannelBan'); } /** * Grants permission to add a user to a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateChannelMembership.html */ public toCreateChannelMembership() { return this.to('CreateChannelMembership'); } /** * Grants permission to create a channel moderator * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateChannelModerator.html */ public toCreateChannelModerator() { return this.to('CreateChannelModerator'); } /** * Grants permission to create a media capture pipeline * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateMediaCapturePipeline.html */ public toCreateMediaCapturePipeline() { return this.to('CreateMediaCapturePipeline'); } /** * Grants permission to create a new Amazon Chime SDK meeting in the specified media Region, with no initial attendees * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateMeeting.html */ public toCreateMeeting() { return this.to('CreateMeeting'); } /** * Grants permission to call a phone number to join the specified Amazon Chime SDK meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateMeetingDialOut.html */ public toCreateMeetingDialOut() { return this.to('CreateMeetingDialOut'); } /** * Grants permission to create a new Amazon Chime SDK meeting in the specified media Region, with a set of attendees * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateMeetingWithAttendees.html */ public toCreateMeetingWithAttendees() { return this.to('CreateMeetingWithAttendees'); } /** * Grants permission to create a phone number order with the Carriers * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreatePhoneNumberOrder.html */ public toCreatePhoneNumberOrder() { return this.to('CreatePhoneNumberOrder'); } /** * Grants permission to create a proxy session for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateProxySession.html */ public toCreateProxySession() { return this.to('CreateProxySession'); } /** * Grants permission to create a room * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateRoom.html */ public toCreateRoom() { return this.to('CreateRoom'); } /** * Grants permission to add a room member * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateRoomMembership.html */ public toCreateRoomMembership() { return this.to('CreateRoomMembership'); } /** * Grants permission to create an Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateSipMediaApplication.html */ public toCreateSipMediaApplication() { return this.to('CreateSipMediaApplication'); } /** * Grants permission to create outbound call for Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateSipMediaApplicationCall.html */ public toCreateSipMediaApplicationCall() { return this.to('CreateSipMediaApplicationCall'); } /** * Grants permission to create an Amazon Chime SIP rule under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateSipRule.html */ public toCreateSipRule() { return this.to('CreateSipRule'); } /** * Grants permission to create a user under the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateUser.html */ public toCreateUser() { return this.to('CreateUser'); } /** * Grants permission to create a Amazon Chime Voice Connector under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateVoiceConnector.html */ public toCreateVoiceConnector() { return this.to('CreateVoiceConnector'); } /** * Grants permission to create a Amazon Chime Voice Connector Group under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_CreateVoiceConnectorGroup.html */ public toCreateVoiceConnectorGroup() { return this.to('CreateVoiceConnectorGroup'); } /** * Grants permission to delete the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAccount.html */ public toDeleteAccount() { return this.to('DeleteAccount'); } /** * Grants permission to delete the OpenIdConfig attributes from your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toDeleteAccountOpenIdConfig() { return this.to('DeleteAccountOpenIdConfig'); } /** * Grants permission to delete the specified SCIM access key associated with your Amazon Chime account and Okta configuration * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toDeleteApiKey() { return this.to('DeleteApiKey'); } /** * Grants permission to delete an AppInstance * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAppInstance.html */ public toDeleteAppInstance() { return this.to('DeleteAppInstance'); } /** * Grants permission to demote an AppInstanceAdmin to an AppInstanceUser * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAppInstanceAdmin.html */ public toDeleteAppInstanceAdmin() { return this.to('DeleteAppInstanceAdmin'); } /** * Grants permission to disable data streaming for the app instance * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAppInstanceStreamingConfigurations.html */ public toDeleteAppInstanceStreamingConfigurations() { return this.to('DeleteAppInstanceStreamingConfigurations'); } /** * Grants permission to delete an AppInstanceUser * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAppInstanceUser.html */ public toDeleteAppInstanceUser() { return this.to('DeleteAppInstanceUser'); } /** * Grants permission to delete the specified attendee from an Amazon Chime SDK meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteAttendee.html */ public toDeleteAttendee() { return this.to('DeleteAttendee'); } /** * Grants permission to delete a Call Detail Record S3 bucket from your Amazon Chime account * * Access Level: Write * * Dependent actions: * - s3:DeleteBucket * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toDeleteCDRBucket() { return this.to('DeleteCDRBucket'); } /** * Grants permission to delete a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteChannel.html */ public toDeleteChannel() { return this.to('DeleteChannel'); } /** * Grants permission to remove a user from a channel's ban list * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteChannelBan.html */ public toDeleteChannelBan() { return this.to('DeleteChannelBan'); } /** * Grants permission to remove a member from a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteChannelMembership.html */ public toDeleteChannelMembership() { return this.to('DeleteChannelMembership'); } /** * Grants permission to delete a channel message * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteChannelMessage.html */ public toDeleteChannelMessage() { return this.to('DeleteChannelMessage'); } /** * Grants permission to delete a channel moderator * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteChannelModerator.html */ public toDeleteChannelModerator() { return this.to('DeleteChannelModerator'); } /** * Grants permission to delete delegated AWS account management from your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toDeleteDelegate() { return this.to('DeleteDelegate'); } /** * Grants permission to delete a domain from your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/claim-domain.html */ public toDeleteDomain() { return this.to('DeleteDomain'); } /** * Grants permission to delete an events configuration for a bot to receive outgoing events * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteEventsConfiguration.html */ public toDeleteEventsConfiguration() { return this.to('DeleteEventsConfiguration'); } /** * Grants permission to delete Active Directory or Okta user groups from your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toDeleteGroups() { return this.to('DeleteGroups'); } /** * Grants permission to delete a media capture pipeline * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteMediaCapturePipeline.html */ public toDeleteMediaCapturePipeline() { return this.to('DeleteMediaCapturePipeline'); } /** * Grants permission to delete the specified Amazon Chime SDK meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteMeeting.html */ public toDeleteMeeting() { return this.to('DeleteMeeting'); } /** * Grants permission to move a phone number to the deletion queue * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeletePhoneNumber.html */ public toDeletePhoneNumber() { return this.to('DeletePhoneNumber'); } /** * Grants permission to delete a proxy session for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteProxySession.html */ public toDeleteProxySession() { return this.to('DeleteProxySession'); } /** * Grants permission to delete a room * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteRoom.html */ public toDeleteRoom() { return this.to('DeleteRoom'); } /** * Grants permission to remove a room member * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteRoomMembership.html */ public toDeleteRoomMembership() { return this.to('DeleteRoomMembership'); } /** * Grants permission to delete Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteSipMediaApplication.html */ public toDeleteSipMediaApplication() { return this.to('DeleteSipMediaApplication'); } /** * Grants permission to delete Amazon Chime SIP rule under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteSipRule.html */ public toDeleteSipRule() { return this.to('DeleteSipRule'); } /** * Grants permission to delete the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnector.html */ public toDeleteVoiceConnector() { return this.to('DeleteVoiceConnector'); } /** * Grants permission to delete emergency calling configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorEmergencyCallingConfiguration.html */ public toDeleteVoiceConnectorEmergencyCallingConfiguration() { return this.to('DeleteVoiceConnectorEmergencyCallingConfiguration'); } /** * Grants permission to delete the specified Amazon Chime Voice Connector Group * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorGroup.html */ public toDeleteVoiceConnectorGroup() { return this.to('DeleteVoiceConnectorGroup'); } /** * Grants permission to delete the origination settings for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorOrigination.html */ public toDeleteVoiceConnectorOrigination() { return this.to('DeleteVoiceConnectorOrigination'); } /** * Grants permission to delete proxy configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorProxy.html */ public toDeleteVoiceConnectorProxy() { return this.to('DeleteVoiceConnectorProxy'); } /** * Grants permission to delete streaming configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorStreamingConfiguration.html */ public toDeleteVoiceConnectorStreamingConfiguration() { return this.to('DeleteVoiceConnectorStreamingConfiguration'); } /** * Grants permission to delete the termination settings for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorTermination.html */ public toDeleteVoiceConnectorTermination() { return this.to('DeleteVoiceConnectorTermination'); } /** * Grants permission to delete SIP termination credentials for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DeleteVoiceConnectorTerminationCredentials.html */ public toDeleteVoiceConnectorTerminationCredentials() { return this.to('DeleteVoiceConnectorTerminationCredentials'); } /** * Grants permission to get the full details of an AppInstance * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeAppInstance.html */ public toDescribeAppInstance() { return this.to('DescribeAppInstance'); } /** * Grants permission to get the full details of an AppInstanceAdmin * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeAppInstanceAdmin.html */ public toDescribeAppInstanceAdmin() { return this.to('DescribeAppInstanceAdmin'); } /** * Grants permission to get the full details of an AppInstanceUser * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeAppInstanceUser.html */ public toDescribeAppInstanceUser() { return this.to('DescribeAppInstanceUser'); } /** * Grants permission to get the full details of a channel * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannel.html */ public toDescribeChannel() { return this.to('DescribeChannel'); } /** * Grants permission to get the full details of a channel ban * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannelBan.html */ public toDescribeChannelBan() { return this.to('DescribeChannelBan'); } /** * Grants permission to get the full details of a channel membership * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannelMembership.html */ public toDescribeChannelMembership() { return this.to('DescribeChannelMembership'); } /** * Grants permission to get the details of a channel based on the membership of the specified AppInstanceUser * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannelMembershipForAppInstanceUser.html */ public toDescribeChannelMembershipForAppInstanceUser() { return this.to('DescribeChannelMembershipForAppInstanceUser'); } /** * Grants permission to get the full details of a channel moderated by the specified AppInstanceUser * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannelModeratedByAppInstanceUser.html */ public toDescribeChannelModeratedByAppInstanceUser() { return this.to('DescribeChannelModeratedByAppInstanceUser'); } /** * Grants permission to get the full details of a single ChannelModerator * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DescribeChannelModerator.html */ public toDescribeChannelModerator() { return this.to('DescribeChannelModerator'); } /** * Grants permission to disassociate the primary provisioned number from the specified Amazon Chime user * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DisassociatePhoneNumberFromUser.html */ public toDisassociatePhoneNumberFromUser() { return this.to('DisassociatePhoneNumberFromUser'); } /** * Grants permission to disassociate multiple phone numbers from the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DisassociatePhoneNumbersFromVoiceConnector.html */ public toDisassociatePhoneNumbersFromVoiceConnector() { return this.to('DisassociatePhoneNumbersFromVoiceConnector'); } /** * Grants permission to disassociate multiple phone numbers from the specified Amazon Chime Voice Connector Group * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DisassociatePhoneNumbersFromVoiceConnectorGroup.html */ public toDisassociatePhoneNumbersFromVoiceConnectorGroup() { return this.to('DisassociatePhoneNumbersFromVoiceConnectorGroup'); } /** * Grants permission to disassociate the specified sign-in delegate groups from the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_DisassociateSigninDelegateGroupsFromAccount.html */ public toDisassociateSigninDelegateGroupsFromAccount() { return this.to('DisassociateSigninDelegateGroupsFromAccount'); } /** * Grants permission to disconnect the Active Directory from your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toDisconnectDirectory() { return this.to('DisconnectDirectory'); } /** * Grants permission to get details for the specified Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetAccount.html */ public toGetAccount() { return this.to('GetAccount'); } /** * Grants permission to get details for the account resource associated with your Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toGetAccountResource() { return this.to('GetAccountResource'); } /** * Grants permission to get account settings for the specified Amazon Chime account ID * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetAccountSettings.html */ public toGetAccountSettings() { return this.to('GetAccountSettings'); } /** * Grants permission to get the account details and OpenIdConfig attributes for your Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toGetAccountWithOpenIdConfig() { return this.to('GetAccountWithOpenIdConfig'); } /** * Grants permission to get retention settings for an app instance * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetAppInstanceRetentionSettings.html */ public toGetAppInstanceRetentionSettings() { return this.to('GetAppInstanceRetentionSettings'); } /** * Grants permission to get the streaming configurations for an app instance * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetAppInstanceStreamingConfigurations.html */ public toGetAppInstanceStreamingConfigurations() { return this.to('GetAppInstanceStreamingConfigurations'); } /** * Grants permission to get attendee details for a specified meeting ID and attendee ID * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetAttendee.html */ public toGetAttendee() { return this.to('GetAttendee'); } /** * Grants permission to retrieve details for the specified bot * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetBot.html */ public toGetBot() { return this.to('GetBot'); } /** * Grants permission to get details of a Call Detail Record S3 bucket associated with your Amazon Chime account * * Access Level: Read * * Dependent actions: * - s3:GetBucketAcl * - s3:GetBucketLocation * - s3:GetBucketLogging * - s3:GetBucketVersioning * - s3:GetBucketWebsite * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toGetCDRBucket() { return this.to('GetCDRBucket'); } /** * Grants permission to get the full details of a channel message * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetChannelMessage.html */ public toGetChannelMessage() { return this.to('GetChannelMessage'); } /** * Grants permission to get domain details for a domain associated with your Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/claim-domain.html */ public toGetDomain() { return this.to('GetDomain'); } /** * Grants permission to retrieve details for an events configuration for a bot to receive outgoing events * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetEventsConfiguration.html */ public toGetEventsConfiguration() { return this.to('GetEventsConfiguration'); } /** * Grants permission to get global settings related to Amazon Chime for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetGlobalSettings.html */ public toGetGlobalSettings() { return this.to('GetGlobalSettings'); } /** * Grants permission to get an existing media capture pipeline * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetMediaCapturePipeline.html */ public toGetMediaCapturePipeline() { return this.to('GetMediaCapturePipeline'); } /** * Grants permission to get the meeting record for a specified meeting ID * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetMeeting.html */ public toGetMeeting() { return this.to('GetMeeting'); } /** * Grants permission to get attendee, connection, and other details for a meeting * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toGetMeetingDetail() { return this.to('GetMeetingDetail'); } /** * Grants permission to get the endpoint for the messaging session * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetMessagingSessionEndpoint.html */ public toGetMessagingSessionEndpoint() { return this.to('GetMessagingSessionEndpoint'); } /** * Grants permission to get details for the specified phone number * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetPhoneNumber.html */ public toGetPhoneNumber() { return this.to('GetPhoneNumber'); } /** * Grants permission to get details for the specified phone number order * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetPhoneNumberOrder.html */ public toGetPhoneNumberOrder() { return this.to('GetPhoneNumberOrder'); } /** * Grants permission to get phone number settings related to Amazon Chime for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetPhoneNumberSettings.html */ public toGetPhoneNumberSettings() { return this.to('GetPhoneNumberSettings'); } /** * Grants permission to get details of the specified proxy session for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetProxySession.html */ public toGetProxySession() { return this.to('GetProxySession'); } /** * Grants permission to retrieve the retention settings for the specified Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetRetentionSettings.html */ public toGetRetentionSettings() { return this.to('GetRetentionSettings'); } /** * Grants permission to retrieve a room * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetRoom.html */ public toGetRoom() { return this.to('GetRoom'); } /** * Grants permission to get details of Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetSipMediaApplication.html */ public toGetSipMediaApplication() { return this.to('GetSipMediaApplication'); } /** * Grants permission to get logging configuration settings for Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetSipMediaApplicationLoggingConfiguration.html */ public toGetSipMediaApplicationLoggingConfiguration() { return this.to('GetSipMediaApplicationLoggingConfiguration'); } /** * Grants permission to get details of Amazon Chime SIP rule under the administrator's AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetSipRule.html */ public toGetSipRule() { return this.to('GetSipRule'); } /** * Grants permission to get telephony limits for the AWS account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html */ public toGetTelephonyLimits() { return this.to('GetTelephonyLimits'); } /** * Grants permission to get details for the specified user ID * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetUser.html */ public toGetUser() { return this.to('GetUser'); } /** * Grants permission to get a summary of user activity on the user details page * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/user-details.html */ public toGetUserActivityReportData() { return this.to('GetUserActivityReportData'); } /** * Grants permission to get user details for an Amazon Chime user based on the email address in an Amazon Chime Enterprise or Team account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/user-details.html */ public toGetUserByEmail() { return this.to('GetUserByEmail'); } /** * Grants permission to get user settings related to the specified Amazon Chime user * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetUserSettings.html */ public toGetUserSettings() { return this.to('GetUserSettings'); } /** * Grants permission to get details for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnector.html */ public toGetVoiceConnector() { return this.to('GetVoiceConnector'); } /** * Grants permission to get details of the emergency calling configuration for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorEmergencyCallingConfiguration.html */ public toGetVoiceConnectorEmergencyCallingConfiguration() { return this.to('GetVoiceConnectorEmergencyCallingConfiguration'); } /** * Grants permission to get details for the specified Amazon Chime Voice Connector Group * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorGroup.html */ public toGetVoiceConnectorGroup() { return this.to('GetVoiceConnectorGroup'); } /** * Grants permission to get details of the logging configuration for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorLoggingConfiguration.html */ public toGetVoiceConnectorLoggingConfiguration() { return this.to('GetVoiceConnectorLoggingConfiguration'); } /** * Grants permission to get details of the origination settings for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorOrigination.html */ public toGetVoiceConnectorOrigination() { return this.to('GetVoiceConnectorOrigination'); } /** * Grants permission to get details of the proxy configuration for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorProxy.html */ public toGetVoiceConnectorProxy() { return this.to('GetVoiceConnectorProxy'); } /** * Grants permission to get details of the streaming configuration for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorStreamingConfiguration.html */ public toGetVoiceConnectorStreamingConfiguration() { return this.to('GetVoiceConnectorStreamingConfiguration'); } /** * Grants permission to get details of the termination settings for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorTermination.html */ public toGetVoiceConnectorTermination() { return this.to('GetVoiceConnectorTermination'); } /** * Grants permission to get details of the termination health for the specified Amazon Chime Voice Connector * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_GetVoiceConnectorTerminationHealth.html */ public toGetVoiceConnectorTerminationHealth() { return this.to('GetVoiceConnectorTerminationHealth'); } /** * Grants permission to send an invitation to accept a request for AWS account delegation for an Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toInviteDelegate() { return this.to('InviteDelegate'); } /** * Grants permission to invite as many as 50 users to the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_InviteUsers.html */ public toInviteUsers() { return this.to('InviteUsers'); } /** * Grants permission to invite users from a third party provider to your Amazon Chime account * * Access Level: Write */ public toInviteUsersFromProvider() { return this.to('InviteUsersFromProvider'); } /** * Grants permission to list Amazon Chime account usage reporting data * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/view-reports.html */ public toListAccountUsageReportData() { return this.to('ListAccountUsageReportData'); } /** * Grants permission to list the Amazon Chime accounts under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAccounts.html */ public toListAccounts() { return this.to('ListAccounts'); } /** * Grants permission to list the SCIM access keys defined for your Amazon Chime account and Okta configuration * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toListApiKeys() { return this.to('ListApiKeys'); } /** * Grants permission to list administrators in the app instance * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAppInstanceAdmins.html */ public toListAppInstanceAdmins() { return this.to('ListAppInstanceAdmins'); } /** * Grants permission to list all AppInstanceUsers created under a single app instance * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAppInstanceUsers.html */ public toListAppInstanceUsers() { return this.to('ListAppInstanceUsers'); } /** * Grants permission to list all Amazon Chime app instances created under a single AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAppInstances.html */ public toListAppInstances() { return this.to('ListAppInstances'); } /** * Grants permission to list the tags applied to an Amazon Chime SDK attendee resource * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAttendeeTags.html */ public toListAttendeeTags() { return this.to('ListAttendeeTags'); } /** * Grants permission to list up to 100 attendees for a specified Amazon Chime SDK meeting * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListAttendees.html */ public toListAttendees() { return this.to('ListAttendees'); } /** * Grants permission to list the bots associated with the administrator's Amazon Chime Enterprise account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListBots.html */ public toListBots() { return this.to('ListBots'); } /** * Grants permission to list Call Detail Record S3 buckets * * Access Level: List * * Dependent actions: * - s3:ListAllMyBuckets * - s3:ListBucket * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toListCDRBucket() { return this.to('ListCDRBucket'); } /** * Grants permission to list the calling regions available for the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html */ public toListCallingRegions() { return this.to('ListCallingRegions'); } /** * Grants permission to list all the users banned from a particular channel * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelBans.html */ public toListChannelBans() { return this.to('ListChannelBans'); } /** * Grants permission to list all channel memberships in a channel * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelMemberships.html */ public toListChannelMemberships() { return this.to('ListChannelMemberships'); } /** * Grants permission to list all channels that a particular AppInstanceUser is a part of * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelMembershipsForAppInstanceUser.html */ public toListChannelMembershipsForAppInstanceUser() { return this.to('ListChannelMembershipsForAppInstanceUser'); } /** * Grants permission to list all the messages in a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelMessages.html */ public toListChannelMessages() { return this.to('ListChannelMessages'); } /** * Grants permission to list all the moderators for a channel * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelModerators.html */ public toListChannelModerators() { return this.to('ListChannelModerators'); } /** * Grants permission to list all the Channels created under a single Chime AppInstance * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannels.html */ public toListChannels() { return this.to('ListChannels'); } /** * Grants permission to list all channels moderated by an app instance user * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListChannelsModeratedByAppInstanceUser.html */ public toListChannelsModeratedByAppInstanceUser() { return this.to('ListChannelsModeratedByAppInstanceUser'); } /** * Grants permission to list account delegate information associated with your Amazon Chime account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toListDelegates() { return this.to('ListDelegates'); } /** * Grants permission to list active Active Directories hosted in the Directory Service of your AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toListDirectories() { return this.to('ListDirectories'); } /** * Grants permission to list domains associated with your Amazon Chime account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/claim-domain.html */ public toListDomains() { return this.to('ListDomains'); } /** * Grants permission to list Active Directory or Okta user groups associated with your Amazon Chime Enterprise account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toListGroups() { return this.to('ListGroups'); } /** * Grants permission to list media capture pipelines * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListMediaCapturePipelines.html */ public toListMediaCapturePipelines() { return this.to('ListMediaCapturePipelines'); } /** * Grants permission to list all events that occurred for a specified meeting * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/view-reports.html */ public toListMeetingEvents() { return this.to('ListMeetingEvents'); } /** * Grants permission to list the tags applied to an Amazon Chime SDK meeting resource * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListMeetingTags.html */ public toListMeetingTags() { return this.to('ListMeetingTags'); } /** * Grants permission to list up to 100 active Amazon Chime SDK meetings * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListMeetings.html */ public toListMeetings() { return this.to('ListMeetings'); } /** * Grants permission to list meetings ended during the specified date range * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/ag/view-reports.html */ public toListMeetingsReportData() { return this.to('ListMeetingsReportData'); } /** * Grants permission to list the phone number orders under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListPhoneNumberOrders.html */ public toListPhoneNumberOrders() { return this.to('ListPhoneNumberOrders'); } /** * Grants permission to list the phone numbers under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListPhoneNumbers.html */ public toListPhoneNumbers() { return this.to('ListPhoneNumbers'); } /** * Grants permission to list proxy sessions for the specified Amazon Chime Voice Connector * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListProxySessions.html */ public toListProxySessions() { return this.to('ListProxySessions'); } /** * Grants permission to list all room members * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListRoomMemberships.html */ public toListRoomMemberships() { return this.to('ListRoomMemberships'); } /** * Grants permission to list rooms * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListRooms.html */ public toListRooms() { return this.to('ListRooms'); } /** * Grants permission to list all Amazon Chime SIP media applications under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListSipMediaApplications.html */ public toListSipMediaApplications() { return this.to('ListSipMediaApplications'); } /** * Grants permission to list all Amazon Chime SIP rules under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListSipRules.html */ public toListSipRules() { return this.to('ListSipRules'); } /** * Grants permission to list the phone number countries supported by the AWS account * * Access Level: List */ public toListSupportedPhoneNumberCountries() { return this.to('ListSupportedPhoneNumberCountries'); } /** * Grants permission to list the tags applied to an Amazon Chime resource * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list the users that belong to the specified Amazon Chime account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListUsers.html */ public toListUsers() { return this.to('ListUsers'); } /** * Grants permission to list the Amazon Chime Voice Connector Groups under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListVoiceConnectorGroups.html */ public toListVoiceConnectorGroups() { return this.to('ListVoiceConnectorGroups'); } /** * Grants permission to list the SIP termination credentials for the specified Amazon Chime Voice Connector * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListVoiceConnectorTerminationCredentials.html */ public toListVoiceConnectorTerminationCredentials() { return this.to('ListVoiceConnectorTerminationCredentials'); } /** * Grants permission to list the Amazon Chime Voice Connectors under the administrator's AWS account * * Access Level: List * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ListVoiceConnectors.html */ public toListVoiceConnectors() { return this.to('ListVoiceConnectors'); } /** * Grants permission to log out the specified user from all of the devices they are currently logged into * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_LogoutUser.html */ public toLogoutUser() { return this.to('LogoutUser'); } /** * Grants permission to enable data retention for the app instance * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutAppInstanceRetentionSettings.html */ public toPutAppInstanceRetentionSettings() { return this.to('PutAppInstanceRetentionSettings'); } /** * Grants permission to configure data streaming for the app instance * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutAppInstanceStreamingConfigurations.html */ public toPutAppInstanceStreamingConfigurations() { return this.to('PutAppInstanceStreamingConfigurations'); } /** * Grants permission to update details for an events configuration for a bot to receive outgoing events * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutEventsConfiguration.html */ public toPutEventsConfiguration() { return this.to('PutEventsConfiguration'); } /** * Grants permission to create or update retention settings for the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutRetentionSettings.html */ public toPutRetentionSettings() { return this.to('PutRetentionSettings'); } /** * Grants permission to update logging configuration settings for Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutSipMediaApplicationLoggingConfiguration.html */ public toPutSipMediaApplicationLoggingConfiguration() { return this.to('PutSipMediaApplicationLoggingConfiguration'); } /** * Grants permission to add emergency calling configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorEmergencyCallingConfiguration.html */ public toPutVoiceConnectorEmergencyCallingConfiguration() { return this.to('PutVoiceConnectorEmergencyCallingConfiguration'); } /** * Grants permission to add logging configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * Dependent actions: * - logs:CreateLogDelivery * - logs:CreateLogGroup * - logs:DeleteLogDelivery * - logs:DescribeLogGroups * - logs:GetLogDelivery * - logs:ListLogDeliveries * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorLoggingConfiguration.html */ public toPutVoiceConnectorLoggingConfiguration() { return this.to('PutVoiceConnectorLoggingConfiguration'); } /** * Grants permission to update the origination settings for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorOrigination.html */ public toPutVoiceConnectorOrigination() { return this.to('PutVoiceConnectorOrigination'); } /** * Grants permission to add proxy configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorProxy.html */ public toPutVoiceConnectorProxy() { return this.to('PutVoiceConnectorProxy'); } /** * Grants permission to add streaming configuration for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorStreamingConfiguration.html */ public toPutVoiceConnectorStreamingConfiguration() { return this.to('PutVoiceConnectorStreamingConfiguration'); } /** * Grants permission to update the termination settings for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorTermination.html */ public toPutVoiceConnectorTermination() { return this.to('PutVoiceConnectorTermination'); } /** * Grants permission to add SIP termination credentials for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_PutVoiceConnectorTerminationCredentials.html */ public toPutVoiceConnectorTerminationCredentials() { return this.to('PutVoiceConnectorTerminationCredentials'); } /** * Grants permission to redact message content * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_RedactChannelMessage.html */ public toRedactChannelMessage() { return this.to('RedactChannelMessage'); } /** * Grants permission to redact the specified Chime conversation Message * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_RedactConversationMessage.html */ public toRedactConversationMessage() { return this.to('RedactConversationMessage'); } /** * Grants permission to redacts the specified Chime room Message * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_RedactRoomMessage.html */ public toRedactRoomMessage() { return this.to('RedactRoomMessage'); } /** * Grants permission to regenerate the security token for the specified bot * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_RegenerateSecurityToken.html */ public toRegenerateSecurityToken() { return this.to('RegenerateSecurityToken'); } /** * Grants permission to modify the account name for your Amazon Chime Enterprise or Team account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/rename-account.html */ public toRenameAccount() { return this.to('RenameAccount'); } /** * Grants permission to renew the delegation request associated with an Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toRenewDelegate() { return this.to('RenewDelegate'); } /** * Grants permission to reset the account resource in your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toResetAccountResource() { return this.to('ResetAccountResource'); } /** * Grants permission to reset the personal meeting PIN for the specified user on an Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_ResetPersonalPIN.html */ public toResetPersonalPIN() { return this.to('ResetPersonalPIN'); } /** * Grants permission to restore the specified phone number from the deltion queue back to the phone number inventory * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_RestorePhoneNumber.html */ public toRestorePhoneNumber() { return this.to('RestorePhoneNumber'); } /** * Grants permission to download the file containing links to all user attachments returned as part of the "Request attachments" action * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/request-attachments.html */ public toRetrieveDataExports() { return this.to('RetrieveDataExports'); } /** * Grants permission to search phone numbers that can be ordered from the carrier * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/APIReference/API_SearchAvailablePhoneNumbers.html */ public toSearchAvailablePhoneNumbers() { return this.to('SearchAvailablePhoneNumbers'); } /** * Grants permission to send a message to a particular channel that the member is a part of * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_SendChannelMessage.html */ public toSendChannelMessage() { return this.to('SendChannelMessage'); } /** * Grants permission to submit the "Request attachments" request * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/request-attachments.html */ public toStartDataExport() { return this.to('StartDataExport'); } /** * Grants permission to start transcription for a meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_StartMeetingTranscription.html */ public toStartMeetingTranscription() { return this.to('StartMeetingTranscription'); } /** * Grants permission to stop transcription for a meeting * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_StopMeetingTranscription.html */ public toStopMeetingTranscription() { return this.to('StopMeetingTranscription'); } /** * Grants permission to submit a customer service support request * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/chime-getting-admin-support.html */ public toSubmitSupportRequest() { return this.to('SubmitSupportRequest'); } /** * Grants permission to suspend users from an Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/manage-access.html */ public toSuspendUsers() { return this.to('SuspendUsers'); } /** * Grants permission to apply the specified tags to the specified Amazon Chime SDK attendee * * Access Level: Tagging * * https://docs.aws.amazon.com/chime/latest/APIReference/API_TagAttendee.html */ public toTagAttendee() { return this.to('TagAttendee'); } /** * Grants permission to apply the specified tags to the specified Amazon Chime SDK meeting * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_TagMeeting.html */ public toTagMeeting() { return this.to('TagMeeting'); } /** * Grants permission to apply the specified tags to the specified Amazon Chime resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/chime/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to unauthorize an Active Directory from your Amazon Chime Enterprise account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toUnauthorizeDirectory() { return this.to('UnauthorizeDirectory'); } /** * Grants permission to untag the specified tags from the specified Amazon Chime SDK attendee * * Access Level: Tagging * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UntagAttendee.html */ public toUntagAttendee() { return this.to('UntagAttendee'); } /** * Grants permission to untag the specified tags from the specified Amazon Chime SDK meeting * * Access Level: Tagging * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UntagMeeting.html */ public toUntagMeeting() { return this.to('UntagMeeting'); } /** * Grants permission to untag the specified tags from the specified Amazon Chime resource * * Access Level: Tagging * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update account details for the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateAccount.html */ public toUpdateAccount() { return this.to('UpdateAccount'); } /** * Grants permission to update the OpenIdConfig attributes for your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/okta_sso.html */ public toUpdateAccountOpenIdConfig() { return this.to('UpdateAccountOpenIdConfig'); } /** * Grants permission to update the account resource in your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toUpdateAccountResource() { return this.to('UpdateAccountResource'); } /** * Grants permission to update the settings for the specified Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateAccountSettings.html */ public toUpdateAccountSettings() { return this.to('UpdateAccountSettings'); } /** * Grants permission to update AppInstance metadata * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateAppInstance.html */ public toUpdateAppInstance() { return this.to('UpdateAppInstance'); } /** * Grants permission to update the details for an AppInstanceUser * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateAppInstanceUser.html */ public toUpdateAppInstanceUser() { return this.to('UpdateAppInstanceUser'); } /** * Grants permission to update the status of the specified bot * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateBot.html */ public toUpdateBot() { return this.to('UpdateBot'); } /** * Grants permission to update your Call Detail Record S3 bucket * * Access Level: Write * * Dependent actions: * - s3:CreateBucket * - s3:DeleteBucket * - s3:ListAllMyBuckets * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toUpdateCDRSettings() { return this.to('UpdateCDRSettings'); } /** * Grants permission to update a channel's attributes * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateChannel.html */ public toUpdateChannel() { return this.to('UpdateChannel'); } /** * Grants permission to update the content of a message * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateChannelMessage.html */ public toUpdateChannelMessage() { return this.to('UpdateChannelMessage'); } /** * Grants permission to set the timestamp to the point when a user last read messages in a channel * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateChannelReadMarker.html */ public toUpdateChannelReadMarker() { return this.to('UpdateChannelReadMarker'); } /** * Grants permission to update the global settings related to Amazon Chime for the AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateGlobalSettings.html */ public toUpdateGlobalSettings() { return this.to('UpdateGlobalSettings'); } /** * Grants permission to update phone number details for the specified phone number * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdatePhoneNumber.html */ public toUpdatePhoneNumber() { return this.to('UpdatePhoneNumber'); } /** * Grants permission to update phone number settings related to Amazon Chime for the AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdatePhoneNumberSettings.html */ public toUpdatePhoneNumberSettings() { return this.to('UpdatePhoneNumberSettings'); } /** * Grants permission to update a proxy session for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateProxySession.html */ public toUpdateProxySession() { return this.to('UpdateProxySession'); } /** * Grants permission to update a room * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateRoom.html */ public toUpdateRoom() { return this.to('UpdateRoom'); } /** * Grants permission to update room membership role * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateRoomMembership.html */ public toUpdateRoomMembership() { return this.to('UpdateRoomMembership'); } /** * Grants permission to update properties of Amazon Chime SIP media application under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateSipMediaApplication.html */ public toUpdateSipMediaApplication() { return this.to('UpdateSipMediaApplication'); } /** * Grants permission to update an Amazon Chime SIP media application call under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateSipMediaApplicationCall.html */ public toUpdateSipMediaApplicationCall() { return this.to('UpdateSipMediaApplicationCall'); } /** * Grants permission to update properties of Amazon Chime SIP rule under the administrator's AWS account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateSipRule.html */ public toUpdateSipRule() { return this.to('UpdateSipRule'); } /** * Grants permission to update the supported license tiers available for users in your Amazon Chime account * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/manage-access.html */ public toUpdateSupportedLicenses() { return this.to('UpdateSupportedLicenses'); } /** * Grants permission to update user details for a specified user ID * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateUser.html */ public toUpdateUser() { return this.to('UpdateUser'); } /** * Grants permission to update the licenses for your Amazon Chime users * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/ag/manage-access.html */ public toUpdateUserLicenses() { return this.to('UpdateUserLicenses'); } /** * Grants permission to update user settings related to the specified Amazon Chime user * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateUserSettings.html */ public toUpdateUserSettings() { return this.to('UpdateUserSettings'); } /** * Grants permission to update Amazon Chime Voice Connector details for the specified Amazon Chime Voice Connector * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateVoiceConnector.html */ public toUpdateVoiceConnector() { return this.to('UpdateVoiceConnector'); } /** * Grants permission to update Amazon Chime Voice Connector Group details for the specified Amazon Chime Voice Connector Group * * Access Level: Write * * https://docs.aws.amazon.com/chime/latest/APIReference/API_UpdateVoiceConnectorGroup.html */ public toUpdateVoiceConnectorGroup() { return this.to('UpdateVoiceConnectorGroup'); } /** * Grants permission to validate the account resource in your Amazon Chime account * * Access Level: Read * * https://docs.aws.amazon.com/chime/latest/ag/control-access.html */ public toValidateAccountResource() { return this.to('ValidateAccountResource'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptDelegate", "ActivateUsers", "AddDomain", "AddOrUpdateGroups", "AssociatePhoneNumberWithUser", "AssociatePhoneNumbersWithVoiceConnector", "AssociatePhoneNumbersWithVoiceConnectorGroup", "AssociateSigninDelegateGroupsWithAccount", "AuthorizeDirectory", "BatchCreateAttendee", "BatchCreateChannelMembership", "BatchCreateRoomMembership", "BatchDeletePhoneNumber", "BatchSuspendUser", "BatchUnsuspendUser", "BatchUpdatePhoneNumber", "BatchUpdateUser", "Connect", "ConnectDirectory", "CreateAccount", "CreateApiKey", "CreateAppInstance", "CreateAppInstanceAdmin", "CreateAppInstanceUser", "CreateAttendee", "CreateBot", "CreateBotMembership", "CreateCDRBucket", "CreateChannel", "CreateChannelBan", "CreateChannelMembership", "CreateChannelModerator", "CreateMediaCapturePipeline", "CreateMeeting", "CreateMeetingDialOut", "CreateMeetingWithAttendees", "CreatePhoneNumberOrder", "CreateProxySession", "CreateRoom", "CreateRoomMembership", "CreateSipMediaApplication", "CreateSipMediaApplicationCall", "CreateSipRule", "CreateUser", "CreateVoiceConnector", "CreateVoiceConnectorGroup", "DeleteAccount", "DeleteAccountOpenIdConfig", "DeleteApiKey", "DeleteAppInstance", "DeleteAppInstanceAdmin", "DeleteAppInstanceStreamingConfigurations", "DeleteAppInstanceUser", "DeleteAttendee", "DeleteCDRBucket", "DeleteChannel", "DeleteChannelBan", "DeleteChannelMembership", "DeleteChannelMessage", "DeleteChannelModerator", "DeleteDelegate", "DeleteDomain", "DeleteEventsConfiguration", "DeleteGroups", "DeleteMediaCapturePipeline", "DeleteMeeting", "DeletePhoneNumber", "DeleteProxySession", "DeleteRoom", "DeleteRoomMembership", "DeleteSipMediaApplication", "DeleteSipRule", "DeleteVoiceConnector", "DeleteVoiceConnectorEmergencyCallingConfiguration", "DeleteVoiceConnectorGroup", "DeleteVoiceConnectorOrigination", "DeleteVoiceConnectorProxy", "DeleteVoiceConnectorStreamingConfiguration", "DeleteVoiceConnectorTermination", "DeleteVoiceConnectorTerminationCredentials", "DisassociatePhoneNumberFromUser", "DisassociatePhoneNumbersFromVoiceConnector", "DisassociatePhoneNumbersFromVoiceConnectorGroup", "DisassociateSigninDelegateGroupsFromAccount", "DisconnectDirectory", "InviteDelegate", "InviteUsers", "InviteUsersFromProvider", "ListChannelMessages", "LogoutUser", "PutAppInstanceRetentionSettings", "PutAppInstanceStreamingConfigurations", "PutEventsConfiguration", "PutRetentionSettings", "PutSipMediaApplicationLoggingConfiguration", "PutVoiceConnectorEmergencyCallingConfiguration", "PutVoiceConnectorLoggingConfiguration", "PutVoiceConnectorOrigination", "PutVoiceConnectorProxy", "PutVoiceConnectorStreamingConfiguration", "PutVoiceConnectorTermination", "PutVoiceConnectorTerminationCredentials", "RedactChannelMessage", "RedactConversationMessage", "RedactRoomMessage", "RegenerateSecurityToken", "RenameAccount", "RenewDelegate", "ResetAccountResource", "ResetPersonalPIN", "RestorePhoneNumber", "RetrieveDataExports", "SendChannelMessage", "StartDataExport", "StartMeetingTranscription", "StopMeetingTranscription", "SubmitSupportRequest", "SuspendUsers", "UnauthorizeDirectory", "UpdateAccount", "UpdateAccountOpenIdConfig", "UpdateAccountResource", "UpdateAccountSettings", "UpdateAppInstance", "UpdateAppInstanceUser", "UpdateBot", "UpdateCDRSettings", "UpdateChannel", "UpdateChannelMessage", "UpdateChannelReadMarker", "UpdateGlobalSettings", "UpdatePhoneNumber", "UpdatePhoneNumberSettings", "UpdateProxySession", "UpdateRoom", "UpdateRoomMembership", "UpdateSipMediaApplication", "UpdateSipMediaApplicationCall", "UpdateSipRule", "UpdateSupportedLicenses", "UpdateUser", "UpdateUserLicenses", "UpdateUserSettings", "UpdateVoiceConnector", "UpdateVoiceConnectorGroup" ], "Read": [ "DescribeAppInstance", "DescribeAppInstanceAdmin", "DescribeAppInstanceUser", "DescribeChannel", "DescribeChannelBan", "DescribeChannelMembership", "DescribeChannelMembershipForAppInstanceUser", "DescribeChannelModeratedByAppInstanceUser", "DescribeChannelModerator", "GetAccount", "GetAccountResource", "GetAccountSettings", "GetAccountWithOpenIdConfig", "GetAppInstanceRetentionSettings", "GetAppInstanceStreamingConfigurations", "GetAttendee", "GetBot", "GetCDRBucket", "GetChannelMessage", "GetDomain", "GetEventsConfiguration", "GetGlobalSettings", "GetMediaCapturePipeline", "GetMeeting", "GetMeetingDetail", "GetMessagingSessionEndpoint", "GetPhoneNumber", "GetPhoneNumberOrder", "GetPhoneNumberSettings", "GetProxySession", "GetRetentionSettings", "GetRoom", "GetSipMediaApplication", "GetSipMediaApplicationLoggingConfiguration", "GetSipRule", "GetTelephonyLimits", "GetUser", "GetUserActivityReportData", "GetUserByEmail", "GetUserSettings", "GetVoiceConnector", "GetVoiceConnectorEmergencyCallingConfiguration", "GetVoiceConnectorGroup", "GetVoiceConnectorLoggingConfiguration", "GetVoiceConnectorOrigination", "GetVoiceConnectorProxy", "GetVoiceConnectorStreamingConfiguration", "GetVoiceConnectorTermination", "GetVoiceConnectorTerminationHealth", "SearchAvailablePhoneNumbers", "ValidateAccountResource" ], "List": [ "ListAccountUsageReportData", "ListAccounts", "ListApiKeys", "ListAppInstanceAdmins", "ListAppInstanceUsers", "ListAppInstances", "ListAttendeeTags", "ListAttendees", "ListBots", "ListCDRBucket", "ListCallingRegions", "ListChannelBans", "ListChannelMemberships", "ListChannelMembershipsForAppInstanceUser", "ListChannelModerators", "ListChannels", "ListChannelsModeratedByAppInstanceUser", "ListDelegates", "ListDirectories", "ListDomains", "ListGroups", "ListMediaCapturePipelines", "ListMeetingEvents", "ListMeetingTags", "ListMeetings", "ListMeetingsReportData", "ListPhoneNumberOrders", "ListPhoneNumbers", "ListProxySessions", "ListRoomMemberships", "ListRooms", "ListSipMediaApplications", "ListSipRules", "ListSupportedPhoneNumberCountries", "ListTagsForResource", "ListUsers", "ListVoiceConnectorGroups", "ListVoiceConnectorTerminationCredentials", "ListVoiceConnectors" ], "Tagging": [ "TagAttendee", "TagMeeting", "TagResource", "UntagAttendee", "UntagMeeting", "UntagResource" ] }; /** * Adds a resource of type meeting to the statement * * https://docs.aws.amazon.com/chime/latest/APIReference/API_Meeting.html * * @param meetingId - Identifier for the meetingId. * @param accountId - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onMeeting(meetingId: string, accountId?: string, partition?: string) { var arn = 'arn:${Partition}:chime::${AccountId}:meeting/${MeetingId}'; arn = arn.replace('${MeetingId}', meetingId); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type app-instance to the statement * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AppInstance.html * * @param appInstanceId - Identifier for the appInstanceId. * @param accountId - 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 onAppInstance(appInstanceId: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:chime:${Region}:${AccountId}:app-instance/${AppInstanceId}'; arn = arn.replace('${AppInstanceId}', appInstanceId); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type app-instance-user to the statement * * https://docs.aws.amazon.com/chime/latest/APIReference/API_AppInstanceUser.html * * @param appInstanceId - Identifier for the appInstanceId. * @param appInstanceUserId - Identifier for the appInstanceUserId. * @param accountId - 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 onAppInstanceUser(appInstanceId: string, appInstanceUserId: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:chime:${Region}:${AccountId}:app-instance/${AppInstanceId}/user/${AppInstanceUserId}'; arn = arn.replace('${AppInstanceId}', appInstanceId); arn = arn.replace('${AppInstanceUserId}', appInstanceUserId); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type channel to the statement * * https://docs.aws.amazon.com/chime/latest/APIReference/API_Channel.html * * @param appInstanceId - Identifier for the appInstanceId. * @param channelId - Identifier for the channelId. * @param accountId - 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 onChannel(appInstanceId: string, channelId: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:chime:${Region}:${AccountId}:app-instance/${AppInstanceId}/channel/${ChannelId}'; arn = arn.replace('${AppInstanceId}', appInstanceId); arn = arn.replace('${ChannelId}', channelId); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { isNil, isFunction, isString } from '@terascope/utils'; import { validateFunctionArgs } from '../argument-validator'; import { Column, validateAccepts, getFieldTypesFromFieldConfigAndChildConfig, ColumnOptions, mapVectorEach, mapVectorEachValue, dynamicMapVectorEach, dynamicMapVectorEachValue } from '../../column'; import { DataFrame } from '../../data-frame'; import { FieldTransformConfig, isFieldTransform, isFieldValidation, ProcessMode, FieldValidateConfig, DataTypeFieldAndChildren, FunctionDefinitionConfig, FunctionContext, DynamicFrameFunctionContext } from '../../function-configs/interfaces'; import { Builder, copyVectorToBuilder } from '../../builder'; import { WritableData } from '../../core'; export interface DataFrameAdapterOptions<T extends Record<string, any>> { args?: T | ((index: number) => T), field?: string; } export interface FrameAdapterFn { column(input: Column<any>): Column<any>; frame(input: DataFrame<Record<string, any>>): DataFrame<Record<string, unknown>>; } function transformColumnData<T extends Record<string, any>>( column: Column, fnDef: FieldTransformConfig<T>, options: DataFrameAdapterOptions<T> ): Column { const err = validateAccepts( fnDef.accepts, getFieldTypesFromFieldConfigAndChildConfig( column.vector.config, column.vector.childConfig, ), ); if (err) throw err; const columnOptions: ColumnOptions = { name: column.name, version: column.version, }; const inputConfig: DataTypeFieldAndChildren = { field_config: column.config, child_config: column.vector.childConfig }; let outputConfig: DataTypeFieldAndChildren; const args = isFunction(options.args) ? options.args(0) : options.args as T; if (fnDef.output_type) { outputConfig = fnDef.output_type( inputConfig, args ); } else { outputConfig = inputConfig; } const builder = Builder.make( new WritableData(column.vector.size), { childConfig: outputConfig.child_config, config: outputConfig.field_config, name: column.vector.name, }, ); if (isFunction(options.args)) { const context: DynamicFrameFunctionContext<T> = { args: options.args, parent: column, inputConfig, }; if (fnDef.process_mode === ProcessMode.NONE) { return new Column( copyVectorToBuilder(column.vector, builder), columnOptions ); } if (fnDef.process_mode === ProcessMode.FULL_VALUES) { return new Column( dynamicMapVectorEach( column.vector, builder, dynamicTransformerFN(fnDef, context), ), columnOptions ); } return new Column( dynamicMapVectorEach( column.vector, builder, dynamicTransformerFN(fnDef, context), ), columnOptions ); } const context: FunctionContext<T> = { args, parent: column, inputConfig, outputConfig }; const transformFn = fnDef.create(context); if (fnDef.process_mode === ProcessMode.NONE) { return new Column( copyVectorToBuilder(column.vector, builder), columnOptions ); } if (fnDef.process_mode === ProcessMode.FULL_VALUES) { return new Column( mapVectorEach( column.vector, builder, transformFn, ), columnOptions ); } return new Column( mapVectorEachValue( column.vector, builder, transformFn, ), columnOptions ); } function validatorTransformFN(validatorFn: (value: unknown, index: number) => unknown) { return function _validatorTransform(value: unknown, index: number): unknown { if (validatorFn(value, index)) return value; return null; }; } function dynamicValidatorFN<T>( fnDef: FieldValidateConfig<T>, context: DynamicFrameFunctionContext<T> ) { return function _dynamicValidatorFN(index: number) { const newArgs = context.args(index); const args = validateFunctionArgs(fnDef, newArgs); const fullContext = { ...context, args }; const validatorFn = fnDef.create(fullContext); return validatorTransformFN(validatorFn); }; } function dynamicTransformerFN<T>( fnDef: FieldTransformConfig<T>, context: DynamicFrameFunctionContext<T> ) { return function _dynamicTransformerFN(index: number) { const newArgs = context.args(index); const args = validateFunctionArgs(fnDef, newArgs); const fullContext = { ...context, args }; return fnDef.create(fullContext); }; } function validateColumnData<T extends Record<string, any>>( column: Column, fnDef: FieldValidateConfig<T>, options: DataFrameAdapterOptions<T> ): Column { const err = validateAccepts( fnDef.accepts, getFieldTypesFromFieldConfigAndChildConfig( column.vector.config, column.vector.childConfig ), ); if (err) { // if there is an error, there is a type mismatch // there is no need to execute, just return an empty column return column.clearAll(); } const columnOptions: ColumnOptions = { name: column.name, version: column.version, }; const inputConfig = { field_config: column.config, child_config: column.vector.childConfig, }; const builder = Builder.make( new WritableData(column.vector.size), { childConfig: column.vector.childConfig, config: column.vector.config, name: column.vector.name, }, ); // since this is a function, it will return dynamic args // need to use separate logic for that feature if (isFunction(options.args)) { const context: DynamicFrameFunctionContext<T> = { args: options.args, parent: column, inputConfig, }; if (fnDef.process_mode === ProcessMode.FULL_VALUES) { return new Column( dynamicMapVectorEach( column.vector, builder, dynamicValidatorFN(fnDef, context), ), columnOptions ); } return new Column( dynamicMapVectorEachValue( column.vector, builder, dynamicValidatorFN(fnDef, context), ), columnOptions ); } const context: FunctionContext<T> = { args: options.args as T, parent: column, inputConfig }; const validatorFn = fnDef.create(context); const validatorTransform = validatorTransformFN(validatorFn); if (fnDef.process_mode === ProcessMode.FULL_VALUES) { return new Column( mapVectorEach( column.vector, builder, validatorTransform, ), columnOptions ); } return new Column( mapVectorEachValue( column.vector, builder, validatorTransform, ), columnOptions ); } function validateColumn<T extends Record<string, any>>( fnDef: FieldValidateConfig<T>, options: DataFrameAdapterOptions<T> ) { return function _validateColumn(column: Column<any>): Column<any> { return validateColumnData(column, fnDef, options); }; } function transformColumn<T extends Record<string, any>>( fnDef: FieldTransformConfig<T>, options: DataFrameAdapterOptions<T> ) { return function _transformColumn(column: Column): Column { return transformColumnData(column, fnDef, options); }; } function validateFrame<T extends Record<string, any>>( fnDef: FieldValidateConfig<T>, options: DataFrameAdapterOptions<T> ) { return function _validateFrame( frame: DataFrame<Record<string, unknown>> ): DataFrame<Record<string, unknown>> { const { field } = options; if (isNil(options.field) || !isString(field)) throw new Error('Must provide a field option when running a DataFrame'); const col = frame.getColumnOrThrow(field); // TODO: should we pass along the parent dataFrame as well? const validCol = validateColumnData(col, fnDef, options); return frame.assign([validCol]); }; } function transformFrame<T extends Record<string, any>>( fnDef: FieldTransformConfig<T>, options: DataFrameAdapterOptions<T> ) { return function _transformFrame( frame: DataFrame<Record<string, unknown>> ): DataFrame<Record<string, unknown>> { const { field } = options; if (isNil(field) || !isString(field)) throw new Error('Must provide a field option when running a DataFrame'); const col = frame.getColumnOrThrow(field); const newCol = transformColumnData(col, fnDef, options); return frame.assign([newCol]); }; } export function dataFrameAdapter<T extends Record<string, any> = Record<string, unknown>>( fnDef: FunctionDefinitionConfig<T>, options: DataFrameAdapterOptions<T> = {} ): FrameAdapterFn { if (isNil(options.args)) options.args = {} as T; // we will validate on each call later if (!isFunction(options.args)) { options.args = validateFunctionArgs(fnDef, options.args); } if (isFieldValidation(fnDef)) { return { column: validateColumn(fnDef, options), frame: validateFrame(fnDef, options) }; } if (isFieldTransform(fnDef)) { return { column: transformColumn(fnDef, options), frame: transformFrame(fnDef, options) }; } throw new Error(`Function definition "${fnDef.name}" (type: ${fnDef.type}) is not supported`); }
the_stack
import { ProcessIEMetadata } from "./../../../adapters/mongo-db/repo-models"; import { NewContractRequest, TaskExecutionRequest, } from "./../../utils/structs/async-requests"; import { print, TypeMessage, printSeparator, } from "../../../adapters/messages/console-log"; import { AccountInfo } from "./../../../adapters/ethereum-blockchain/structs/account-info"; import { ContractInfo } from "./../../../adapters/ethereum-blockchain/structs/contract-info"; import { RepoType } from "../../../adapters/mongo-db/repo-types"; import { printError } from "../../../adapters/messages/error-logs"; import * as mongoDBAdapter from "./../../../adapters/mongo-db/mongo-db-adapter"; import * as ethereumAdapter from "./../../../adapters/ethereum-blockchain/ethereum-adapter"; import { FunctionInfo } from "../../../adapters/ethereum-blockchain/structs/function-info"; import * as eventMonitorService from "./event-monitor"; import { EventType } from "./../worklist-handler/event-monitor"; import { webSocket } from "../../../app"; let defaultAcccount: AccountInfo; export let createNewProcessInstance = async ( iFlowAddr: string, runtimeRegistry: ContractInfo, accessCtrolAddr: string, rbPolicyAddr: string, taskRoleMapAddr: string ) => { try { await validateAddressInput(iFlowAddr, "IFlow"); await validateAddressInput(accessCtrolAddr, "DynamicAccessControl"); await validateAddressInput(rbPolicyAddr, "RoleBindingPolicy"); await validateAddressInput(taskRoleMapAddr, "TaskRoleMap"); let interpreterInfo = await getInterpreterInfoFromIFlow(iFlowAddr); let transactionHash = await ethereumAdapter.execContractFunctionAsync( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("newRestrictedIInstanceFor", [ "address", "address", "address", "address", "address", ]), this.defaultAccount, [ iFlowAddr, interpreterInfo.address, accessCtrolAddr, rbPolicyAddr, taskRoleMapAddr, ] ); eventMonitorService.listenForPendingLogs( interpreterInfo.address, interpreterInfo.abi, EventType.NewCaseCreated, new NewContractRequest( transactionHash, this.handleNewInstanceCreated, interpreterInfo.address ) ); return transactionHash; } catch (error) { printError( `INTERPRETATION ENGINE: executionMediator`, "createNewProcessInstance", error ); return Promise.reject(error); } }; export let queryProcessState = async ( iDataAddr: string, runtimeRegistry: ContractInfo ) => { try { await validateAddressInput(iDataAddr, "IData"); // Retrieving the IFlow node related to the input IData from Runtime Registry. let iFlowAddr = await findIFlowAddress(iDataAddr, runtimeRegistry); // Retrieving identifier of the process metadata entry in repository from Runtime Registry. let procId = await ethereumAdapter.callContractFunction( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("getBundleIdFromIFlow", ["address"], "bytes32"), this.defaultAccount, [iFlowAddr] ); // Retrieving the Process Hierarchy metadata from process repository let procInfo = (await mongoDBAdapter.findModelMetadataById( RepoType.ProcessInterpretedEngine, procId )) as ProcessIEMetadata; // BFS on process hierarchy to discover enabled tasks let enabledWorkitems = new Array<any>(); let queue = [procInfo]; let iDataAddresses = [iDataAddr]; for (let topP = 0; topP < queue.length; topP++) { procInfo = queue[topP]; iDataAddr = iDataAddresses[topP]; let iFlowInfo = procInfo.iFlow; let iDataInfo = procInfo.iData; let tokens = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( iDataAddr, iDataInfo.abi, new FunctionInfo("getMarking", [], "uint256"), this.defaultAccount ) ); let elementList: Array<any> = procInfo.indexToElement; for (let eInd = 1; eInd < elementList.length; eInd++) { let preC = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( iFlowInfo.address, iFlowInfo.abi, new FunctionInfo("getPreCond", ["uint256"], "uint256"), this.defaultAccount, [eInd] ) ); let typeInfo = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( iFlowInfo.address, iFlowInfo.abi, new FunctionInfo("getTypeInfo", ["uint256"], "uint256"), this.defaultAccount, [eInd] ) ); if (isWorkItem(typeInfo)) { // User Task or Receive Task for (let i = 0; i < preC.length; i++) { if (preC[i] === "1" && i < tokens.length && tokens[i] === "1") { enabledWorkitems.push({ elementName: JSON.parse(elementList[eInd].element).eName, input: elementList[eInd].input, output: elementList[eInd].output, bundleId: procInfo._id, hrefs: [`/i-flow/${eInd}/i-data/${iDataAddr}`], }); break; } } } } let startedActivities = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( iDataAddr, iDataInfo.abi, new FunctionInfo("getStartedActivities", [], "uint256"), this.defaultAccount ) ); for (let subPInd = 1; subPInd < startedActivities.length; subPInd++) { if (startedActivities[subPInd] === "1") { let childAddresses: Array<string> = await ethereumAdapter.callContractFunction( iDataAddr, iDataInfo.abi, new FunctionInfo("getChildProcInst", ["uint256"], "address[]"), this.defaultAccount, [subPInd] ); for (let j = 0; j < childAddresses.length; j++) { queue.push(procInfo.children[j]); iDataAddresses.push(childAddresses[j]); } } } } printInOutInfo(1, [iDataAddresses[0], enabledWorkitems]); return enabledWorkitems; } catch (error) { printError( `INTERPRETATION ENGINE: executionMediator`, "queryProcessState", error ); return Promise.reject(error); } }; export let executeTask = async ( eIndex: string, iDataAddr: string, inParams: any, runtimeRegistry: ContractInfo ) => { try { await validateAddressInput(iDataAddr, "IData"); // Retrieving the IFlow node related to the input IData from Runtime Registry. let iFlowAddr = await findIFlowAddress(iDataAddr, runtimeRegistry); let iFlowInfo = (await mongoDBAdapter.findContractInfoByAddress( RepoType.SmartContract, iFlowAddr )) as ContractInfo; let iDataInfo = (await mongoDBAdapter.findContractInfoById( RepoType.SmartContract, iFlowInfo._relId )) as ContractInfo; let [paramTypes, paramValues] = extractParams(inParams, eIndex); let transactionHash = await ethereumAdapter.execContractFunctionAsync( iDataAddr, iDataInfo.abi, new FunctionInfo("checkIn", paramTypes), this.defaultAccount, paramValues ); eventMonitorService.listenForPendingTransaction( transactionHash, new TaskExecutionRequest( transactionHash, this.handleTaskExecutionCompleted, eIndex, paramValues, iDataAddr ) ); return transactionHash; } catch (error) { return Promise.reject(error); } }; export let checkOutTaskData = async ( eIndex: string, iDataAddr: string, outParams: Array<any>, runtimeRegistry: ContractInfo ) => { try { if (outParams.length == 0) return {}; await validateAddressInput(iDataAddr, "IData"); // Retrieving the IFlow node related to the input IData from Runtime Registry. let iFlowAddr = await findIFlowAddress(iDataAddr, runtimeRegistry); let iFlowInfo = (await mongoDBAdapter.findContractInfoByAddress( RepoType.SmartContract, iFlowAddr )) as ContractInfo; let iDataInfo = (await mongoDBAdapter.findContractInfoById( RepoType.SmartContract, iFlowInfo._relId )) as ContractInfo; let paramInfo = extractOutParams(outParams); let processData = mapOutParamToValue( await ethereumAdapter.callContractFunction( iDataAddr, iDataInfo.abi, new FunctionInfo(paramInfo[0], ["uint256"], paramInfo[1], true), this.defaultAccount, [eIndex] ), outParams ); printInOutInfo(2, [eIndex, iDataAddr, processData]); return processData; } catch (error) { print(error, TypeMessage.error); return Promise.reject(error); } }; ///////////////////////////////////////////////////// /////// CALLBACKS FOR ASYNCHRONOUS OPERATIONS /////// ///////////////////////////////////////////////////// let findIFlowAddress = async ( iDataAddr: string, runtimeRegistry: ContractInfo ): Promise<string> => { return await ethereumAdapter.callContractFunction( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("getIFlowFromIData", ["address"], "address"), this.defaultAccount, [iDataAddr] ); }; export let handleNewInstanceCreated = async ( requestInfo: NewContractRequest ) => { if (webSocket) webSocket.send(JSON.stringify(requestInfo)); printHandlerInfo(1, requestInfo); }; export let handleTaskExecutionCompleted = ( requestInfo: TaskExecutionRequest ) => { if (webSocket) webSocket.send(JSON.stringify(requestInfo)); printHandlerInfo(2, requestInfo); }; //////////////////////////////////////////// //////////// PRIVATE FUNCTIONS ///////////// //////////////////////////////////////////// let validateAddressInput = async (address: string, nodeType: string) => { if (!ethereumAdapter.isValidBlockchainAddress(address)) { printError( `INTERPRETATION ENGINE: executionMediator`, "createNewProcessInstance", `Invalid ${nodeType} Address ${address}` ); throw new Error(`Invalid ${nodeType} Address ${address}`); } if (!this.defaultAccount) this.defaultAccount = await ethereumAdapter.defaultDeployment(); }; let isWorkItem = (typeInfo: Array<string>) => { return ( typeInfo[0] === "1" && typeInfo[3] === "1" && (typeInfo[11] === "1" || typeInfo[14] === "1") ); }; let getInterpreterInfoFromIFlow = async ( iFlowAddr: string ): Promise<ContractInfo> => { let iFlowInfo = await mongoDBAdapter.findContractInfoByAddress( RepoType.SmartContract, iFlowAddr ); let interpreterAddr = await ethereumAdapter.callContractFunction( iFlowAddr, (iFlowInfo as ContractInfo).abi, new FunctionInfo("getInterpreterInst", [], "address"), this.defaultAccount, [] ); let interpreterInfo = await mongoDBAdapter.findContractInfoByAddress( RepoType.SmartContract, interpreterAddr ); return interpreterInfo as ContractInfo; }; let extractParams = (jsonInput: Array<any>, eInd: string) => { let types = ["uint256"]; let values = [eInd]; jsonInput.forEach((param) => { types.push(param.type); values.push(param.value); }); return [types, values]; }; let extractOutParams = (outParams: Array<any>): Array<string> => { let functName = "checkOut"; let paramTypes = []; outParams.forEach((param) => { functName += param.type.charAt(0).toUpperCase() + param.type.charAt(1); paramTypes.push(param.type.toString()); }); return [functName, `${paramTypes.toString()}`]; }; let mapOutParamToValue = (processData: any, outParams: Array<any>) => { let result = {}; for (let i = 0; i < outParams.length; i++) result[outParams[i].name] = processData[i]; return result; }; let printInOutInfo = (type: number, info: any) => { switch (type) { case 1: { print( `Enabled activities of process running at ${info[0]} retrieved`, TypeMessage.success ); print(JSON.stringify(info[1]), TypeMessage.data); printSeparator(); break; } case 2: { print( `Output params from task ${info[0]} at IData ${info[1]} checked out`, TypeMessage.success ); print(` Data: ${JSON.stringify(info[2])}`, TypeMessage.data); printSeparator(); break; } } }; let printHandlerInfo = (type: number, requestInfo: any) => { switch (type) { case 1: { print( `SUCCESS: New Process Instance created from IFlow running at ${requestInfo.iFlowAddr}`, TypeMessage.success ); print( ` TransactionHash: ${requestInfo.transactionHash}`, TypeMessage.info ); print(` Address: ${requestInfo.iDataAddr}`, TypeMessage.info); print(` GasUsed: ${requestInfo.gasCost} units`, TypeMessage.info); printSeparator(); break; } case 2: { print( `SUCCESS: Task ${requestInfo.eName} executed successfully at IData running at ${requestInfo.iDataAddr}`, TypeMessage.success ); print( ` TransactionHash: ${requestInfo.transactionHash}`, TypeMessage.info ); print(` Input Params: ${requestInfo.params}`, TypeMessage.info); print(` GasUsed: ${requestInfo.gasCost} units`, TypeMessage.info); printSeparator(); break; } } };
the_stack
import { utils } from '@tanker/crypto'; import type { DataStore, BaseConfig, SortParams } from '@tanker/datastore-base'; import { errors as dbErrors } from '@tanker/datastore-base'; import { expect, uuid } from '@tanker/test-utils'; export type { DataStore, BaseConfig }; // eslint-disable-next-line @typescript-eslint/naming-convention const { RecordNotFound, RecordNotUnique, UnknownError, VersionError } = dbErrors; type TestRecord = { _id: string; // eslint-disable-line @typescript-eslint/naming-convention a: string; b: string; c: number; d?: (string | Uint8Array) | null; e?: string; }; // Keep only the original properties, e.g. strip PouchDB private // property '_rev' representing the record's current revision. const cleanRecord = (record: Record<string, any>): TestRecord => { // eslint-disable-next-line @typescript-eslint/naming-convention const { _id, a, b, c, d } = record; if ('e' in record) { // optional field return { _id, a, b, c, d, e: record['e'] }; } return { _id, a, b, c, d }; }; const makeDBName = () => `test-db-${uuid.v4().replace('-', '').slice(0, 12)}`; export type DataStoreGenerator = (baseConfig: BaseConfig) => Promise<DataStore>; export const generateDataStoreTests = (dataStoreName: string, generator: DataStoreGenerator) => describe(`DataStore generic tests: ${dataStoreName}`, () => { // Here are a few useful test constants const tableName = 'test-table'; const schemas = [{ version: 1, tables: [{ name: tableName, indexes: [['a'], ['b'], ['c']], }], }]; const binary = new Uint8Array(32); binary[0] = 42; binary[10] = 255; // Note: 'd' is not indexable since it contains null values // see: https://www.w3.org/TR/IndexedDB/#key-construct const record1 = { _id: 'key1', a: '1', b: 'b', c: 3, d: 'd' }; const record2 = { _id: 'key2', a: '2', b: 'b', c: 1, d: null, e: 'e' }; const record3 = { _id: 'key3', a: '3', b: 'z', c: 2, d: binary, e: 'e' }; describe('admin operations', () => { let storeConfig: BaseConfig; beforeEach(() => { storeConfig = { dbName: makeDBName(), schemas: [...schemas] }; }); it('persists data after reopening', async () => { const store1 = await generator(storeConfig); await store1.put(tableName, record1); await store1.close(); const store2 = await generator(storeConfig); const result = await store2.get(tableName, record1._id); expect(cleanRecord(result)).to.deep.equal(record1); await store2.close(); }); it('can be destroyed and re-created empty', async () => { const store1 = await generator(storeConfig); await store1.put(tableName, record1); await store1.destroy(); const store2 = await generator(storeConfig); const actual = await store2.getAll(tableName); expect(actual).to.be.an('array').that.is.empty; await store2.close(); }); it('can add new indexes with a new schema', async () => { // Populate store const store = await generator(storeConfig); await store.put(tableName, record1); await store.put(tableName, record2); await store.put(tableName, record3); await store.close(); // Upgrade the schema storeConfig.schemas!.push({ version: 2, tables: [{ name: tableName, indexes: [['a'], ['b'], ['c'], ['e']], // add index on 'e' }], }); const storeWithNewSchema = await generator(storeConfig); // Check new index on 'e' is usable const result = await storeWithNewSchema.find(tableName, { selector: { e: record2.e } }); expect(result.map(cleanRecord)).to.deep.equal([record2, record3]); await storeWithNewSchema.close(); }); it('can delete a table with a new schema', async () => { // Populate store const store = await generator(storeConfig); await store.put(tableName, record1); await store.close(); // Upgrade the schema storeConfig.schemas!.push({ version: 2, tables: [{ name: tableName, deleted: true, // delete the only table }], }); const storeWithNewSchema = await generator(storeConfig); // Check the table can't be used anymore await expect(storeWithNewSchema.get(tableName, record1._id)).to.be.rejectedWith(UnknownError); await storeWithNewSchema.close(); }); // pouchDB doesn't handle "schema" versions if (!dataStoreName.match(/pouchdb/)) { it('throws VersionError when opening a storage using downgraded schema', async () => { storeConfig.schemas!.push({ version: 2, tables: [{ name: tableName, indexes: [['a'], ['b'], ['c']], }], }); const store = await generator(storeConfig); await store.close(); storeConfig.schemas!.pop(); await expect(generator(storeConfig)).to.be.rejectedWith(VersionError); }); } }); describe('regular operations', () => { let store: DataStore; before(async () => { store = await generator({ dbName: makeDBName(), schemas }); }); beforeEach(async () => { await store.clear(tableName); }); after(async () => { await store.destroy(); await store.close(); }); describe('basic queries', () => { it('can clear records', async () => { await store.put(tableName, record1); await store.put(tableName, record2); await store.clear(tableName); const result = await store.getAll(tableName); expect(result).to.be.an('array').that.is.empty; }); it('throws RecordNotFound when record is not found', async () => { await store.put(tableName, record1); await expect(store.get(tableName, record2._id)).to.be.rejectedWith(RecordNotFound); }); it('can add and get back a simple record', async () => { await store.add(tableName, record1); const actual = await store.get(tableName, record1._id); expect(cleanRecord(actual)).to.deep.equal(cleanRecord(record1)); }); it('can add and get back a record containing binary data', async () => { await store.add(tableName, record3); const actual = await store.get(tableName, record3._id); const actualBinary = actual['d']; expect(actualBinary).to.be.instanceof(Uint8Array); expect(utils.equalArray(actualBinary, record3.d)).to.be.true; expect(actualBinary.length).to.eq(record3.d.length); expect(cleanRecord(actual)).to.deep.equal(cleanRecord(record3)); }); it('can add and get back a record containing nested binary data', async () => { const record4 = { _id: '4', a: { b: { c: binary } } }; await store.add(tableName, record4); const actual = await store.get(tableName, record4._id); const actualBinary = actual['a'].b.c; expect(utils.equalArray(actualBinary, record4.a.b.c)).to.be.true; expect(actualBinary.length).to.eq(record4.a.b.c.length); expect(cleanRecord(actual)).to.deep.equal(cleanRecord(record4)); }); it('can not add a record with a primary key already in use', async () => { await store.add(tableName, record1); await expect(store.add(tableName, { _id: record1._id })).to.be.rejectedWith(RecordNotUnique); }); it('can put a record several times, with updates', async () => { await store.put(tableName, record1); const updatedRecord: TestRecord = { ...record1 }; updatedRecord.a = 'newValue'; delete updatedRecord.d; await store.put(tableName, updatedRecord); const actual = await store.get(tableName, record1._id); expect(actual['a']).to.eq('newValue'); expect('d' in actual).to.be.false; }); it('can delete a record', async () => { await store.bulkPut(tableName, [record1, record2, record3]); await store.delete(tableName, record2._id); const result = await store.getAll(tableName); expect(result.map(cleanRecord)).to.deep.equal([record1, record3]); }); it('can delete a non-existing record', async () => { await store.bulkPut(tableName, [record1, record2, record3]); await store.delete(tableName, 'blah'); const result = await store.getAll(tableName); expect(result.map(cleanRecord)).to.deep.equal([record1, record2, record3]); }); }); describe('bulk queries', () => { it('can bulk add some records', async () => { await store.bulkAdd(tableName, [record1, record2]); const result1 = await store.getAll(tableName); expect(result1.map(cleanRecord)).to.deep.equal([record1, record2]); }); it('can bulk add empty arrays', async () => { await store.bulkAdd(tableName, []); const all = await store.getAll(tableName); expect(all).to.be.an('array').that.is.empty; }); it('can bulk put empty arrays', async () => { await store.bulkPut(tableName, []); const all = await store.getAll(tableName); expect(all).to.be.an('array').that.is.empty; }); it('can bulk delete empty arrays', async () => { await store.bulkPut(tableName, [record1, record2]); await store.bulkDelete(tableName, []); const all = await store.getAll(tableName); expect(all.length).to.be.equal(2); }); it('bulk add and does not update aready existing records', async () => { await store.bulkAdd(tableName, [record1, record2]); const newRecord2 = { ...record2, e: 'new value' }; await store.bulkAdd(tableName, [newRecord2, record3]); // expect newRecord2 to be silently ignored const result2 = await store.getAll(tableName); expect(result2.map(cleanRecord)).to.deep.equal([record1, record2, record3]); }); it('can bulk put same records several times', async () => { await store.bulkPut(tableName, [record1, record2]); const result1 = await store.getAll(tableName); expect(result1.map(cleanRecord)).to.deep.equal([record1, record2]); const newRecord2 = { ...record2, e: 'new value' }; await store.bulkPut(tableName, [newRecord2, record3]); const result2 = await store.getAll(tableName); expect(result2.map(cleanRecord)).to.deep.equal([record1, newRecord2, record3]); }); it('can bulk put and bulk delete records (passing an array)', async () => { await store.bulkPut(tableName, [record1, record2, record3]); const result1 = await store.getAll(tableName); expect(result1.map(cleanRecord)).to.deep.equal([record1, record2, record3]); await store.bulkDelete(tableName, [record2, record3]); // except record1 const result2 = await store.getAll(tableName); expect(result2.map(cleanRecord)).to.deep.equal([record1]); }); it('can bulk put and bulk delete records (using variadic args)', async () => { await store.bulkPut(tableName, record1, record2, record3); const result1 = await store.getAll(tableName); expect(result1.map(cleanRecord)).to.deep.equal([record1, record2, record3]); await store.bulkDelete(tableName, record1, record3); // except record2 const result2 = await store.getAll(tableName); expect(result2.map(cleanRecord)).to.deep.equal([record2]); }); }); describe('advanced queries', () => { beforeEach(async () => { await store.bulkAdd(tableName, [record1, record2, record3]); }); it('can find the first record to match selector or sort', async () => { const result1 = await store.first(tableName, { selector: { a: record1.a } }); const result2 = await store.first(tableName, { selector: { a: record2.a } }); const result3 = await store.first(tableName, { sort: [{ a: 'asc' }] }); const result4 = await store.first(tableName, { sort: [{ a: 'desc' }] }); const result5 = await store.first(tableName); expect(cleanRecord(result1)).to.deep.equal(record1); expect(cleanRecord(result2)).to.deep.equal(record2); expect(cleanRecord(result3)).to.deep.equal(record1); expect(cleanRecord(result4)).to.deep.equal(record3); expect(cleanRecord(result5)).to.deep.equal(record1); }); it('can find the list of all records matching a value (2 flavors)', async () => { const result1 = await store.find(tableName, { selector: { b: record1.b } }); const result2 = await store.find(tableName, { selector: { b: { $eq: record1.b } } }); expect(result1.map(cleanRecord)).to.have.deep.members([record1, record2]); expect(result2.map(cleanRecord)).to.have.deep.members([record1, record2]); }); it('can sort results in ascending order', async () => { const result = await store.find(tableName, { sort: [{ c: 'asc' }] }); expect(result.map(x => x['c'])).to.deep.equal([1, 2, 3]); }); it('can sort results in descending order', async () => { const result = await store.find(tableName, { sort: [{ c: 'desc' }] }); expect(result.map(x => x['c'])).to.deep.equal([3, 2, 1]); }); it('can limit the number of results', async () => { const result1 = await store.find(tableName, { sort: [{ c: 'asc' }], limit: 2 }); const result2 = await store.find(tableName, { sort: [{ c: 'desc' }], limit: 1 }); expect(result1.map(x => x['c'])).to.deep.equal([1, 2]); expect(result2.map(x => x['c'])).to.deep.equal([3]); }); it('can find records with comparison operators', async () => { const sort: SortParams = [{ c: 'asc' }]; const result1 = await store.find(tableName, { sort, selector: { c: { $gt: 1 } } }); const result2 = await store.find(tableName, { sort, selector: { c: { $gte: 2 } } }); const result3 = await store.find(tableName, { sort, selector: { c: { $lt: 3 } } }); const result4 = await store.find(tableName, { sort, selector: { c: { $lte: 2 } } }); const result5 = await store.find(tableName, { sort, selector: { _id: { $in: ['key2', 'key3'] } } }); expect(result1.map(cleanRecord)).to.deep.equal([record3, record1]); expect(result2.map(cleanRecord)).to.deep.equal([record3, record1]); expect(result3.map(cleanRecord)).to.deep.equal([record2, record3]); expect(result4.map(cleanRecord)).to.deep.equal([record2, record3]); expect(result5.map(cleanRecord)).to.deep.equal([record2, record3]); }); it('can find records with $in operator', async () => { const result1 = await store.find(tableName, { selector: { a: { $in: ['2', '1'] } } }); expect(result1.map(cleanRecord)).to.deep.equal([record1, record2]); }); it('can find records with $ne operator', async () => { const result1 = await store.find(tableName, { selector: { b: { $ne: 'b' } } }); expect(result1.map(cleanRecord)).to.deep.equal([record3]); }); it('can find records with multiple selectors', async () => { // Note: at least one operator given MUST match an index const result1 = await store.find(tableName, { selector: { a: { $gte: '2' }, c: { $lt: 2 } } }); // both indexed const result2 = await store.find(tableName, { selector: { b: 'b', d: null } }); const result3 = await store.find(tableName, { selector: { b: 'b', d: { $ne: null } } }); expect(result1.map(cleanRecord)).to.deep.equal([record2]); expect(result2.map(cleanRecord)).to.deep.equal([record2]); expect(result3.map(cleanRecord)).to.deep.equal([record1]); }); it('can find records with $exists operator on secondary field', async () => { // Note: we're not implementing it on the primary search field as it's not // performant at all and can be achieved with a simple getAll() // followed by a javascript filter! const result1 = await store.find(tableName, { selector: { b: 'b', e: { $exists: true } } }); const result2 = await store.find(tableName, { selector: { b: 'b', e: { $exists: false } } }); expect(result1.map(cleanRecord)).to.deep.equal([record2]); expect(result2.map(cleanRecord)).to.deep.equal([record1]); }); }); }); });
the_stack
import '@material/mwc-icon'; import { MobxLitElement } from '@adobe/lit-mobx'; import { css, customElement, html } from 'lit-element'; import { styleMap } from 'lit-html/directives/style-map'; import { Duration } from 'luxon'; import { computed, observable } from 'mobx'; import { fromPromise, IPromiseBasedObservable, PENDING } from 'mobx-utils'; import '../../../context/artifact_provider'; import '../../expandable_entry'; import './image_diff_artifact'; import './text_artifact'; import './text_diff_artifact'; import { AppState, consumeAppState } from '../../../context/app_state'; import { TEST_STATUS_DISPLAY_MAP } from '../../../libs/constants'; import { consumer } from '../../../libs/context'; import { reportRenderError } from '../../../libs/error_handler'; import { sanitizeHTML } from '../../../libs/sanitize_html'; import { displayCompactDuration, parseProtoDuration } from '../../../libs/time_utils'; import { unwrapObservable } from '../../../libs/unwrap_observable'; import { getRawArtifactUrl, router } from '../../../routes'; import { Artifact, ListArtifactsResponse, TestResult } from '../../../services/resultdb'; import colorClasses from '../../../styles/color_classes.css'; import commonStyle from '../../../styles/common_style.css'; /** * Renders an expandable entry of the given test result. */ @customElement('milo-result-entry') @consumer export class ResultEntryElement extends MobxLitElement { @observable.ref @consumeAppState() appState!: AppState; @observable.ref id = ''; @observable.ref testResult!: TestResult; @observable.ref private _expanded = false; @computed get expanded() { return this._expanded; } set expanded(newVal: boolean) { this._expanded = newVal; // Always render the content once it was expanded so the descendants' states // don't get reset after the node is collapsed. this.shouldRenderContent = this.shouldRenderContent || newVal; } @observable.ref private shouldRenderContent = false; @observable.ref private tagExpanded = false; @computed private get duration() { const durationStr = this.testResult.duration; if (!durationStr) { return null; } return Duration.fromMillis(parseProtoDuration(durationStr)); } @computed private get parentInvId() { return /^invocations\/(.+?)\/.+$/.exec(this.testResult.name)![1]; } @computed private get swarmingTask() { const match = this.parentInvId.match(/^task-(.+)-([0-9a-f]+)$/); if (!match) { return null; } return { host: match[1], id: match[2], }; } @computed private get resultArtifacts$(): IPromiseBasedObservable<ListArtifactsResponse> { if (!this.appState.resultDb) { // Returns a promise that never resolves when resultDb isn't ready. return fromPromise(Promise.race([])); } // TODO(weiweilin): handle pagination. return fromPromise(this.appState.resultDb.listArtifacts({ parent: this.testResult.name })); } @computed private get resultArtifacts() { return unwrapObservable(this.resultArtifacts$, {}).artifacts || []; } @computed private get invArtifacts$() { if (!this.appState.resultDb) { // Returns a promise that never resolves when resultDb isn't ready. return fromPromise(Promise.race([])); } // TODO(weiweilin): handle pagination. return fromPromise(this.appState.resultDb.listArtifacts({ parent: 'invocations/' + this.parentInvId })); } @computed private get invArtifacts() { return unwrapObservable(this.invArtifacts$, {}).artifacts || []; } @computed private get artifactsMapping() { return new Map([ ...this.resultArtifacts.map((obj) => [obj.artifactId, obj] as [string, Artifact]), ...this.invArtifacts.map((obj) => ['inv-level/' + obj.artifactId, obj] as [string, Artifact]), ]); } @computed private get textDiffArtifact() { return this.resultArtifacts.find((a) => a.artifactId === 'text_diff'); } @computed private get imageDiffArtifactGroup() { return { expected: this.resultArtifacts.find((a) => a.artifactId === 'expected_image'), actual: this.resultArtifacts.find((a) => a.artifactId === 'actual_image'), diff: this.resultArtifacts.find((a) => a.artifactId === 'image_diff'), }; } private renderFailureReason() { const errMsg = this.testResult.failureReason?.primaryErrorMessage; if (!errMsg) { return html``; } return html` <milo-expandable-entry contentRuler="none" .expanded=${true}> <span slot="header">Failure Reason:</span> <pre id="failure-reason" class="info-block" slot="content">${errMsg}</pre> </milo-expandable-entry> `; } private renderSummaryHtml() { if (!this.testResult.summaryHtml) { return html``; } return html` <milo-expandable-entry contentRuler="none" .expanded=${true}> <span slot="header">Summary:</span> <div id="summary-html" class="info-block" slot="content"> <milo-artifact-provider .artifacts=${this.artifactsMapping} .finalized=${this.invArtifacts$.state !== PENDING && this.resultArtifacts$.state !== PENDING} > ${sanitizeHTML(this.testResult.summaryHtml)} </milo-artifact-provider> </div> </milo-expandable-entry> `; } private renderTags() { if ((this.testResult.tags || []).length === 0) { return html``; } return html` <milo-expandable-entry contentRuler="invisible" .onToggle=${(expanded: boolean) => { this.tagExpanded = expanded; }} > <span slot="header" class="one-line-content"> Tags: <span class="greyed-out" style=${styleMap({ display: this.tagExpanded ? 'none' : '' })}> ${this.testResult.tags?.map( (tag) => html` <span class="kv-key">${tag.key}</span> <span class="kv-value">${tag.value}</span> ` )} </span> </span> <table id="tag-table" slot="content" border="0"> ${this.testResult.tags?.map( (tag) => html` <tr> <td>${tag.key}:</td> <td>${tag.value}</td> </tr> ` )} </table> </milo-expandable-entry> `; } private renderInvocationLevelArtifacts() { if (this.invArtifacts.length === 0) { return html``; } return html` <div id="inv-artifacts-header"> From the parent inv <a href=${router.urlForName('invocation', { invocation_id: this.parentInvId })}></a>: </div> <ul> ${this.invArtifacts.map( (artifact) => html` <li> <a href=${getRawArtifactUrl(artifact.name)} target="_blank">${artifact.artifactId}</a> </li> ` )} </ul> `; } private renderArtifacts() { const artifactCount = this.resultArtifacts.length + this.invArtifacts.length; if (artifactCount === 0) { return html``; } return html` <milo-expandable-entry contentRuler="invisible"> <span slot="header"> Artifacts: <span class="greyed-out">${artifactCount}</span> </span> <div slot="content"> <ul> ${this.resultArtifacts.map( (artifact) => html` <li> <a href=${getRawArtifactUrl(artifact.name)} target="_blank">${artifact.artifactId}</a> </li> ` )} </ul> ${this.renderInvocationLevelArtifacts()} </div> </milo-expandable-entry> `; } private renderContent() { if (!this.shouldRenderContent) { return html``; } return html` ${this.renderFailureReason()}${this.renderSummaryHtml()} ${this.textDiffArtifact && html` <milo-text-diff-artifact .artifact=${this.textDiffArtifact}> </milo-text-diff-artifact> `} ${this.imageDiffArtifactGroup.diff && html` <milo-image-diff-artifact .expected=${this.imageDiffArtifactGroup.expected} .actual=${this.imageDiffArtifactGroup.actual} .diff=${this.imageDiffArtifactGroup.diff} > </milo-image-diff-artifact> `} ${this.renderArtifacts()} ${this.renderTags()} `; } protected render = reportRenderError(this, () => { return html` <milo-expandable-entry .expanded=${this.expanded} .onToggle=${(expanded: boolean) => (this.expanded = expanded)}> <span id="header" slot="header"> <div class="badge" title=${this.duration ? '' : 'No duration'}> ${this.duration ? displayCompactDuration(this.duration) : 'N/A'} </div> run #${this.id} <span class=${this.testResult.expected ? 'expected' : 'unexpected'}> ${this.testResult.expected ? 'expectedly' : 'unexpectedly'} ${TEST_STATUS_DISPLAY_MAP[this.testResult.status]} </span> ${this.swarmingTask ? html` in task: <a href="https://${this.swarmingTask.host}/task?id=${this.swarmingTask.id}" target="_blank" @click=${(e: Event) => e.stopPropagation()} > ${this.swarmingTask.id} </a> ` : ''} </span> <div slot="content">${this.renderContent()}</div> </milo-expandable-entry> `; }); static styles = [ commonStyle, colorClasses, css` :host { display: block; } #header { display: inline-block; font-size: 14px; letter-spacing: 0.1px; font-weight: 500; } [slot='header'] { overflow: hidden; text-overflow: ellipsis; } [slot='content'] { overflow: hidden; } .info-block { background-color: var(--block-background-color); padding: 5px; } pre { margin: 0; font-size: 12px; white-space: pre-wrap; overflow-wrap: break-word; } #summary-html p:first-child { margin-top: 0; } #summary-html p:last-child { margin-bottom: 0; } #tag-table { width: fit-content; } .kv-key::after { content: ':'; } .kv-value::after { content: ','; } .kv-value:last-child::after { content: ''; } .greyed-out { color: var(--greyed-out-text-color); } ul { margin: 3px 0; padding-inline-start: 28px; } #inv-artifacts-header { margin-top: 12px; } `, ]; }
the_stack
import { Component, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { ArchwizardModule } from '../archwizard.module'; import { checkClasses } from '../util/test-utils'; import { WizardStep } from '../util/wizard-step.interface'; import { WizardComponent } from './wizard.component'; @Component({ selector: 'aw-test-wizard', template: ` <aw-wizard [disableNavigationBar]="disableNavigationBar" [defaultStepIndex]="defaultStepIndex" [awNavigationMode] [navigateForward]="navigateForward" [navigateBackward]="navigateBackward"> <aw-wizard-step stepTitle='Steptitle 1' *ngIf="showStep1"> Step 1 </aw-wizard-step> <aw-wizard-step stepTitle='Steptitle 2'> Step 2 </aw-wizard-step> <aw-wizard-step stepTitle='Steptitle 3' *ngIf="showStep3"> Step 3 </aw-wizard-step> </aw-wizard> ` }) class WizardTestComponent { public navigateForward = 'deny'; public navigateBackward = 'deny'; public disableNavigationBar = false; public defaultStepIndex = 0; public showStep1 = true; public showStep3 = true; @ViewChild(WizardComponent) public wizard: WizardComponent; } describe('WizardComponent', () => { let wizardTestFixture: ComponentFixture<WizardTestComponent>; let wizardTest: WizardTestComponent; let wizard: WizardComponent; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [WizardTestComponent], imports: [ArchwizardModule] }).compileComponents(); })); beforeEach(fakeAsync(() => { wizardTestFixture = TestBed.createComponent(WizardTestComponent); wizardTestFixture.detectChanges(); wizardTest = wizardTestFixture.componentInstance; wizard = wizardTest.wizard; // wait a tick to ensure that the initialization has been completed tick(); wizardTestFixture.detectChanges(); })); it('should create', () => { expect(wizardTest).toBeTruthy(); expect(wizard).toBeTruthy(); }); it('should contain navigation bar at the correct position in default navBarLocation mode', () => { const navBarEl = wizardTestFixture.debugElement.query(By.css('aw-wizard-navigation-bar')); const wizardEl = wizardTestFixture.debugElement.query(By.css('aw-wizard')); const wizardStepsDiv = wizardTestFixture.debugElement.query(By.css('div.wizard-steps')); // check default: the navbar should be at the top of the wizard if no navBarLocation was set expect(navBarEl).toBeTruthy(); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard')).children.length).toBe(2); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :first-child')).name).toBe('aw-wizard-navigation-bar'); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :last-child')).name).toBe('div'); checkClasses(navBarEl.classes, ['horizontal', 'small']); checkClasses(wizardEl.classes, ['horizontal']); checkClasses(wizardStepsDiv.classes, ['wizard-steps', 'horizontal']); }); it('should contain navigation bar at the correct position in top navBarLocation mode', () => { wizard.navBarLocation = 'top'; wizardTestFixture.detectChanges(); const navBarEl = wizardTestFixture.debugElement.query(By.css('aw-wizard-navigation-bar')); const wizardEl = wizardTestFixture.debugElement.query(By.css('aw-wizard')); const wizardStepsDiv = wizardTestFixture.debugElement.query(By.css('div.wizard-steps')); // check default: the navbar should be at the top of the wizard if no navBarLocation was set expect(navBarEl).toBeTruthy(); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard')).children.length).toBe(2); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :first-child')).name).toBe('aw-wizard-navigation-bar'); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :last-child')).name).toBe('div'); checkClasses(navBarEl.classes, ['horizontal', 'small']); checkClasses(wizardEl.classes, ['horizontal']); checkClasses(wizardStepsDiv.classes, ['wizard-steps', 'horizontal']); }); it('should contain navigation bar at the correct position in left navBarLocation mode', () => { wizard.navBarLocation = 'left'; wizardTestFixture.detectChanges(); const navBarEl = wizardTestFixture.debugElement.query(By.css('aw-wizard-navigation-bar')); const wizardEl = wizardTestFixture.debugElement.query(By.css('aw-wizard')); const wizardStepsDiv = wizardTestFixture.debugElement.query(By.css('div.wizard-steps')); // check default: the navbar should be at the top of the wizard if no navBarLocation was set expect(navBarEl).toBeTruthy(); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard')).children.length).toBe(2); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :first-child')).name).toBe('aw-wizard-navigation-bar'); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :last-child')).name).toBe('div'); checkClasses(navBarEl.classes, ['vertical', 'small']); checkClasses(wizardEl.classes, ['vertical']); checkClasses(wizardStepsDiv.classes, ['wizard-steps', 'vertical']); }); it('should contain navigation bar at the correct position in bottom navBarLocation mode', () => { wizard.navBarLocation = 'bottom'; wizardTestFixture.detectChanges(); const navBarEl = wizardTestFixture.debugElement.query(By.css('aw-wizard-navigation-bar')); const wizardEl = wizardTestFixture.debugElement.query(By.css('aw-wizard')); const wizardStepsDiv = wizardTestFixture.debugElement.query(By.css('div.wizard-steps')); // check default: the navbar should be at the top of the wizard if no navBarLocation was set expect(navBarEl).toBeTruthy(); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard')).children.length).toBe(2); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :first-child')).name).toBe('div'); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :last-child')).name).toBe('aw-wizard-navigation-bar'); checkClasses(navBarEl.classes, ['horizontal', 'small']); checkClasses(wizardEl.classes, ['horizontal']); checkClasses(wizardStepsDiv.classes, ['wizard-steps', 'horizontal']); }); it('should contain navigation bar at the correct position in right navBarLocation mode', () => { wizard.navBarLocation = 'right'; wizardTestFixture.detectChanges(); const navBarEl = wizardTestFixture.debugElement.query(By.css('aw-wizard-navigation-bar')); const wizardEl = wizardTestFixture.debugElement.query(By.css('aw-wizard')); const wizardStepsDiv = wizardTestFixture.debugElement.query(By.css('div.wizard-steps')); // check default: the navbar should be at the top of the wizard if no navBarLocation was set expect(navBarEl).toBeTruthy(); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard')).children.length).toBe(2); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :first-child')).name).toBe('div'); expect(wizardTestFixture.debugElement.query(By.css('aw-wizard > :last-child')).name).toBe('aw-wizard-navigation-bar'); checkClasses(navBarEl.classes, ['vertical', 'small']); checkClasses(wizardEl.classes, ['vertical']); checkClasses(wizardStepsDiv.classes, ['wizard-steps', 'vertical']); }); it('should change the navigation mode correctly during runtime', () => { const oldNavigation = wizard.navigation; wizardTest.navigateForward = 'allow'; wizardTest.navigateBackward = 'allow'; wizardTestFixture.detectChanges(); expect(wizard.navigation).not.toBe(oldNavigation); }); it('should change disableNavigationBar correctly during runtime', () => { expect(wizard.disableNavigationBar).toBe(false); wizardTest.disableNavigationBar = true; wizardTestFixture.detectChanges(); expect(wizard.disableNavigationBar).toBe(true); }); it('should change defaultStepIndex correctly during runtime', () => { expect(wizard.defaultStepIndex).toBe(0); wizardTest.defaultStepIndex = 1; wizardTestFixture.detectChanges(); expect(wizard.defaultStepIndex).toBe(1); }); it('should react on a previous step removal and insertion correctly', fakeAsync(() => { wizard.goToStep(1); tick(); wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); wizardTest.showStep1 = false; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(0); expect(wizard.wizardSteps.length).toBe(2); wizardTest.showStep1 = true; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); })); it('should react on a later step removal and insertion correctly', fakeAsync(() => { wizard.goToStep(1); tick(); wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); wizardTest.showStep3 = false; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(2); wizardTest.showStep3 = true; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); })); it('should react on a combined removal and insertion of previous and later steps correctly', fakeAsync(() => { wizard.goToStep(1); tick(); wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); wizardTest.showStep1 = false; wizardTest.showStep3 = false; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(0); expect(wizard.wizardSteps.length).toBe(1); wizardTest.showStep1 = true; wizardTest.showStep3 = true; wizardTestFixture.detectChanges(); expect(wizard.currentStepIndex).toBe(1); expect(wizard.wizardSteps.length).toBe(3); })); it('should have steps', () => { expect(wizard.wizardSteps.length).toBe(3); }); it('should start at first step', () => { expect(wizard.currentStepIndex).toBe(0); expect(wizard.currentStep.stepTitle).toBe('Steptitle 1'); checkWizardSteps(wizard.wizardSteps, 0); }); it('should return correct step at index', () => { expect(() => wizard.getStepAtIndex(-1)) .toThrow(new Error(`Expected a known step, but got stepIndex: -1.`)); expect(wizard.getStepAtIndex(0).stepTitle).toBe('Steptitle 1'); expect(wizard.getStepAtIndex(1).stepTitle).toBe('Steptitle 2'); expect(wizard.getStepAtIndex(2).stepTitle).toBe('Steptitle 3'); // Check that the first wizard step is the only selected one checkWizardSteps(wizard.wizardSteps, 0); expect(() => wizard.getStepAtIndex(3)) .toThrow(new Error(`Expected a known step, but got stepIndex: 3.`)); }); it('should return correct index at step', () => { expect(wizard.getIndexOfStep(wizard.getStepAtIndex(0))).toBe(0); expect(wizard.getIndexOfStep(wizard.getStepAtIndex(1))).toBe(1); expect(wizard.getIndexOfStep(wizard.getStepAtIndex(2))).toBe(2); }); it('should have next step', () => { expect(wizard.hasNextStep()).toBe(true); wizard.currentStepIndex++; expect(wizard.hasNextStep()).toBe(true); wizard.currentStepIndex++; expect(wizard.hasNextStep()).toBe(false); }); it('should have previous step', () => { expect(wizard.hasPreviousStep()).toBe(false); wizard.currentStepIndex++; expect(wizard.hasPreviousStep()).toBe(true); wizard.currentStepIndex++; expect(wizard.hasPreviousStep()).toBe(true); }); it('should be last step', () => { expect(wizard.isLastStep()).toBe(false); wizard.currentStepIndex++; expect(wizard.isLastStep()).toBe(false); wizard.currentStepIndex++; expect(wizard.isLastStep()).toBe(true); }); it('should return null when staying in an incorrect step', () => { wizard.currentStepIndex = -1; expect(wizard.currentStep).toBeNull(); }); }); function checkWizardSteps(steps: WizardStep[], selectedStepIndex: number) { steps.forEach((step, index) => { // Only the selected step should be selected if (index === selectedStepIndex) { expect(step.selected).toBe(true, `the selected wizard step index ${index} is not selected`); } else { expect(step.selected).toBe(false, `the not selected wizard step index ${index} is selected`); } // All steps before the selected step need to be completed if (index < selectedStepIndex) { expect(step.completed).toBe(true, `the wizard step ${index} is not completed while the currently selected step index is ${selectedStepIndex}`); } else if (index > selectedStepIndex) { expect(step.completed).toBe(false, `the wizard step ${index} is completed while the currently selected step index is ${selectedStepIndex}`); } }); }
the_stack
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action, set } from '@ember/object'; export interface IFilm { /** Title of film. */ title: string; /** Release year. */ year: number; /** IMDb ranking. */ rank: number; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface TestArgs {} export default class Test extends Component<TestArgs> { popperTargetValue!: HTMLElement; propsObject = { active: true, large: true, fill: false, intent: 'primary', icon: 'calendar', rightIcon: 'add', }; text = 'button'; className = 'hii'; propsValue = { className: 'hgh', intent: 'primary', icon: 'tick', }; size = 100; calloutText = `The component is a simple wrapper around the CSS API that provides props for modifiers and optional title element. Any additional HTML props will be spread to the rendered `; elevationText = 'elevationText'; elevation = 4; value = 0.4; options = [{ value: 'a' }, { value: 'b', className: 'foo' }, { value: 'c', disabled: true }, { label: 'Dog' }]; switchLabel = 'Privacy setting'; textIG = 'hi'; value1 = 'asdfsdafasdfsdfsdfsdfsdfsdafasdfdsafasdfdsfadsfadsfdsfdsfdsfdsfsdfsdfdsfsdfsdfsd'; tagText = 'hii'; values = ['hii', 'hii2']; @action onClick() { set(this.propsObject, 'active', !this.propsObject.active); set(this.propsObject, 'intent', 'success'); set(this, 'className', '123'); set(this.propsValue, 'icon', 'add'); set(this, 'elevation', 2); set(this, 'size', 200); set(this, 'value', 0.8); set(this, 'textIG', 'hii1212'); set(this, 'valueNI', 'eee'); } @action onKeyDown() { // console.log('onKeyDown'); } @action onKeyUp() { // console.log('onKeyUp'); } @action handleEnabledChange() { // console.log('hii'); } @action handleChange(values: Array<string>) { // console.log(values); set(this, 'values', values); } //numeric input disabled = true; fill = false; large = false; leftIcon = ''; allowNumericCharactersOnly = true; selectAllOnFocus = false; selectAllOnIncrement = false; min = 0; intent = 'none'; max = 100; valueNI = ''; buttonPosition = 'right'; isOpen = false; keepChildrenMounted = false; collapseText = `[11:53:30] Finished 'typescript-bundle-blueprint' after 769 ms <br /> [11:53:30] Starting 'typescript-typings-blueprint'... <br /> [11:53:30] Finished 'typescript-typings-blueprint' after 198 ms <br /> [11:53:30] write ./blueprint.css <br /> [11:53:30] Finished 'sass-compile-blueprint' after 2.84 s`; show = 'Show'; hide = 'Hide'; build = 'build logs'; @action onClickButton() { //mouse event action set(this, 'isOpen', !this.isOpen); } @action doFuction() { set(this, 'keepChildrenMounted', !this.keepChildrenMounted); } isOpenOverlay = false; hasBackdrop = true; autoFocus = true; enforceFocus = true; canEscapeKeyClose = true; usePortal = true; canOutsideClickClose = true; useTallContent = false; isOpenPopper = false; @action onOverlayToggle() { set(this, 'isOpenOverlay', !this.isOpenOverlay); } @action onOverlayToggle1() { set(this, 'isOpenPopper', !this.isOpenPopper); } @action onClose() { set(this, 'isOpenOverlay', false); set(this, 'isOpenPopper', false); set(this, 'isOpenDialog', !this.isOpenDialog); } @action handleClose() { set(this, 'isOpenOverlay', false); set(this, 'useTallContent', false); } @action focusButton() { (document.querySelector('.focus-button') as HTMLElement).focus(); } @action toggleScrollButton() { set(this, 'useTallContent', !this.useTallContent); } @action onPropsChangeEvent(type: string) { if (type == 'autoFoucs') { set(this, 'autoFocus', !this.autoFocus); } else if (type == 'enforceFocus') { set(this, 'enforceFocus', !this.enforceFocus); } else if (type == 'usePortal') { set(this, 'usePortal', !this.usePortal); } else if (type == 'canOutsideClickClose') { set(this, 'canOutsideClickClose', !this.canOutsideClickClose); } else if (type == 'canEscapeKeyClose') { set(this, 'canEscapeKeyClose', !this.canEscapeKeyClose); } else if (type == 'hasBackdrop') { set(this, 'hasBackdrop', !this.hasBackdrop); } } isOpenDialog = false; @action onDialogToggle() { set(this, 'isOpenDialog', !this.isOpenDialog); } @action didInsertPopper(element: HTMLElement) { this.popperTargetValue = element; } //select TOP_100_FILMS1 = [ { title: 'The Shawshank Redemption', year: 1994 }, { title: 'The Godfather', year: 1972 }, { title: 'The Godfather: Part II', year: 1974 }, { title: 'The Dark Knight', year: 2008 }, { title: '12 Angry Men', year: 1957 }, { title: "Schindler's List", year: 1993 }, { title: 'Pulp Fiction', year: 1994 }, { title: 'The Lord of the Rings: The Return of the King', year: 2003 }, { title: 'The Good, the Bad and the Ugly', year: 1966 }, { title: 'Fight Club', year: 1999 }, { title: 'The Lord of the Rings: The Fellowship of the Ring', year: 2001 }, { title: 'Star Wars: Episode V - The Empire Strikes Back', year: 1980 }, { title: 'Forrest Gump', year: 1994 }, { title: 'Inception', year: 2010 }, { title: 'The Lord of the Rings: The Two Towers', year: 2002 }, { title: "One Flew Over the Cuckoo's Nest", year: 1975 }, { title: 'Goodfellas', year: 1990 }, { title: 'The Matrix', year: 1999 }, { title: 'Seven Samurai', year: 1954 }, { title: 'Star Wars: Episode IV - A New Hope', year: 1977 }, { title: 'City of God', year: 2002 }, { title: 'Se7en', year: 1995 }, { title: 'The Silence of the Lambs', year: 1991 }, { title: "It's a Wonderful Life", year: 1946 }, { title: 'Life Is Beautiful', year: 1997 }, { title: 'The Usual Suspects', year: 1995 }, { title: 'Léon: The Professional', year: 1994 }, { title: 'Spirited Away', year: 2001 }, { title: 'Saving Private Ryan', year: 1998 }, { title: 'Once Upon a Time in the West', year: 1968 }, { title: 'American History X', year: 1998 }, { title: 'Interstellar', year: 2014 }, { title: 'Casablanca', year: 1942 }, { title: 'City Lights', year: 1931 }, { title: 'Psycho', year: 1960 }, { title: 'The Green Mile', year: 1999 }, { title: 'The Intouchables', year: 2011 }, { title: 'Modern Times', year: 1936 }, { title: 'Raiders of the Lost Ark', year: 1981 }, { title: 'Rear Window', year: 1954 }, { title: 'The Pianist', year: 2002 }, { title: 'The Departed', year: 2006 }, { title: 'Terminator 2: Judgment Day', year: 1991 }, { title: 'Back to the Future', year: 1985 }, { title: 'Whiplash', year: 2014 }, { title: 'Gladiator', year: 2000 }, { title: 'Memento', year: 2000 }, { title: 'The Prestige', year: 2006 }, { title: 'The Lion King', year: 1994 }, { title: 'Apocalypse Now', year: 1979 }, { title: 'Alien', year: 1979 }, { title: 'Sunset Boulevard', year: 1950 }, { title: 'Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb', year: 1964, }, { title: 'The Great Dictator', year: 1940 }, { title: 'Cinema Paradiso', year: 1988 }, { title: 'The Lives of Others', year: 2006 }, { title: 'Grave of the Fireflies', year: 1988 }, { title: 'Paths of Glory', year: 1957 }, { title: 'Django Unchained', year: 2012 }, { title: 'The Shining', year: 1980 }, { title: 'WALL·E', year: 2008 }, { title: 'American Beauty', year: 1999 }, { title: 'The Dark Knight Rises', year: 2012 }, { title: 'Princess Mononoke', year: 1997 }, { title: 'Aliens', year: 1986 }, { title: 'Oldboy', year: 2003 }, { title: 'Once Upon a Time in America', year: 1984 }, { title: 'Witness for the Prosecution', year: 1957 }, { title: 'Das Boot', year: 1981 }, { title: 'Citizen Kane', year: 1941 }, { title: 'North by Northwest', year: 1959 }, { title: 'Vertigo', year: 1958 }, { title: 'Star Wars: Episode VI - Return of the Jedi', year: 1983 }, { title: 'Reservoir Dogs', year: 1992 }, { title: 'Braveheart', year: 1995 }, { title: 'M', year: 1931 }, { title: 'Requiem for a Dream', year: 2000 }, { title: 'Amélie', year: 2001 }, { title: 'A Clockwork Orange', year: 1971 }, { title: 'Like Stars on Earth', year: 2007 }, { title: 'Taxi Driver', year: 1976 }, { title: 'Lawrence of Arabia', year: 1962 }, { title: 'Double Indemnity', year: 1944 }, { title: 'Eternal Sunshine of the Spotless Mind', year: 2004 }, { title: 'Amadeus', year: 1984 }, { title: 'To Kill a Mockingbird', year: 1962 }, { title: 'Toy Story 3', year: 2010 }, { title: 'Logan', year: 2017 }, { title: 'Full Metal Jacket', year: 1987 }, { title: 'Dangal', year: 2016 }, { title: 'The Sting', year: 1973 }, { title: '2001: A Space Odyssey', year: 1968 }, { title: "Singin' in the Rain", year: 1952 }, { title: 'Toy Story', year: 1995 }, { title: 'Bicycle Thieves', year: 1948 }, { title: 'The Kid', year: 1921 }, { title: 'Inglourious Basterds', year: 2009 }, { title: 'Snatch', year: 2000 }, { title: '3 Idiots', year: 2009 }, { title: 'Monty Python and the Holy Grail', year: 1975 }, ].map((m, index) => ({ ...m, rank: index + 1 })); TOP_100_FILMS = this.TOP_100_FILMS1; isOpenSelect = false; selectTargetValue!: HTMLElement; @action onSelectToggle() { set(this, 'isOpenSelect', !this.isOpenSelect); } @action selectPath(element: HTMLElement) { this.selectTargetValue = element; } filterFilm = (query, film, _index, exactMatch) => { const normalizedTitle = film.title.toLowerCase(); const normalizedQuery = query.toLowerCase(); if (exactMatch) { return normalizedTitle === normalizedQuery; } else { return `${film.rank}. ${normalizedTitle} ${film.year}`.indexOf(normalizedQuery) >= 0; } }; createFilm = (title: string) => { return { rank: 100 + Math.floor(Math.random() * 100 + 1), title, year: new Date().getFullYear(), }; }; @action onCloseSelect() { set(this, 'isOpenSelect', false); } createdItems = []; film = this.TOP_100_FILMS[0]; maybeCreateNewItemFromQuery = (title: string) => { return { rank: 100 + Math.floor(Math.random() * 100 + 1), title, year: new Date().getFullYear(), }; }; isItemDisabled1 = (film: IFilm) => { return film.year < 2000; }; @action handleValueChange(film: IFilm) { const { createdItems, items } = maybeDeleteCreatedFilmFromArrays(this.TOP_100_FILMS, this.createdItems, this.film); // Add the new film to the list if it is newly created. const { createdItems: nextCreatedItems, items: nextItems } = maybeAddCreatedFilmToArrays(items, createdItems, film); set(this, 'createdItems', nextCreatedItems); set(this, 'film', film); set(this, 'TOP_100_FILMS', nextItems); set(this, 'isOpenSelect', false); } noResults = `<li class=""><a tabindex="-1" class="ee-menu-item ee-disabled"><div class="ee-text-overflow-ellipsis ee-fill">No results.</div></a></li>`; initialContent = `<li class=""><a tabindex="-1" class="ee-menu-item ee-disabled"><div class="ee-text-overflow-ellipsis ee-fill">${this.TOP_100_FILMS1.length} items loaded.</div></a></li>`; // multi-select ------------------------- popoverProps = { minimal: true, }; items = this.TOP_100_FILMS1; createdItemsMulti = []; films = []; areFilmsEqual = (filmA: IFilm, filmB: IFilm) => { // Compare only the titles (ignoring case) just for simplicity. return filmA.title.toLowerCase() === filmB.title.toLowerCase(); }; @action handleFilmSelect(film: IFilm) { if (!this.isFilmSelected(film)) { this.selectFilm(film); } else { this.deselectFilm(this.getSelectedFilmIndex(film)); } } private getSelectedFilmIndex(film: IFilm) { return this.films.indexOf(film); } private isFilmSelected(film: IFilm) { return this.getSelectedFilmIndex(film) !== -1; } private deselectFilm(index: number) { const film = this.films[index]; const { createdItems: nextCreatedItems, items: nextItems } = maybeDeleteCreatedFilmFromArrays( this.items, this.createdItemsMulti, film ); // Delete the item if the user manually created it. set(this, 'createdItemsMulti', nextCreatedItems); set( this, 'films', this.films.filter((_film, i) => i !== index) ); set(this, 'items', nextItems); } private selectFilm(film: IFilm) { this.selectFilms([film]); } private selectFilms(filmsToSelect: IFilm[]) { let nextCreatedItems = this.createdItemsMulti.slice(); let nextFilms = this.films.slice(); let nextItems = this.items.slice(); filmsToSelect.forEach((film) => { const results = maybeAddCreatedFilmToArrays(nextItems, nextCreatedItems, film); nextItems = results.items; nextCreatedItems = results.createdItems; // Avoid re-creating an item that is already selected (the "Create // Item" option will be shown even if it matches an already selected // item). nextFilms = !arrayContainsFilm(nextFilms, film) ? [...nextFilms, film] : nextFilms; }); set(this, 'createdItemsMulti', nextCreatedItems); set(this, 'films', nextFilms); set(this, 'items', nextItems); } renderTag = (film: IFilm) => film.title; @action handleTagRemove(_tag: string, index: number) { this.deselectFilm(index); } @action handleClearTagInput() { set(this, 'films', []); } //tooltip related things goes here @tracked tooltipRefVar: HTMLElement = null; isOpenTooltip = false; tooltip1 = false; tooltip2 = false; @action tooltipRef(element: HTMLElement) { this.tooltipRefVar = element; } @action openTooltip(type: number) { if (type == 1) set(this, 'tooltip1', true); else set(this, 'tooltip2', true); set(this, 'isOpenTooltip', true); } @action closeTooltip(type: number) { if (type == 1) set(this, 'tooltip1', false); else set(this, 'tooltip2', false); set(this, 'isOpenTooltip', false); } // Drawer goes here isOpenDrawer = false; @action handleOpenDrawer() { set(this, 'isOpenDrawer', true); } @action handleCloseDrawer() { set(this, 'isOpenDrawer', false); } } export function maybeAddCreatedFilmToArrays( items: IFilm[], createdItems: IFilm[], film: IFilm ): { createdItems: IFilm[]; items: IFilm[] } { const isNewlyCreatedItem = !arrayContainsFilm(items, film); return { createdItems: isNewlyCreatedItem ? addFilmToArray(createdItems, film) : createdItems, // Add a created film to `items` so that the film can be deselected. items: isNewlyCreatedItem ? addFilmToArray(items, film) : items, }; } export function maybeDeleteCreatedFilmFromArrays( items: IFilm[], createdItems: IFilm[], film: IFilm ): { createdItems: IFilm[]; items: IFilm[] } { const wasItemCreatedByUser = arrayContainsFilm(createdItems, film); // Delete the item if the user manually created it. return { createdItems: wasItemCreatedByUser ? deleteFilmFromArray(createdItems, film) : createdItems, items: wasItemCreatedByUser ? deleteFilmFromArray(items, film) : items, }; } export function arrayContainsFilm(films: IFilm[], filmToFind: IFilm): boolean { return films.some((film: IFilm) => film.title === filmToFind.title); } export function addFilmToArray(films: IFilm[], filmToAdd: IFilm) { return [...films, filmToAdd]; } export function deleteFilmFromArray(films: IFilm[], filmToDelete: IFilm) { return films.filter((film) => film !== filmToDelete); }
the_stack
import { Debug, Log } from '../globals' // const nucleotides = 'ACTG'; const aminoacidsX = 'ACDEFGHIKLMNPQRSTVWY' const aminoacids = 'ARNDCQEGHILKMFPSTWYVBZ?' const blosum62x = [ [4, 0, -2, -1, -2, 0, -2, -1, -1, -1, -1, -2, -1, -1, -1, 1, 0, 0, -3, -2], // A [0, 9, -3, -4, -2, -3, -3, -1, -3, -1, -1, -3, -3, -3, -3, -1, -1, -1, -2, -2], // C [-2, -3, 6, 2, -3, -1, -1, -3, -1, -4, -3, 1, -1, 0, -2, 0, -1, -3, -4, -3], // D [-1, -4, 2, 5, -3, -2, 0, -3, 1, -3, -2, 0, -1, 2, 0, 0, -1, -2, -3, -2], // E [-2, -2, -3, -3, 6, -3, -1, 0, -3, 0, 0, -3, -4, -3, -3, -2, -2, -1, 1, 3], // F [0, -3, -1, -2, -3, 6, -2, -4, -2, -4, -3, 0, -2, -2, -2, 0, -2, -3, -2, -3], // G [-2, -3, -1, 0, -1, -2, 8, -3, -1, -3, -2, 1, -2, 0, 0, -1, -2, -3, -2, 2], // H [-1, -1, -3, -3, 0, -4, -3, 4, -3, 2, 1, -3, -3, -3, -3, -2, -1, 3, -3, -1], // I [-1, -3, -1, 1, -3, -2, -1, -3, 5, -2, -1, 0, -1, 1, 2, 0, -1, -2, -3, -2], // K [-1, -1, -4, -3, 0, -4, -3, 2, -2, 4, 2, -3, -3, -2, -2, -2, -1, 1, -2, -1], // L [-1, -1, -3, -2, 0, -3, -2, 1, -1, 2, 5, -2, -2, 0, -1, -1, -1, 1, -1, -1], // M [-2, -3, 1, 0, -3, 0, 1, -3, 0, -3, -2, 6, -2, 0, 0, 1, 0, -3, -4, -2], // N [-1, -3, -1, -1, -4, -2, -2, -3, -1, -3, -2, -2, 7, -1, -2, -1, -1, -2, -4, -3], // P [-1, -3, 0, 2, -3, -2, 0, -3, 1, -2, 0, 0, -1, 5, 1, 0, -1, -2, -2, -1], // Q [-1, -3, -2, 0, -3, -2, 0, -3, 2, -2, -1, 0, -2, 1, 5, -1, -1, -3, -3, -2], // R [1, -1, 0, 0, -2, 0, -1, -2, 0, -2, -1, 1, -1, 0, -1, 4, 1, -2, -3, -2], // S [0, -1, -1, -1, -2, -2, -2, -1, -1, -1, -1, 0, -1, -1, -1, 1, 5, 0, -2, -2], // T [0, -1, -3, -2, -1, -3, -3, 3, -2, 1, 1, -3, -2, -2, -3, -2, 0, 4, -3, -1], // V [-3, -2, -4, -3, 1, -2, -2, -3, -3, -2, -1, -4, -4, -2, -3, -3, -2, -3, 11, 2], // W [-2, -2, -3, -2, 3, -3, 2, -1, -2, -1, -1, -2, -3, -1, -2, -2, -2, -1, 2, 7] // Y ] const blosum62 = [ // A R N D C Q E G H I L K M F P S T W Y V B Z X [4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0, -2, -1, 0], // A [-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3, -1, 0, -1], // R [-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3, 3, 0, -1], // N [-2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3, 4, 1, -1], // D [0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1, -3, -3, -2], // C [-1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2, 0, 3, -1], // Q [-1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1], // E [0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3, -1, -2, -1], // G [-2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3, 0, 0, -1], // H [-1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3, -3, -3, -1], // I [-1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1, -4, -3, -1], // L [-1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2, 0, 1, -1], // K [-1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1, -3, -1, -1], // M [-2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1, -3, -3, -1], // F [-1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2, -2, -1, -2], // P [1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2, 0, 0, 0], // S [0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0, -1, -1, 0], // T [-3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3, -4, -3, -2], // W [-2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1, -3, -2, -1], // Y [0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4, -3, -2, -1], // V [-2, -1, 3, 4, -3, 0, 1, -1, 0, -3, -4, 0, -3, -3, -2, 0, -1, -4, -3, -3, 4, 1, -1], // B [-1, 0, 0, 1, -3, 3, 4, -2, 0, -3, -3, 1, -1, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1], // Z [0, -1, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, 0, 0, -2, -1, -1, -1, -1, -1] // X ] function prepareMatrix (cellNames: string, mat: number[][]) { let j: number let i = 0 const matDict: { [k: string]: { [k: string]: number } } = {} mat.forEach(function (row) { j = 0 const rowDict: { [k: string]: number } = {} row.forEach(function (elm) { rowDict[ cellNames[ j++ ] ] = elm }) matDict[ cellNames[ i++ ] ] = rowDict }) return matDict } const SubstitutionMatrices = (function () { return { blosum62: prepareMatrix(aminoacids, blosum62), blosum62x: prepareMatrix(aminoacidsX, blosum62x) } }()) export type SubstitutionMatrix = ''|'blosum62'|'blosum62x' class Alignment { substMatrix: { [k: string]: { [k: string]: number } } n: number m: number score?: number ali: string S: number[][] V: number[][] H: number[][] ali1: string ali2: string constructor (readonly seq1: string, readonly seq2: string, readonly gapPenalty = -10, readonly gapExtensionPenalty = -1, substMatrix: SubstitutionMatrix = 'blosum62') { // TODO try encoding seqs as integers and use array subst matrix, maybe faster if (substMatrix) { this.substMatrix = SubstitutionMatrices[ substMatrix ] } } initMatrices () { this.n = this.seq1.length this.m = this.seq2.length // Log.log(this.n, this.m); this.score = undefined this.ali = '' this.S = [] this.V = [] this.H = [] for (let i = 0; i <= this.n; ++i) { this.S[ i ] = [] this.V[ i ] = [] this.H[ i ] = [] for (let j = 0; j <= this.m; ++j) { this.S[ i ][ j ] = 0 this.V[ i ][ j ] = 0 this.H[ i ][ j ] = 0 } } for (let i = 0; i <= this.n; ++i) { this.S[ i ][ 0 ] = this.gap(0) this.H[ i ][ 0 ] = -Infinity } for (let j = 0; j <= this.m; ++j) { this.S[ 0 ][ j ] = this.gap(0) this.V[ 0 ][ j ] = -Infinity } this.S[ 0 ][ 0 ] = 0 // Log.log(this.S, this.V, this.H); } gap (len: number) { return this.gapPenalty + len * this.gapExtensionPenalty } makeScoreFn () { const seq1 = this.seq1 const seq2 = this.seq2 const substMatrix = this.substMatrix if (substMatrix) { return function score (i: number, j: number) { const c1 = seq1[ i ] const c2 = seq2[ j ] try { return substMatrix[ c1 ][ c2 ] } catch (e) { return -4 } } } else { Log.warn('Alignment: no subst matrix') return function scoreNoSubstMat (i: number, j: number) { const c1 = seq1[ i ] const c2 = seq2[ j ] return c1 === c2 ? 5 : -3 } } } calc () { if (Debug) Log.time('Alignment.calc') this.initMatrices() const gap0 = this.gap(0) const scoreFn = this.makeScoreFn() const gapExtensionPenalty = this.gapExtensionPenalty const V = this.V const H = this.H const S = this.S const n = this.n const m = this.m let Vi1, Si1, Vi, Hi, Si for (let i = 1; i <= n; ++i) { Si1 = S[ i - 1 ] Vi1 = V[ i - 1 ] Vi = V[ i ] Hi = H[ i ] Si = S[ i ] for (let j = 1; j <= m; ++j) { Vi[j] = Math.max( Si1[ j ] + gap0, Vi1[ j ] + gapExtensionPenalty ) Hi[j] = Math.max( Si[ j - 1 ] + gap0, Hi[ j - 1 ] + gapExtensionPenalty ) Si[j] = Math.max( Si1[ j - 1 ] + scoreFn(i - 1, j - 1), // match Vi[ j ], // del Hi[ j ] // ins ) } } if (Debug) Log.timeEnd('Alignment.calc') if (Debug) Log.log(this.S, this.V, this.H) } trace () { if (Debug) Log.time('Alignment.trace') this.ali1 = '' this.ali2 = '' const scoreFn = this.makeScoreFn() let i = this.n let j = this.m let mat if (this.S[i][j] >= this.V[i][j]) { mat = 'S' this.score = this.S[i][j] } else if (this.V[i][j] >= this.H[i][j]) { mat = 'V' this.score = this.V[i][j] } else { mat = 'H' this.score = this.H[i][j] } if (Debug) Log.log('Alignment: SCORE', this.score) if (Debug) Log.log('Alignment: S, V, H', this.S[i][j], this.V[i][j], this.H[i][j]) while (i > 0 && j > 0) { if (mat === 'S') { if (this.S[i][j] === this.S[i - 1][j - 1] + scoreFn(i - 1, j - 1)) { this.ali1 = this.seq1[i - 1] + this.ali1 this.ali2 = this.seq2[j - 1] + this.ali2 --i --j mat = 'S' } else if (this.S[i][j] === this.V[i][j]) { mat = 'V' } else if (this.S[i][j] === this.H[i][j]) { mat = 'H' } else { // Log.debug('Alignment: S'); --i --j } } else if (mat === 'V') { if (this.V[i][j] === this.V[i - 1][j] + this.gapExtensionPenalty) { this.ali1 = this.seq1[i - 1] + this.ali1 this.ali2 = '-' + this.ali2 --i mat = 'V' } else if (this.V[i][j] === this.S[i - 1][j] + this.gap(0)) { this.ali1 = this.seq1[i - 1] + this.ali1 this.ali2 = '-' + this.ali2 --i mat = 'S' } else { // Log.debug('Alignment: V'); --i } } else if (mat === 'H') { if (this.H[i][j] === this.H[i][j - 1] + this.gapExtensionPenalty) { this.ali1 = '-' + this.ali1 this.ali2 = this.seq2[j - 1] + this.ali2 --j mat = 'H' } else if (this.H[i][j] === this.S[i][j - 1] + this.gap(0)) { this.ali1 = '-' + this.ali1 this.ali2 = this.seq2[j - 1] + this.ali2 --j mat = 'S' } else { // Log.debug('Alignment: H'); --j } } else { Log.error('Alignment: no matrix') } } while (i > 0) { this.ali1 = this.seq1[ i - 1 ] + this.ali1 this.ali2 = '-' + this.ali2 --i } while (j > 0) { this.ali1 = '-' + this.ali1 this.ali2 = this.seq2[ j - 1 ] + this.ali2 --j } if (Debug) Log.timeEnd('Alignment.trace') if (Debug) Log.log([this.ali1, this.ali2]) } } export default Alignment
the_stack
import { bulkUISync } from './internal/dispatch'; import app from './app'; import { EventEmitter, IEventMap } from './internal/events'; import globals from './internal/globals'; import { Menu, MenuTypeCode } from './menu'; import { WebView, WebPreferences } from './webview'; const { BrowserWindowNative } = require('./bindings'); const TitleBarStyleCode = { default: 0, hidden: 1, hiddeninset: 2 } as { [index: string]: number }; const vibrancyLayoutAttributes = new Set(['left', 'right', 'top', 'bottom', 'width', 'height']); export type VibrancyMaterial = 'appearance-based' | 'light' | 'dark' | 'medium-light' | 'ultra-dark' | 'titlebar' | 'selection' | 'menu' | 'popover' | 'sidebar' | //10.11+ 'header-view' | 'sheet' | 'window-background' | 'hud-window' | 'full-screen-ui' | 'tool-tip' | 'content-background' | 'under-window-background' | 'under-page-background' //10.14+ export type VibrancyBlendingMode = 'behind-window' | 'within-window'; export type VibrancyState = 'follows-window' | 'active' | 'inactive'; export type TitleBarStyle = 'default' | 'hidden' | 'hiddenInset'; export interface Vibrancy { material?: VibrancyMaterial; blending?: VibrancyBlendingMode; state?: VibrancyState; left?: string | number; right?: string | number; top?: string | number; bottom?: string | number; } export interface IBrowserWindowConstructorOptions { width: number, height: number, x: number, y: number, center: boolean, title: string, icon: string | null, show: boolean, titleBarStyle: TitleBarStyle, maximizable: boolean, minimizable: boolean, resizable: boolean, frame: boolean, closable: boolean, vibrancies: Vibrancy[], vibrancy: VibrancyMaterial, maxHeight: number, maxWidth: number, minHeight: number, minWidth: number, menu: Menu | null, webPreferences: Partial<WebPreferences> }; export interface BrowserWindowEvents extends IEventMap { 'blur': [], 'focus': [], 'resize': [], 'close': [], 'move': [], 'page-title-updated': [string], 'ready-to-show': [], 'closed': [] } export class BrowserWindow extends EventEmitter<BrowserWindowEvents> { /** @internal */ private id_: number; /** @internal */ private hasBeenShown_ = false; /** @internal */ private webview_: WebView; /** @internal */ private native_: any; /** @internal */ private title_: string; /** @internal */ private titleBarStyle_: TitleBarStyle; /** @internal */ private minimumSize_: [number, number]; /** @internal */ private maximumSize_: [number, number]; /** @internal */ private menu_: Menu | null = null; /** @internal */ private menuNativeId_: number | null = null; constructor(options: Partial<IBrowserWindowConstructorOptions> = {}) { super(); let defaultMenu: Menu | null = null; if (process.platform !== 'darwin' && !options.hasOwnProperty('menu')) { defaultMenu = app.getMenu() } const fullOptions: IBrowserWindowConstructorOptions = Object.assign({ width: 800, height: 600, x: 0, y: 0, center: (typeof options.x !== 'number') && (typeof options.y !== 'number'), title: "Untitled Window", icon: null, show: true, titleBarStyle: 'default', maximizable: true, minimizable: true, resizable: true, frame: true, closable: true, vibrancies: null, vibrancy: null, maxHeight: 0, maxWidth: 0, minHeight: 0, minWidth: 0, menu: defaultMenu, webPreferences: { } }, options); bulkUISync(() => { this.webview_ = new WebView({ onPageTitleUpdated: (title: string) => { if (this.isDestroyed()) return; this.trigger_('page-title-updated', { defaultAction: () => this.setTitle(title) }, title); }, onReadyToShow: () => { if (this.isDestroyed()) return; if (!this.hasBeenShown_) { this.trigger_('ready-to-show'); } } }, Object.assign({ engine: null }, fullOptions.webPreferences)); this.native_ = new BrowserWindowNative(this.webview_['native_'], { onBlur: () => { if (this.isDestroyed()) return; if (globals.focusedBrowserWindow === this) { globals.focusedBrowserWindow = null; }; this.trigger_('blur'); }, onFocus: () => { if (this.isDestroyed()) return; globals.focusedBrowserWindow = this; this.trigger_('focus'); }, onResize: () => { if (this.isDestroyed()) return; this.trigger_('resize') }, onMove: () => { if (this.isDestroyed()) return; this.trigger_('move') }, onClose: () => { if (this.isDestroyed()) return; this.trigger_('close', { defaultAction: () => this.destroy() }) } }); this.native_.setMaximizable(fullOptions.maximizable); this.native_.setMinimizable(fullOptions.minimizable); this.native_.setResizable(fullOptions.resizable); this.native_.setHasFrame(fullOptions.frame); this.native_.setClosable(fullOptions.closable); if (process.platform !== 'darwin') { this.setMenu(fullOptions.menu); this.setIcon(fullOptions.icon); } if (process.platform === 'darwin' && fullOptions.frame) { this.setTitleBarStyle(fullOptions.titleBarStyle); } this.setTitle(fullOptions.title); this.setMaximumSize(fullOptions.maxWidth, fullOptions.maxHeight); this.setMinimumSize(fullOptions.minWidth, fullOptions.minHeight); this.setSize(fullOptions.width, fullOptions.height, false); if (fullOptions.center) { this.native_.center(); } else { this.native_.setPosition(fullOptions.x, fullOptions.y,false); } if (process.platform === 'darwin') { if (fullOptions.vibrancies) { this.setVibrancies(fullOptions.vibrancies); } else { this.setVibrancy(fullOptions.vibrancy); } } if (fullOptions.show) { this.show(); } }); this.id_ = this.webview_.id; globals.browserWindowsById.set(this.id_, this); globals.webViewsById.set(this.webview_.id, this.webview_); } get id() { return this.id_; } setTitleBarStyle(style: TitleBarStyle): void { this.titleBarStyle_ = style; this.native_.setTitleBarStyle(TitleBarStyleCode[style.toLowerCase()] || TitleBarStyleCode.default); } show() { if (!this.hasBeenShown_) { if (process.platform !== 'darwin') { this.actuallySetTheMenu_(); } this.hasBeenShown_ = true; } this.native_.show(); } setSize(width: number, height: number, animate: boolean = false) { this.native_.setSize(width, height, animate); } setMaximumSize(width: number, height: number) { this.native_.setMaximumSize(width, height); } setMinimumSize(width: number, height: number) { this.native_.setMinimumSize(width, height); } setVibrancy(material: VibrancyMaterial | null) { if (material != null) { this.setVibrancies([{ material, left: 0, right: 0, top: 0, bottom: 0 }]); } else { this.setVibrancies([]); } } setVibrancies(vibrancies: Vibrancy[]) { this.native_.setVibrancies((vibrancies || []).filter(v => v != null).map(v => [ v.material || 'appearance-based', v.blending || (v.material === 'titlebar' ? 'within-window': 'behind-window'), v.state || 'follows-window', (() => { const layoutEntries = Object.entries(v).filter(entry => vibrancyLayoutAttributes.has(entry[0])); if (layoutEntries.length != 4) { throw new Error("There must be exactly 4 layout attributes in a vibrancy"); } return layoutEntries.map(([key, value]) => { let numValue = value; let isPoint = true; if (typeof value === 'string') { if (value.endsWith('%')) { isPoint = false; value = value.substring(0, value.length - 1); } numValue = parseFloat(value); } return [key, numValue, isPoint]; }) })() ])); } setPosition(x: number, y: number, animate: boolean = false): void { this.native_.setPosition(x, y, animate); } setTitle(title: string): void { this.title_ = title; this.native_.setTitle(title); } getTitle(): string { return this.title_; } center(): void { this.native_.center(); } setMenu(menu: Menu | null) { if (this.menuNativeId_ != null) { bulkUISync(() => { this.menu_!['destroyNative_'](this.menuNativeId_!); }) } this.menu_ = menu; if (this.hasBeenShown_) { this.actuallySetTheMenu_(); } } /** @internal */ private actuallySetTheMenu_() { bulkUISync(() => { if (this.menu_ == null) { this.native_.setMenu(null); this.menuNativeId_ = null; } else { const [menuNativeId, nativeMenu] = this.menu_['createNative_'](MenuTypeCode.main, this); this.native_.setMenu(nativeMenu); this.menuNativeId_ = menuNativeId; } }); } getMenu(): Menu | null { return this.menu_; } setIcon(path: string | null) { this.native_.setIcon(path); } getPosition(): [number, number] { return this.native_.getPosition(); } getSize(): [number, number] { return this.native_.getSize(); } destroy(): void { bulkUISync(() => { if (this.menuNativeId_ != null) { this.menu_!['destroyNative_'](this.menuNativeId_); this.menu_ = null; } this.webview_['native_'].destroy(); this.native_.destroy(); }); this.webview_['native_'] = null; this.native_ = null; if (globals.focusedBrowserWindow === this) { globals.focusedBrowserWindow = null; }; globals.browserWindowsById.delete(this.id_); globals.webViewsById.delete(this.id_); try { this.trigger_('closed'); } finally { this.removeAllListeners(); if (globals.browserWindowsById.size === 0) { app['notifyWindowAllClosed_'](); } } } isDestroyed(): boolean { return this.native_ == null; } minimize(): void { this.native_.minimize(); } close(): void { this.trigger_('close', { defaultAction: () => this.destroy() }); } get webView(): WebView { return this.webview_; } get webContents(): WebView { return this.webView; } loadFile(filePath: string): void { this.webview_.loadFile(filePath); } loadURL(url: string): void { this.webview_.loadURL(url); } reload(): void { this.webview_.reload(); } static getAllWindows(): BrowserWindow[] { return Array.from(globals.browserWindowsById.values()); } static getFocusedWindow(): BrowserWindow | null { return globals.focusedBrowserWindow; } static fromWebView(webview: WebView): BrowserWindow { return globals.browserWindowsById.get(webview.id)!; } static fromWebContents(webview: WebView): BrowserWindow { return this.fromWebView(webview); } static fromId(id: number): BrowserWindow | null { return globals.browserWindowsById.get(id) || null; } }
the_stack
import { OfficeExtension } from "../api-extractor-inputs-office/office" import { Office as Outlook} from "../api-extractor-inputs-outlook/outlook" //////////////////////////////////////////////////////////////// ////////////////////// Begin OneNote APIs ////////////////////// //////////////////////////////////////////////////////////////// export declare namespace OneNote { /** * * Represents the top-level object that contains all globally addressable OneNote objects such as notebooks, the active notebook, and the active section. * * [Api set: OneNoteApi 1.1] */ export class Application extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the collection of notebooks that are open in the OneNote application instance. In OneNote on the web, only one notebook at a time is open in the application instance. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly notebooks: OneNote.NotebookCollection; /** * * Gets the active notebook if one exists. If no notebook is active, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ getActiveNotebook(): OneNote.Notebook; /** * * Gets the active notebook if one exists. If no notebook is active, returns null. * * [Api set: OneNoteApi 1.1] */ getActiveNotebookOrNull(): OneNote.Notebook; /** * * Gets the active outline if one exists, If no outline is active, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ getActiveOutline(): OneNote.Outline; /** * * Gets the active outline if one exists, otherwise returns null. * * [Api set: OneNoteApi 1.1] */ getActiveOutlineOrNull(): OneNote.Outline; /** * * Gets the active page if one exists. If no page is active, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ getActivePage(): OneNote.Page; /** * * Gets the active page if one exists. If no page is active, returns null. * * [Api set: OneNoteApi 1.1] */ getActivePageOrNull(): OneNote.Page; /** * * Gets the active Paragraph if one exists, If no Paragraph is active, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ getActiveParagraph(): OneNote.Paragraph; /** * * Gets the active Paragraph if one exists, otherwise returns null. * * [Api set: OneNoteApi 1.1] */ getActiveParagraphOrNull(): OneNote.Paragraph; /** * * Gets the active section if one exists. If no section is active, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ getActiveSection(): OneNote.Section; /** * * Gets the active section if one exists. If no section is active, returns null. * * [Api set: OneNoteApi 1.1] */ getActiveSectionOrNull(): OneNote.Section; getWindowSize(): OfficeExtension.ClientResult<number[]>; insertHtmlAtCurrentPosition(html: string): void; isViewingDeletedNotes(): OfficeExtension.ClientResult<boolean>; /** * * Opens the specified page in the application instance. * * [Api set: OneNoteApi 1.1] * * @param page - The page to open. */ navigateToPage(page: OneNote.Page): void; /** * * Gets the specified page, and opens it in the application instance. * * [Api set: OneNoteApi 1.1] * * @param url - The client url of the page to open. */ navigateToPageWithClientUrl(url: string): OneNote.Page; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.ApplicationLoadOptions): OneNote.Application; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Application; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Application; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Application object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.ApplicationData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.ApplicationData; } /** * * Represents ink analysis data for a given set of ink strokes. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysis extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the parent page object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly page: OneNote.Page; /** * * Gets the ID of the InkAnalysis object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.InkAnalysis): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.InkAnalysisUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.InkAnalysis): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysis` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysis` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysis` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisLoadOptions): OneNote.InkAnalysis; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysis; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkAnalysis; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysis; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysis; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkAnalysis object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkAnalysisData; } /** * * Represents ink analysis data for an identified paragraph formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisParagraph extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Reference to the parent InkAnalysisPage. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly inkAnalysis: OneNote.InkAnalysis; /** * * Gets the ink analysis lines in this ink analysis paragraph. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly lines: OneNote.InkAnalysisLineCollection; /** * * Gets the ID of the InkAnalysisParagraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.InkAnalysisParagraph): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.InkAnalysisParagraphUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.InkAnalysisParagraph): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisParagraph` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraph` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisParagraph` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisParagraphLoadOptions): OneNote.InkAnalysisParagraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisParagraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraph; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisParagraph; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisParagraph; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkAnalysisParagraph object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisParagraphData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkAnalysisParagraphData; } /** * * Represents a collection of InkAnalysisParagraph objects. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisParagraphCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.InkAnalysisParagraph[]; /** * * Returns the number of InkAnalysisParagraphs in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a InkAnalysisParagraph object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the InkAnalysisParagraph object, or the index location of the InkAnalysisParagraph object in the collection. */ getItem(index: number | string): OneNote.InkAnalysisParagraph; /** * * Gets a InkAnalysisParagraph on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.InkAnalysisParagraph; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisParagraphCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisParagraphCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.InkAnalysisParagraphCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisParagraphCollection; load(option?: OfficeExtension.LoadOption): OneNote.InkAnalysisParagraphCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisParagraphCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisParagraphCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.InkAnalysisParagraphCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisParagraphCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.InkAnalysisParagraphCollectionData; } /** * * Represents ink analysis data for an identified text line formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisLine extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Reference to the parent InkAnalysisParagraph. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraph: OneNote.InkAnalysisParagraph; /** * * Gets the ink analysis words in this ink analysis line. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly words: OneNote.InkAnalysisWordCollection; /** * * Gets the ID of the InkAnalysisLine object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.InkAnalysisLine): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.InkAnalysisLineUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.InkAnalysisLine): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisLine` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLine` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisLine` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisLineLoadOptions): OneNote.InkAnalysisLine; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisLine; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkAnalysisLine; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisLine; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisLine; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkAnalysisLine object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisLineData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkAnalysisLineData; } /** * * Represents a collection of InkAnalysisLine objects. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisLineCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.InkAnalysisLine[]; /** * * Returns the number of InkAnalysisLines in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a InkAnalysisLine object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the InkAnalysisLine object, or the index location of the InkAnalysisLine object in the collection. */ getItem(index: number | string): OneNote.InkAnalysisLine; /** * * Gets a InkAnalysisLine on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.InkAnalysisLine; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisLineCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLineCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisLineCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisLineCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.InkAnalysisLineCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisLineCollection; load(option?: OfficeExtension.LoadOption): OneNote.InkAnalysisLineCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisLineCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisLineCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.InkAnalysisLineCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisLineCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.InkAnalysisLineCollectionData; } /** * * Represents ink analysis data for an identified word formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisWord extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Reference to the parent InkAnalysisLine. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly line: OneNote.InkAnalysisLine; /** * * Gets the ID of the InkAnalysisWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * The id of the recognized language in this inkAnalysisWord. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly languageId: string; /** * * Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly strokePointers: OneNote.InkStrokePointer[]; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly wordAlternates: string[]; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.InkAnalysisWord): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.InkAnalysisWordUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.InkAnalysisWord): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisWord` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWord` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisWord` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisWordLoadOptions): OneNote.InkAnalysisWord; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisWord; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkAnalysisWord; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisWord; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisWord; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkAnalysisWord object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisWordData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkAnalysisWordData; } /** * * Represents a collection of InkAnalysisWord objects. * * [Api set: OneNoteApi 1.1] */ export class InkAnalysisWordCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.InkAnalysisWord[]; /** * * Returns the number of InkAnalysisWords in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a InkAnalysisWord object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the InkAnalysisWord object, or the index location of the InkAnalysisWord object in the collection. */ getItem(index: number | string): OneNote.InkAnalysisWord; /** * * Gets a InkAnalysisWord on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.InkAnalysisWord; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkAnalysisWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWordCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisWordCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkAnalysisWordCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.InkAnalysisWordCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkAnalysisWordCollection; load(option?: OfficeExtension.LoadOption): OneNote.InkAnalysisWordCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkAnalysisWordCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkAnalysisWordCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.InkAnalysisWordCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkAnalysisWordCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.InkAnalysisWordCollectionData; } /** * * Represents a group of ink strokes. * * [Api set: OneNoteApi 1.1] */ export class FloatingInk extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the strokes of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly inkStrokes: OneNote.InkStrokeCollection; /** * * Gets the PageContent parent of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly pageContent: OneNote.PageContent; /** * * Gets the ID of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.FloatingInk` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.FloatingInk` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.FloatingInk` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.FloatingInkLoadOptions): OneNote.FloatingInk; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.FloatingInk; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.FloatingInk; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.FloatingInk; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.FloatingInk; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.FloatingInk object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.FloatingInkData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.FloatingInkData; } /** * * Represents a single stroke of ink. * * [Api set: OneNoteApi 1.1] */ export class InkStroke extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly floatingInk: OneNote.FloatingInk; /** * * Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkStroke` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkStroke` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkStroke` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkStrokeLoadOptions): OneNote.InkStroke; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkStroke; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkStroke; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkStroke; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkStroke; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkStroke object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkStrokeData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkStrokeData; } /** * * Represents a collection of InkStroke objects. * * [Api set: OneNoteApi 1.1] */ export class InkStrokeCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.InkStroke[]; /** * * Returns the number of InkStrokes in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a InkStroke object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the InkStroke object, or the index location of the InkStroke object in the collection. */ getItem(index: number | string): OneNote.InkStroke; /** * * Gets a InkStroke on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.InkStroke; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkStrokeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkStrokeCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkStrokeCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkStrokeCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.InkStrokeCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkStrokeCollection; load(option?: OfficeExtension.LoadOption): OneNote.InkStrokeCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkStrokeCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkStrokeCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.InkStrokeCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkStrokeCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.InkStrokeCollectionData; } /** * * A container for the ink in a word in a paragraph. * * [Api set: OneNoteApi 1.1] */ export class InkWord extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * The parent paragraph containing the ink word. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraph: OneNote.Paragraph; /** * * Gets the ID of the InkWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * The id of the recognized language in this ink word. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly languageId: string; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly wordAlternates: string[]; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkWord` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkWord` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkWord` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkWordLoadOptions): OneNote.InkWord; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkWord; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.InkWord; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkWord; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkWord; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.InkWord object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkWordData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.InkWordData; } /** * * Represents a collection of InkWord objects. * * [Api set: OneNoteApi 1.1] */ export class InkWordCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.InkWord[]; /** * * Returns the number of InkWords in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a InkWord object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the InkWord object, or the index location of the InkWord object in the collection. */ getItem(index: number | string): OneNote.InkWord; /** * * Gets a InkWord on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.InkWord; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.InkWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.InkWordCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkWordCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.InkWordCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.InkWordCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.InkWordCollection; load(option?: OfficeExtension.LoadOption): OneNote.InkWordCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.InkWordCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.InkWordCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.InkWordCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.InkWordCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.InkWordCollectionData; } /** * * Represents a OneNote notebook. Notebooks contain section groups and sections. * * [Api set: OneNoteApi 1.1] */ export class Notebook extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * The section groups in the notebook. Read only * * [Api set: OneNoteApi 1.1] */ readonly sectionGroups: OneNote.SectionGroupCollection; /** * * The the sections of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ readonly sections: OneNote.SectionCollection; /** * * The url of the site that this notebook is located. Read only * * [Api set: OneNoteApi 1.1] */ readonly baseUrl: string; /** * * The client url of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ readonly clientUrl: string; /** * * Gets the ID of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * True if the Notebook is not created by the user (i.e. 'Misplaced Sections'). Read only * * [Api set: OneNoteApi 1.2] */ readonly isVirtual: boolean; /** * * Gets the name of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly name: string; /** * * Adds a new section to the end of the notebook. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the new section. */ addSection(name: string): OneNote.Section; /** * * Adds a new section group to the end of the notebook. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the new section. */ addSectionGroup(name: string): OneNote.SectionGroup; /** * * Gets the REST API ID. * * [Api set: OneNoteApi 1.1] */ getRestApiId(): OfficeExtension.ClientResult<string>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Notebook` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Notebook` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Notebook` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.NotebookLoadOptions): OneNote.Notebook; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Notebook; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Notebook; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Notebook; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Notebook; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Notebook object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.NotebookData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.NotebookData; } /** * * Represents a collection of notebooks. * * [Api set: OneNoteApi 1.1] */ export class NotebookCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.Notebook[]; /** * * Returns the number of notebooks in the collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets the collection of notebooks with the specified name that are open in the application instance. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the notebook. */ getByName(name: string): OneNote.NotebookCollection; /** * * Gets a notebook by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the notebook, or the index location of the notebook in the collection. */ getItem(index: number | string): OneNote.Notebook; /** * * Gets a notebook on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.Notebook; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.NotebookCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.NotebookCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.NotebookCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.NotebookCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.NotebookCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.NotebookCollection; load(option?: OfficeExtension.LoadOption): OneNote.NotebookCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.NotebookCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.NotebookCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.NotebookCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.NotebookCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.NotebookCollectionData; } /** * * Represents a OneNote section group. Section groups can contain sections and other section groups. * * [Api set: OneNoteApi 1.1] */ export class SectionGroup extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the notebook that contains the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly notebook: OneNote.Notebook; /** * * Gets the section group that contains the section group. Throws ItemNotFound if the section group is a direct child of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentSectionGroup: OneNote.SectionGroup; /** * * Gets the section group that contains the section group. Returns null if the section group is a direct child of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentSectionGroupOrNull: OneNote.SectionGroup; /** * * The collection of section groups in the section group. Read only * * [Api set: OneNoteApi 1.1] */ readonly sectionGroups: OneNote.SectionGroupCollection; /** * * The collection of sections in the section group. Read only * * [Api set: OneNoteApi 1.1] */ readonly sections: OneNote.SectionCollection; /** * * The client url of the section group. Read only * * [Api set: OneNoteApi 1.1] */ readonly clientUrl: string; /** * * Gets the ID of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the name of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly name: string; /** * * Adds a new section to the end of the section group. * * [Api set: OneNoteApi 1.1] * * @param title - The name of the new section. */ addSection(title: string): OneNote.Section; /** * * Adds a new section group to the end of this sectionGroup. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the new section. */ addSectionGroup(name: string): OneNote.SectionGroup; /** * * Gets the REST API ID. * * [Api set: OneNoteApi 1.1] */ getRestApiId(): OfficeExtension.ClientResult<string>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.SectionGroup` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroup` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionGroup` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.SectionGroupLoadOptions): OneNote.SectionGroup; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.SectionGroup; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.SectionGroup; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.SectionGroup; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.SectionGroup; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.SectionGroup object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.SectionGroupData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.SectionGroupData; } /** * * Represents a collection of section groups. * * [Api set: OneNoteApi 1.1] */ export class SectionGroupCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.SectionGroup[]; /** * * Returns the number of section groups in the collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets the collection of section groups with the specified name. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the section group. */ getByName(name: string): OneNote.SectionGroupCollection; /** * * Gets a section group by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the section group, or the index location of the section group in the collection. */ getItem(index: number | string): OneNote.SectionGroup; /** * * Gets a section group on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.SectionGroup; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.SectionGroupCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroupCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionGroupCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.SectionGroupCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.SectionGroupCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.SectionGroupCollection; load(option?: OfficeExtension.LoadOption): OneNote.SectionGroupCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.SectionGroupCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.SectionGroupCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.SectionGroupCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.SectionGroupCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.SectionGroupCollectionData; } /** * * Represents a OneNote section. Sections can contain pages. * * [Api set: OneNoteApi 1.1] */ export class Section extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the notebook that contains the section. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly notebook: OneNote.Notebook; /** * * The collection of pages in the section. Read only * * [Api set: OneNoteApi 1.1] */ readonly pages: OneNote.PageCollection; /** * * Gets the section group that contains the section. Throws ItemNotFound if the section is a direct child of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentSectionGroup: OneNote.SectionGroup; /** * * Gets the section group that contains the section. Returns null if the section is a direct child of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentSectionGroupOrNull: OneNote.SectionGroup; /** * * The client url of the section. Read only * * [Api set: OneNoteApi 1.1] */ readonly clientUrl: string; /** * * Gets the ID of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * True if this section is encrypted with a password. Read only * * [Api set: OneNoteApi 1.2] */ readonly isEncrypted: boolean; /** * * True if this section is locked. Read only * * [Api set: OneNoteApi 1.2] */ readonly isLocked: boolean; /** * * Gets the name of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly name: string; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ readonly webUrl: string; /** * * Adds a new page to the end of the section. * * [Api set: OneNoteApi 1.1] * * @param title - The title of the new page. */ addPage(title: string): OneNote.Page; /** * * Copies this section to specified notebook. * * [Api set: OneNoteApi 1.1] * * @param destinationNotebook - The notebook to copy this section to. */ copyToNotebook(destinationNotebook: OneNote.Notebook): OneNote.Section; /** * * Copies this section to specified section group. * * [Api set: OneNoteApi 1.1] * * @param destinationSectionGroup - The section group to copy this section to. */ copyToSectionGroup(destinationSectionGroup: OneNote.SectionGroup): OneNote.Section; /** * * Gets the REST API ID. * * [Api set: OneNoteApi 1.1] */ getRestApiId(): OfficeExtension.ClientResult<string>; /** * * Inserts a new section before or after the current section. * * [Api set: OneNoteApi 1.1] * * @param location - The location of the new section relative to the current section. * @param title - The name of the new section. */ insertSectionAsSibling(location: OneNote.InsertLocation, title: string): OneNote.Section; /** * * Inserts a new section before or after the current section. * * [Api set: OneNoteApi 1.1] * * @param locationString - The location of the new section relative to the current section. * @param title - The name of the new section. */ insertSectionAsSibling(locationString: "Before" | "After", title: string): OneNote.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Section` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Section` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Section` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.SectionLoadOptions): OneNote.Section; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Section; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Section; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Section; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Section; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Section object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.SectionData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.SectionData; } /** * * Represents a collection of sections. * * [Api set: OneNoteApi 1.1] */ export class SectionCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.Section[]; /** * * Returns the number of sections in the collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets the collection of sections with the specified name. * * [Api set: OneNoteApi 1.1] * * @param name - The name of the section. */ getByName(name: string): OneNote.SectionCollection; /** * * Gets a section by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the section, or the index location of the section in the collection. */ getItem(index: number | string): OneNote.Section; /** * * Gets a section on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.SectionCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.SectionCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.SectionCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.SectionCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.SectionCollection; load(option?: OfficeExtension.LoadOption): OneNote.SectionCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.SectionCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.SectionCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.SectionCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.SectionCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.SectionCollectionData; } /** * * Represents a OneNote page. * * [Api set: OneNoteApi 1.1] */ export class Page extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * The collection of PageContent objects on the page. Read only * * [Api set: OneNoteApi 1.1] */ readonly contents: OneNote.PageContentCollection; /** * * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. * * [Api set: OneNoteApi 1.1] */ readonly inkAnalysisOrNull: OneNote.InkAnalysis; /** * * Gets the section that contains the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentSection: OneNote.Section; /** * * Gets the ClassNotebookPageSource to the page. * * [Api set: OneNoteApi 1.1] */ readonly classNotebookPageSource: string; /** * * The client url of the page. Read only * * [Api set: OneNoteApi 1.1] */ readonly clientUrl: string; /** * * Gets the ID of the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets or sets the indentation level of the page. * * [Api set: OneNoteApi 1.1] */ pageLevel: number; /** * * Gets or sets the title of the page. * * [Api set: OneNoteApi 1.1] */ title: string; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ readonly webUrl: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.Page): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.PageUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.Page): void; /** * * Adds an Outline to the page at the specified position. * * [Api set: OneNoteApi 1.1] * * @param left - The left position of the top, left corner of the Outline. * @param top - The top position of the top, left corner of the Outline. * @param html - An HTML string that describes the visual presentation of the Outline. See {@link https://docs.microsoft.com/office/dev/add-ins/onenote/onenote-add-ins-page-content#supported-html | Supported HTML} for the OneNote add-ins JavaScript API. */ addOutline(left: number, top: number, html: string): OneNote.Outline; /** * * Return a json string with node id and content in html format. * * [Api set: OneNoteApi 1.1] */ analyzePage(): OfficeExtension.ClientResult<string>; /** * * Inserts a new page with translated content. * * [Api set: OneNoteApi 1.1] * * @param translatedContent - Translated content of the page */ applyTranslation(translatedContent: string): void; /** * * Copies this page to specified section. * * [Api set: OneNoteApi 1.1] * * @param destinationSection - The section to copy this page to. */ copyToSection(destinationSection: OneNote.Section): OneNote.Page; /** * * Copies this page to specified section and sets ClassNotebookPageSource. * * [Api set: OneNoteApi 1.1] */ copyToSectionAndSetClassNotebookPageSource(destinationSection: OneNote.Section): OneNote.Page; /** * * Gets the REST API ID. * * [Api set: OneNoteApi 1.1] */ getRestApiId(): OfficeExtension.ClientResult<string>; /** * * Does the page has content title. * * [Api set: OneNoteApi 1.1] */ hasTitleContent(): OfficeExtension.ClientResult<boolean>; /** * * Inserts a new page before or after the current page. * * [Api set: OneNoteApi 1.1] * * @param location - The location of the new page relative to the current page. * @param title - The title of the new page. */ insertPageAsSibling(location: OneNote.InsertLocation, title: string): OneNote.Page; /** * * Inserts a new page before or after the current page. * * [Api set: OneNoteApi 1.1] * * @param locationString - The location of the new page relative to the current page. * @param title - The title of the new page. */ insertPageAsSibling(locationString: "Before" | "After", title: string): OneNote.Page; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Page` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Page` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Page` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.PageLoadOptions): OneNote.Page; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Page; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Page; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Page; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Page; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Page object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.PageData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.PageData; } /** * * Represents a collection of pages. * * [Api set: OneNoteApi 1.1] */ export class PageCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.Page[]; /** * * Returns the number of pages in the collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets the collection of pages with the specified title. * * [Api set: OneNoteApi 1.1] * * @param title - The title of the page. */ getByTitle(title: string): OneNote.PageCollection; /** * * Gets a page by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the page, or the index location of the page in the collection. */ getItem(index: number | string): OneNote.Page; /** * * Gets a page on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.Page; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.PageCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.PageCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.PageCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.PageCollection; load(option?: OfficeExtension.LoadOption): OneNote.PageCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.PageCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.PageCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.PageCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.PageCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.PageCollectionData; } /** * * Represents a region on a page that contains top-level content types such as Outline or Image. A PageContent object can be assigned an XY position. * * [Api set: OneNoteApi 1.1] */ export class PageContent extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. * * [Api set: OneNoteApi 1.1] */ readonly image: OneNote.Image; /** * * Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. * * [Api set: OneNoteApi 1.1] */ readonly ink: OneNote.FloatingInk; /** * * Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. * * [Api set: OneNoteApi 1.1] */ readonly outline: OneNote.Outline; /** * * Gets the page that contains the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentPage: OneNote.Page; /** * * Gets the ID of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets or sets the left (X-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ left: number; /** * * Gets or sets the top (Y-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ top: number; /** * * Gets the type of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly type: OneNote.PageContentType | "Outline" | "Image" | "Ink" | "Other"; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.PageContent): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.PageContentUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.PageContent): void; /** * * Deletes the PageContent object. * * [Api set: OneNoteApi 1.1] */ delete(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.PageContent` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.PageContent` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageContent` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.PageContentLoadOptions): OneNote.PageContent; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.PageContent; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.PageContent; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.PageContent; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.PageContent; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.PageContent object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.PageContentData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.PageContentData; } /** * * Represents the contents of a page, as a collection of PageContent objects. * * [Api set: OneNoteApi 1.1] */ export class PageContentCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.PageContent[]; /** * * Returns the number of page contents in the collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a PageContent object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the PageContent object, or the index location of the PageContent object in the collection. */ getItem(index: number | string): OneNote.PageContent; /** * * Gets a page content on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.PageContent; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.PageContentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.PageContentCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageContentCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.PageContentCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.PageContentCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.PageContentCollection; load(option?: OfficeExtension.LoadOption): OneNote.PageContentCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.PageContentCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.PageContentCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.PageContentCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.PageContentCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.PageContentCollectionData; } /** * * Represents a container for Paragraph objects. * * [Api set: OneNoteApi 1.1] */ export class Outline extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the PageContent object that contains the Outline. This object defines the position of the Outline on the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly pageContent: OneNote.PageContent; /** * * Gets the collection of Paragraph objects in the Outline. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraphs: OneNote.ParagraphCollection; /** * * Gets the ID of the Outline object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Adds the specified HTML to the bottom of the Outline. * * [Api set: OneNoteApi 1.1] * * @param html - The HTML string to append. See {@link https://docs.microsoft.com/office/dev/add-ins/onenote/onenote-add-ins-page-content#supported-html | Supported HTML} for the OneNote add-ins JavaScript API. */ appendHtml(html: string): void; /** * * Adds the specified image to the bottom of the Outline. * * [Api set: OneNoteApi 1.1] * * @param base64EncodedImage - HTML string to append. * @param width - Optional. Width in the unit of Points. The default value is null and image width will be respected. * @param height - Optional. Height in the unit of Points. The default value is null and image height will be respected. */ appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; /** * * Adds the specified text to the bottom of the Outline. * * [Api set: OneNoteApi 1.1] * * @param paragraphText - HTML string to append. */ appendRichText(paragraphText: string): OneNote.RichText; /** * * Adds a table with the specified number of rows and columns to the bottom of the outline. * * [Api set: OneNoteApi 1.1] * * @param rowCount - Required. The number of rows in the table. * @param columnCount - Required. The number of columns in the table. * @param values - Optional 2D array. Cells are filled if the corresponding strings are specified in the array. */ appendTable(rowCount: number, columnCount: number, values?: string[][]): OneNote.Table; /** * * Check if the outline is title outline. * * [Api set: OneNoteApi 1.1] */ isTitle(): OfficeExtension.ClientResult<boolean>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Outline` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Outline` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Outline` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.OutlineLoadOptions): OneNote.Outline; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Outline; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Outline; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Outline; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Outline; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Outline object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.OutlineData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.OutlineData; } /** * * A container for the visible content on a page. A Paragraph can contain any one ParagraphType type of content. * * [Api set: OneNoteApi 1.1] */ export class Paragraph extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly image: OneNote.Image; /** * * Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly inkWords: OneNote.InkWordCollection; /** * * Gets the Outline object that contains the Paragraph. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly outline: OneNote.Outline; /** * * The collection of paragraphs under this paragraph. Read only * * [Api set: OneNoteApi 1.1] */ readonly paragraphs: OneNote.ParagraphCollection; /** * * Gets the parent paragraph object. Throws if a parent paragraph does not exist. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentParagraph: OneNote.Paragraph; /** * * Gets the parent paragraph object. Returns null if a parent paragraph does not exist. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentParagraphOrNull: OneNote.Paragraph; /** * * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, throws ItemNotFound. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentTableCell: OneNote.TableCell; /** * * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, returns null. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentTableCellOrNull: OneNote.TableCell; /** * * Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. Read-only * * [Api set: OneNoteApi 1.1] */ readonly richText: OneNote.RichText; /** * * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly table: OneNote.Table; /** * * Gets the ID of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the type of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly type: OneNote.ParagraphType | "RichText" | "Image" | "Table" | "Ink" | "Other"; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.Paragraph): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ParagraphUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.Paragraph): void; /** * * Add NoteTag to the paragraph. * * [Api set: OneNoteApi 1.1] * * @param type - The type of the NoteTag. * @param status - The status of the NoteTag. */ addNoteTag(type: OneNote.NoteTagType, status: OneNote.NoteTagStatus): OneNote.NoteTag; /** * * Add NoteTag to the paragraph. * * [Api set: OneNoteApi 1.1] * * @param typeString - The type of the NoteTag. * @param status - The status of the NoteTag. */ addNoteTag(typeString: "Unknown" | "ToDo" | "Important" | "Question" | "Contact" | "Address" | "PhoneNumber" | "Website" | "Idea" | "Critical" | "ToDoPriority1" | "ToDoPriority2", status: "Unknown" | "Normal" | "Completed" | "Disabled" | "OutlookTask" | "TaskNotSyncedYet" | "TaskRemoved"): OneNote.NoteTag; /** * * Deletes the paragraph * * [Api set: OneNoteApi 1.1] */ delete(): void; /** * * Get list information of paragraph * * [Api set: OneNoteApi 1.1] */ getParagraphInfo(): OfficeExtension.ClientResult<OneNote.ParagraphInfo>; /** * * Inserts the specified HTML content * * [Api set: OneNoteApi 1.1] * * @param insertLocation - The location of new contents relative to the current Paragraph. * @param html - An HTML string that describes the visual presentation of the content. See {@link https://docs.microsoft.com/office/dev/add-ins/onenote/onenote-add-ins-page-content#supported-html | Supported HTML} for the OneNote add-ins JavaScript API. */ insertHtmlAsSibling(insertLocation: OneNote.InsertLocation, html: string): void; /** * * Inserts the specified HTML content * * [Api set: OneNoteApi 1.1] * * @param insertLocationString - The location of new contents relative to the current Paragraph. * @param html - An HTML string that describes the visual presentation of the content. See {@link https://docs.microsoft.com/office/dev/add-ins/onenote/onenote-add-ins-page-content#supported-html | Supported HTML} for the OneNote add-ins JavaScript API. */ insertHtmlAsSibling(insertLocationString: "Before" | "After", html: string): void; /** * * Inserts the image at the specified insert location.. * * [Api set: OneNoteApi 1.1] * * @param insertLocation - The location of the table relative to the current Paragraph. * @param base64EncodedImage - HTML string to append. * @param width - Optional. Width in the unit of Points. The default value is null and image width will be respected. * @param height - Optional. Height in the unit of Points. The default value is null and image height will be respected. */ insertImageAsSibling(insertLocation: OneNote.InsertLocation, base64EncodedImage: string, width: number, height: number): OneNote.Image; /** * * Inserts the image at the specified insert location.. * * [Api set: OneNoteApi 1.1] * * @param insertLocationString - The location of the table relative to the current Paragraph. * @param base64EncodedImage - HTML string to append. * @param width - Optional. Width in the unit of Points. The default value is null and image width will be respected. * @param height - Optional. Height in the unit of Points. The default value is null and image height will be respected. */ insertImageAsSibling(insertLocationString: "Before" | "After", base64EncodedImage: string, width: number, height: number): OneNote.Image; /** * * Inserts the paragraph text at the specifiec insert location. * * [Api set: OneNoteApi 1.1] * * @param insertLocation - The location of the table relative to the current Paragraph. * @param paragraphText - HTML string to append. */ insertRichTextAsSibling(insertLocation: OneNote.InsertLocation, paragraphText: string): OneNote.RichText; /** * * Inserts the paragraph text at the specifiec insert location. * * [Api set: OneNoteApi 1.1] * * @param insertLocationString - The location of the table relative to the current Paragraph. * @param paragraphText - HTML string to append. */ insertRichTextAsSibling(insertLocationString: "Before" | "After", paragraphText: string): OneNote.RichText; /** * * Adds a table with the specified number of rows and columns before or after the current paragraph. * * [Api set: OneNoteApi 1.1] * * @param insertLocation - The location of the table relative to the current Paragraph. * @param rowCount - The number of rows in the table. * @param columnCount - The number of columns in the table. * @param values - Optional 2D array. Cells are filled if the corresponding strings are specified in the array. */ insertTableAsSibling(insertLocation: OneNote.InsertLocation, rowCount: number, columnCount: number, values?: string[][]): OneNote.Table; /** * * Adds a table with the specified number of rows and columns before or after the current paragraph. * * [Api set: OneNoteApi 1.1] * * @param insertLocationString - The location of the table relative to the current Paragraph. * @param rowCount - The number of rows in the table. * @param columnCount - The number of columns in the table. * @param values - Optional 2D array. Cells are filled if the corresponding strings are specified in the array. */ insertTableAsSibling(insertLocationString: "Before" | "After", rowCount: number, columnCount: number, values?: string[][]): OneNote.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Paragraph` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Paragraph` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Paragraph` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.ParagraphLoadOptions): OneNote.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Paragraph; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Paragraph; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Paragraph; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Paragraph object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.ParagraphData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.ParagraphData; } /** * * Represents a collection of Paragraph objects. * * [Api set: OneNoteApi 1.1] */ export class ParagraphCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.Paragraph[]; /** * * Returns the number of paragraphs in the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a Paragraph object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - The ID of the Paragraph object, or the index location of the Paragraph object in the collection. */ getItem(index: number | string): OneNote.Paragraph; /** * * Gets a paragraph on its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.ParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.ParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.ParagraphCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.ParagraphCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.ParagraphCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.ParagraphCollection; load(option?: OfficeExtension.LoadOption): OneNote.ParagraphCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.ParagraphCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.ParagraphCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.ParagraphCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.ParagraphCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.ParagraphCollectionData; } /** * * A container for the NoteTag in a paragraph. * * [Api set: OneNoteApi 1.1] */ export class NoteTag extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Id of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the status of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly status: OneNote.NoteTagStatus | "Unknown" | "Normal" | "Completed" | "Disabled" | "OutlookTask" | "TaskNotSyncedYet" | "TaskRemoved"; /** * * Gets the type of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly type: OneNote.NoteTagType | "Unknown" | "ToDo" | "Important" | "Question" | "Contact" | "Address" | "PhoneNumber" | "Website" | "Idea" | "Critical" | "ToDoPriority1" | "ToDoPriority2"; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.NoteTag` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.NoteTag` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.NoteTag` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.NoteTagLoadOptions): OneNote.NoteTag; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.NoteTag; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.NoteTag; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.NoteTag; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.NoteTag; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.NoteTag object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.NoteTagData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.NoteTagData; } /** * * Represents a RichText object in a Paragraph. * * [Api set: OneNoteApi 1.1] */ export class RichText extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Paragraph object that contains the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraph: OneNote.Paragraph; /** * * Gets the ID of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * The language id of the text. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly languageId: string; /** * * Gets the text content of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly text: string; /** * * Get the HTML of the rich text * * [Api set: OneNoteApi 1.1] * @returns The html of the rich text */ getHtml(): OfficeExtension.ClientResult<string>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.RichText` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.RichText` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.RichText` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.RichTextLoadOptions): OneNote.RichText; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.RichText; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.RichText; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.RichText; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.RichText; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.RichText object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.RichTextData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.RichTextData; } /** * * Represents an Image. An Image can be a direct child of a PageContent object or a Paragraph object. * * [Api set: OneNoteApi 1.1] */ export class Image extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the PageContent object that contains the Image. Throws if the Image is not a direct child of a PageContent. This object defines the position of the Image on the page. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly pageContent: OneNote.PageContent; /** * * Gets the Paragraph object that contains the Image. Throws if the Image is not a direct child of a Paragraph. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraph: OneNote.Paragraph; /** * * Gets or sets the description of the Image. * * [Api set: OneNoteApi 1.1] */ description: string; /** * * Gets or sets the height of the Image layout. * * [Api set: OneNoteApi 1.1] */ height: number; /** * * Gets or sets the hyperlink of the Image. * * [Api set: OneNoteApi 1.1] */ hyperlink: string; /** * * Gets the ID of the Image object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the data obtained by OCR (Optical Character Recognition) of this Image, such as OCR text and language. * * [Api set: OneNoteApi 1.1] */ readonly ocrData: OneNote.ImageOcrData; /** * * Gets or sets the width of the Image layout. * * [Api set: OneNoteApi 1.1] */ width: number; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.Image): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ImageUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.Image): void; /** * * Gets the base64-encoded binary representation of the Image. Example: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA... * * [Api set: OneNoteApi 1.1] */ getBase64Image(): OfficeExtension.ClientResult<string>; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Image` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Image` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Image` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.ImageLoadOptions): OneNote.Image; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Image; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Image; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Image; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Image; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Image object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.ImageData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.ImageData; } /** * * Represents a table in a OneNote page. * * [Api set: OneNoteApi 1.1] */ export class Table extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the Paragraph object that contains the Table object. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraph: OneNote.Paragraph; /** * * Gets all of the table rows. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly rows: OneNote.TableRowCollection; /** * * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. * * [Api set: OneNoteApi 1.1] */ borderVisible: boolean; /** * * Gets the number of columns in the table. * * [Api set: OneNoteApi 1.1] */ readonly columnCount: number; /** * * Gets the ID of the table. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the number of rows in the table. * * [Api set: OneNoteApi 1.1] */ readonly rowCount: number; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.Table): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.TableUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.Table): void; /** * * Adds a column to the end of the table. Values, if specified, are set in the new column. Otherwise the column is empty. * * [Api set: OneNoteApi 1.1] * * @param values - Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. */ appendColumn(values?: string[]): void; /** * * Adds a row to the end of the table. Values, if specified, are set in the new row. Otherwise the row is empty. * * [Api set: OneNoteApi 1.1] * * @param values - Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. */ appendRow(values?: string[]): OneNote.TableRow; /** * * Clears the contents of the table. * * [Api set: OneNoteApi 1.1] */ clear(): void; /** * * Gets the table cell at a specified row and column. * * [Api set: OneNoteApi 1.1] * * @param rowIndex - The index of the row. * @param cellIndex - The index of the cell in the row. */ getCell(rowIndex: number, cellIndex: number): OneNote.TableCell; /** * * Inserts a column at the given index in the table. Values, if specified, are set in the new column. Otherwise the column is empty. * * [Api set: OneNoteApi 1.1] * * @param index - Index where the column will be inserted in the table. * @param values - Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. */ insertColumn(index: number, values?: string[]): void; /** * * Inserts a row at the given index in the table. Values, if specified, are set in the new row. Otherwise the row is empty. * * [Api set: OneNoteApi 1.1] * * @param index - Index where the row will be inserted in the table. * @param values - Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. */ insertRow(index: number, values?: string[]): OneNote.TableRow; /** * * Sets the shading color of all cells in the table. The color code to set the cells to. * * [Api set: OneNoteApi 1.1] */ setShadingColor(colorCode: string): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.Table` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.Table` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Table` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.TableLoadOptions): OneNote.Table; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.Table; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.Table; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.Table; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.Table; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.Table object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.TableData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.TableData; } /** * * Represents a row in a table. * * [Api set: OneNoteApi 1.1] */ export class TableRow extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly cells: OneNote.TableCellCollection; /** * * Gets the parent table. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentTable: OneNote.Table; /** * * Gets the number of cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly cellCount: number; /** * * Gets the ID of the row. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the index of the row in its parent table. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly rowIndex: number; /** * * Clears the contents of the row. * * [Api set: OneNoteApi 1.1] */ clear(): void; /** * * Inserts a row before or after the current row. * * [Api set: OneNoteApi 1.1] * * @param insertLocation - Where the new rows should be inserted relative to the current row. * @param values - Strings to insert in the new row, specified as an array. Must not have more cells than in the current row. Optional. */ insertRowAsSibling(insertLocation: OneNote.InsertLocation, values?: string[]): OneNote.TableRow; /** * * Inserts a row before or after the current row. * * [Api set: OneNoteApi 1.1] * * @param insertLocationString - Where the new rows should be inserted relative to the current row. * @param values - Strings to insert in the new row, specified as an array. Must not have more cells than in the current row. Optional. */ insertRowAsSibling(insertLocationString: "Before" | "After", values?: string[]): OneNote.TableRow; /** * * Sets the shading color of all cells in the row. The color code to set the cells to. * * [Api set: OneNoteApi 1.1] */ setShadingColor(colorCode: string): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.TableRow` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableRow` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.TableRowLoadOptions): OneNote.TableRow; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.TableRow; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.TableRow; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.TableRow; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.TableRow; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.TableRow object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.TableRowData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.TableRowData; } /** * * Contains a collection of TableRow objects. * * [Api set: OneNoteApi 1.1] */ export class TableRowCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.TableRow[]; /** * * Returns the number of table rows in this collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a table row object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - A number that identifies the index location of a table row object. */ getItem(index: number | string): OneNote.TableRow; /** * * Gets a table row at its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.TableRow; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableRowCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.TableRowCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.TableRowCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.TableRowCollection; load(option?: OfficeExtension.LoadOption): OneNote.TableRowCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.TableRowCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.TableRowCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.TableRowCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.TableRowCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.TableRowCollectionData; } /** * * Represents a cell in a OneNote table. * * [Api set: OneNoteApi 1.1] */ export class TableCell extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * * Gets the collection of Paragraph objects in the TableCell. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly paragraphs: OneNote.ParagraphCollection; /** * * Gets the parent row of the cell. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly parentRow: OneNote.TableRow; /** * * Gets the index of the cell in its row. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly cellIndex: number; /** * * Gets the ID of the cell. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly id: string; /** * * Gets the index of the cell's row in the table. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly rowIndex: number; /** * * Gets and sets the shading color of the cell * * [Api set: OneNoteApi 1.1] */ shadingColor: string; /** Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * * @remarks * * This method has the following additional signature: * * `set(properties: OneNote.TableCell): void` * * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.TableCellUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: OneNote.TableCell): void; /** * * Adds the specified HTML to the bottom of the TableCell. * * [Api set: OneNoteApi 1.1] * * @param html - The HTML string to append. See {@link https://docs.microsoft.com/office/dev/add-ins/onenote/onenote-add-ins-page-content#supported-html | Supported HTML} for the OneNote add-ins JavaScript API. */ appendHtml(html: string): void; /** * * Adds the specified image to table cell. * * [Api set: OneNoteApi 1.1] * * @param base64EncodedImage - HTML string to append. * @param width - Optional. Width in the unit of Points. The default value is null and image width will be respected. * @param height - Optional. Height in the unit of Points. The default value is null and image height will be respected. */ appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; /** * * Adds the specified text to table cell. * * [Api set: OneNoteApi 1.1] * * @param paragraphText - HTML string to append. */ appendRichText(paragraphText: string): OneNote.RichText; /** * * Adds a table with the specified number of rows and columns to table cell. * * [Api set: OneNoteApi 1.1] * * @param rowCount - Required. The number of rows in the table. * @param columnCount - Required. The number of columns in the table. * @param values - Optional 2D array. Cells are filled if the corresponding strings are specified in the array. */ appendTable(rowCount: number, columnCount: number, values?: string[][]): OneNote.Table; /** * * Clears the contents of the cell. * * [Api set: OneNoteApi 1.1] */ clear(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.TableCell` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.TableCell` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableCell` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.TableCellLoadOptions): OneNote.TableCell; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.TableCell; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNamesAndPaths - Where propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): OneNote.TableCell; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.TableCell; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.TableCell; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original OneNote.TableCell object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.TableCellData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): OneNote.Interfaces.TableCellData; } /** * * Contains a collection of TableCell objects. * * [Api set: OneNoteApi 1.1] */ export class TableCellCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: OneNote.TableCell[]; /** * * Returns the number of tablecells in this collection. Read-only. * * [Api set: OneNoteApi 1.1] */ readonly count: number; /** * * Gets a table cell object by ID or by its index in the collection. Read-only. * * [Api set: OneNoteApi 1.1] * * @param index - A number that identifies the index location of a table cell object. */ getItem(index: number | string): OneNote.TableCell; /** * * Gets a tablecell at its position in the collection. * * [Api set: OneNoteApi 1.1] * * @param index - Index value of the object to be retrieved. Zero-indexed. */ getItemAt(index: number): OneNote.TableCell; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * * @remarks * * In addition to this signature, this method has the following signatures: * * `load(option?: string | string[]): OneNote.TableCellCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * * `load(option?: { select?: string; expand?: string; }): OneNote.TableCellCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableCellCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * * @param options - Provides options for which properties of the object to load. */ load(option?: OneNote.Interfaces.TableCellCollectionLoadOptions & OneNote.Interfaces.CollectionLoadOptions): OneNote.TableCellCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): OneNote.TableCellCollection; load(option?: OfficeExtension.LoadOption): OneNote.TableCellCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): OneNote.TableCellCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): OneNote.TableCellCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `OneNote.TableCellCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `OneNote.Interfaces.TableCellCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): OneNote.Interfaces.TableCellCollectionData; } /** * * Represents data obtained by OCR (optical character recognition) of an image. * * [Api set: OneNoteApi 1.1] */ export interface ImageOcrData { /** * * Represents the OCR language, with values such as EN-US * * [Api set: OneNoteApi 1.1] */ ocrLanguageId: string; /** * * Represents the text obtained by OCR of the image * * [Api set: OneNoteApi 1.1] */ ocrText: string; } /** * * Weak reference to an ink stroke object and its content parent. * * [Api set: OneNoteApi 1.1] */ export interface InkStrokePointer { /** * * Represents the id of the page content object corresponding to this stroke * * [Api set: OneNoteApi 1.1] */ contentId: string; /** * * Represents the id of the ink stroke * * [Api set: OneNoteApi 1.1] */ inkStrokeId: string; } /** * * List information for paragraph. * * [Api set: OneNoteApi 1.1] */ export interface ParagraphInfo { /** * * // Bullet list type of paragraph * * [Api set: OneNoteApi 1.1] */ bulletType: string; /** * * // Index of paragraph in list * * [Api set: OneNoteApi 1.1] */ index: number; /** * * // Type of list in paragraph * * [Api set: OneNoteApi 1.1] */ listType: OneNote.ListType | "None" | "Number" | "Bullet"; /** * * // number list type of paragraph * * [Api set: OneNoteApi 1.1] */ numberType: OneNote.NumberType | "None" | "Arabic" | "UCRoman" | "LCRoman" | "UCLetter" | "LCLetter" | "Ordinal" | "Cardtext" | "Ordtext" | "Hex" | "ChiManSty" | "DbNum1" | "DbNum2" | "Aiueo" | "Iroha" | "DbChar" | "SbChar" | "DbNum3" | "DbNum4" | "Circlenum" | "DArabic" | "DAiueo" | "DIroha" | "ArabicLZ" | "Bullet" | "Ganada" | "Chosung" | "GB1" | "GB2" | "GB3" | "GB4" | "Zodiac1" | "Zodiac2" | "Zodiac3" | "TpeDbNum1" | "TpeDbNum2" | "TpeDbNum3" | "TpeDbNum4" | "ChnDbNum1" | "ChnDbNum2" | "ChnDbNum3" | "ChnDbNum4" | "KorDbNum1" | "KorDbNum2" | "KorDbNum3" | "KorDbNum4" | "Hebrew1" | "Arabic1" | "Hebrew2" | "Arabic2" | "Hindi1" | "Hindi2" | "Hindi3" | "Thai1" | "Thai2" | "NumInDash" | "LCRus" | "UCRus" | "LCGreek" | "UCGreek" | "Lim" | "Custom"; } /** * [Api set: OneNoteApi 1.1] */ enum InsertLocation { before = "Before", after = "After", } /** * [Api set: OneNoteApi 1.1] */ enum PageContentType { outline = "Outline", image = "Image", ink = "Ink", other = "Other", } /** * [Api set: OneNoteApi 1.1] */ enum ParagraphType { richText = "RichText", image = "Image", table = "Table", ink = "Ink", other = "Other", } /** * [Api set: OneNoteApi 1.1] */ enum NoteTagType { unknown = "Unknown", toDo = "ToDo", important = "Important", question = "Question", contact = "Contact", address = "Address", phoneNumber = "PhoneNumber", website = "Website", idea = "Idea", critical = "Critical", toDoPriority1 = "ToDoPriority1", toDoPriority2 = "ToDoPriority2", } /** * [Api set: OneNoteApi 1.1] */ enum NoteTagStatus { unknown = "Unknown", normal = "Normal", completed = "Completed", disabled = "Disabled", outlookTask = "OutlookTask", taskNotSyncedYet = "TaskNotSyncedYet", taskRemoved = "TaskRemoved", } /** * [Api set: OneNoteApi 1.1] */ enum ListType { none = "None", number = "Number", bullet = "Bullet", } /** * [Api set: OneNoteApi 1.1] */ enum NumberType { none = "None", arabic = "Arabic", ucroman = "UCRoman", lcroman = "LCRoman", ucletter = "UCLetter", lcletter = "LCLetter", ordinal = "Ordinal", cardtext = "Cardtext", ordtext = "Ordtext", hex = "Hex", chiManSty = "ChiManSty", dbNum1 = "DbNum1", dbNum2 = "DbNum2", aiueo = "Aiueo", iroha = "Iroha", dbChar = "DbChar", sbChar = "SbChar", dbNum3 = "DbNum3", dbNum4 = "DbNum4", circlenum = "Circlenum", darabic = "DArabic", daiueo = "DAiueo", diroha = "DIroha", arabicLZ = "ArabicLZ", bullet = "Bullet", ganada = "Ganada", chosung = "Chosung", gb1 = "GB1", gb2 = "GB2", gb3 = "GB3", gb4 = "GB4", zodiac1 = "Zodiac1", zodiac2 = "Zodiac2", zodiac3 = "Zodiac3", tpeDbNum1 = "TpeDbNum1", tpeDbNum2 = "TpeDbNum2", tpeDbNum3 = "TpeDbNum3", tpeDbNum4 = "TpeDbNum4", chnDbNum1 = "ChnDbNum1", chnDbNum2 = "ChnDbNum2", chnDbNum3 = "ChnDbNum3", chnDbNum4 = "ChnDbNum4", korDbNum1 = "KorDbNum1", korDbNum2 = "KorDbNum2", korDbNum3 = "KorDbNum3", korDbNum4 = "KorDbNum4", hebrew1 = "Hebrew1", arabic1 = "Arabic1", hebrew2 = "Hebrew2", arabic2 = "Arabic2", hindi1 = "Hindi1", hindi2 = "Hindi2", hindi3 = "Hindi3", thai1 = "Thai1", thai2 = "Thai2", numInDash = "NumInDash", lcrus = "LCRus", ucrus = "UCRus", lcgreek = "LCGreek", ucgreek = "UCGreek", lim = "Lim", custom = "Custom", } enum ErrorCodes { generalException = "GeneralException", } export module Interfaces { /** * Provides ways to load properties of only a subset of members of a collection. */ export interface CollectionLoadOptions { /** * Specify the number of items in the queried collection to be included in the result. */ $top?: number; /** * Specify the number of items in the collection that are to be skipped and not included in the result. If top is specified, the selection of result will start after skipping the specified number of items. */ $skip?: number; } /** An interface for updating data on the InkAnalysis object, for use in "inkAnalysis.set({ ... })". */ export interface InkAnalysisUpdateData { /** * * Gets the parent page object. * * [Api set: OneNoteApi 1.1] */ page?: OneNote.Interfaces.PageUpdateData; } /** An interface for updating data on the InkAnalysisParagraph object, for use in "inkAnalysisParagraph.set({ ... })". */ export interface InkAnalysisParagraphUpdateData { /** * * Reference to the parent InkAnalysisPage. * * [Api set: OneNoteApi 1.1] */ inkAnalysis?: OneNote.Interfaces.InkAnalysisUpdateData; } /** An interface for updating data on the InkAnalysisParagraphCollection object, for use in "inkAnalysisParagraphCollection.set({ ... })". */ export interface InkAnalysisParagraphCollectionUpdateData { items?: OneNote.Interfaces.InkAnalysisParagraphData[]; } /** An interface for updating data on the InkAnalysisLine object, for use in "inkAnalysisLine.set({ ... })". */ export interface InkAnalysisLineUpdateData { /** * * Reference to the parent InkAnalysisParagraph. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.InkAnalysisParagraphUpdateData; } /** An interface for updating data on the InkAnalysisLineCollection object, for use in "inkAnalysisLineCollection.set({ ... })". */ export interface InkAnalysisLineCollectionUpdateData { items?: OneNote.Interfaces.InkAnalysisLineData[]; } /** An interface for updating data on the InkAnalysisWord object, for use in "inkAnalysisWord.set({ ... })". */ export interface InkAnalysisWordUpdateData { /** * * Reference to the parent InkAnalysisLine. * * [Api set: OneNoteApi 1.1] */ line?: OneNote.Interfaces.InkAnalysisLineUpdateData; } /** An interface for updating data on the InkAnalysisWordCollection object, for use in "inkAnalysisWordCollection.set({ ... })". */ export interface InkAnalysisWordCollectionUpdateData { items?: OneNote.Interfaces.InkAnalysisWordData[]; } /** An interface for updating data on the InkStrokeCollection object, for use in "inkStrokeCollection.set({ ... })". */ export interface InkStrokeCollectionUpdateData { items?: OneNote.Interfaces.InkStrokeData[]; } /** An interface for updating data on the InkWordCollection object, for use in "inkWordCollection.set({ ... })". */ export interface InkWordCollectionUpdateData { items?: OneNote.Interfaces.InkWordData[]; } /** An interface for updating data on the NotebookCollection object, for use in "notebookCollection.set({ ... })". */ export interface NotebookCollectionUpdateData { items?: OneNote.Interfaces.NotebookData[]; } /** An interface for updating data on the SectionGroupCollection object, for use in "sectionGroupCollection.set({ ... })". */ export interface SectionGroupCollectionUpdateData { items?: OneNote.Interfaces.SectionGroupData[]; } /** An interface for updating data on the SectionCollection object, for use in "sectionCollection.set({ ... })". */ export interface SectionCollectionUpdateData { items?: OneNote.Interfaces.SectionData[]; } /** An interface for updating data on the Page object, for use in "page.set({ ... })". */ export interface PageUpdateData { /** * * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. * * [Api set: OneNoteApi 1.1] */ inkAnalysisOrNull?: OneNote.Interfaces.InkAnalysisUpdateData; /** * * Gets or sets the indentation level of the page. * * [Api set: OneNoteApi 1.1] */ pageLevel?: number; /** * * Gets or sets the title of the page. * * [Api set: OneNoteApi 1.1] */ title?: string; } /** An interface for updating data on the PageCollection object, for use in "pageCollection.set({ ... })". */ export interface PageCollectionUpdateData { items?: OneNote.Interfaces.PageData[]; } /** An interface for updating data on the PageContent object, for use in "pageContent.set({ ... })". */ export interface PageContentUpdateData { /** * * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageUpdateData; /** * * Gets or sets the left (X-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ left?: number; /** * * Gets or sets the top (Y-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ top?: number; } /** An interface for updating data on the PageContentCollection object, for use in "pageContentCollection.set({ ... })". */ export interface PageContentCollectionUpdateData { items?: OneNote.Interfaces.PageContentData[]; } /** An interface for updating data on the Paragraph object, for use in "paragraph.set({ ... })". */ export interface ParagraphUpdateData { /** * * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageUpdateData; /** * * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. * * [Api set: OneNoteApi 1.1] */ table?: OneNote.Interfaces.TableUpdateData; } /** An interface for updating data on the ParagraphCollection object, for use in "paragraphCollection.set({ ... })". */ export interface ParagraphCollectionUpdateData { items?: OneNote.Interfaces.ParagraphData[]; } /** An interface for updating data on the Image object, for use in "image.set({ ... })". */ export interface ImageUpdateData { /** * * Gets or sets the description of the Image. * * [Api set: OneNoteApi 1.1] */ description?: string; /** * * Gets or sets the height of the Image layout. * * [Api set: OneNoteApi 1.1] */ height?: number; /** * * Gets or sets the hyperlink of the Image. * * [Api set: OneNoteApi 1.1] */ hyperlink?: string; /** * * Gets or sets the width of the Image layout. * * [Api set: OneNoteApi 1.1] */ width?: number; } /** An interface for updating data on the Table object, for use in "table.set({ ... })". */ export interface TableUpdateData { /** * * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. * * [Api set: OneNoteApi 1.1] */ borderVisible?: boolean; } /** An interface for updating data on the TableRowCollection object, for use in "tableRowCollection.set({ ... })". */ export interface TableRowCollectionUpdateData { items?: OneNote.Interfaces.TableRowData[]; } /** An interface for updating data on the TableCell object, for use in "tableCell.set({ ... })". */ export interface TableCellUpdateData { /** * * Gets and sets the shading color of the cell * * [Api set: OneNoteApi 1.1] */ shadingColor?: string; } /** An interface for updating data on the TableCellCollection object, for use in "tableCellCollection.set({ ... })". */ export interface TableCellCollectionUpdateData { items?: OneNote.Interfaces.TableCellData[]; } /** An interface describing the data returned by calling "application.toJSON()". */ export interface ApplicationData { /** * * Gets the collection of notebooks that are open in the OneNote application instance. In OneNote on the web, only one notebook at a time is open in the application instance. Read-only. * * [Api set: OneNoteApi 1.1] */ notebooks?: OneNote.Interfaces.NotebookData[]; } /** An interface describing the data returned by calling "inkAnalysis.toJSON()". */ export interface InkAnalysisData { /** * * Gets the parent page object. Read-only. * * [Api set: OneNoteApi 1.1] */ page?: OneNote.Interfaces.PageData; /** * * Gets the ID of the InkAnalysis object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "inkAnalysisParagraph.toJSON()". */ export interface InkAnalysisParagraphData { /** * * Reference to the parent InkAnalysisPage. Read-only. * * [Api set: OneNoteApi 1.1] */ inkAnalysis?: OneNote.Interfaces.InkAnalysisData; /** * * Gets the ink analysis lines in this ink analysis paragraph. Read-only. * * [Api set: OneNoteApi 1.1] */ lines?: OneNote.Interfaces.InkAnalysisLineData[]; /** * * Gets the ID of the InkAnalysisParagraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "inkAnalysisParagraphCollection.toJSON()". */ export interface InkAnalysisParagraphCollectionData { items?: OneNote.Interfaces.InkAnalysisParagraphData[]; } /** An interface describing the data returned by calling "inkAnalysisLine.toJSON()". */ export interface InkAnalysisLineData { /** * * Reference to the parent InkAnalysisParagraph. Read-only. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.InkAnalysisParagraphData; /** * * Gets the ink analysis words in this ink analysis line. Read-only. * * [Api set: OneNoteApi 1.1] */ words?: OneNote.Interfaces.InkAnalysisWordData[]; /** * * Gets the ID of the InkAnalysisLine object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "inkAnalysisLineCollection.toJSON()". */ export interface InkAnalysisLineCollectionData { items?: OneNote.Interfaces.InkAnalysisLineData[]; } /** An interface describing the data returned by calling "inkAnalysisWord.toJSON()". */ export interface InkAnalysisWordData { /** * * Reference to the parent InkAnalysisLine. Read-only. * * [Api set: OneNoteApi 1.1] */ line?: OneNote.Interfaces.InkAnalysisLineData; /** * * Gets the ID of the InkAnalysisWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * The id of the recognized language in this inkAnalysisWord. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: string; /** * * Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. * * [Api set: OneNoteApi 1.1] */ strokePointers?: OneNote.InkStrokePointer[]; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: string[]; } /** An interface describing the data returned by calling "inkAnalysisWordCollection.toJSON()". */ export interface InkAnalysisWordCollectionData { items?: OneNote.Interfaces.InkAnalysisWordData[]; } /** An interface describing the data returned by calling "floatingInk.toJSON()". */ export interface FloatingInkData { /** * * Gets the strokes of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ inkStrokes?: OneNote.Interfaces.InkStrokeData[]; /** * * Gets the ID of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "inkStroke.toJSON()". */ export interface InkStrokeData { /** * * Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ floatingInk?: OneNote.Interfaces.FloatingInkData; /** * * Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "inkStrokeCollection.toJSON()". */ export interface InkStrokeCollectionData { items?: OneNote.Interfaces.InkStrokeData[]; } /** An interface describing the data returned by calling "inkWord.toJSON()". */ export interface InkWordData { /** * * Gets the ID of the InkWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * The id of the recognized language in this ink word. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: string; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: string[]; } /** An interface describing the data returned by calling "inkWordCollection.toJSON()". */ export interface InkWordCollectionData { items?: OneNote.Interfaces.InkWordData[]; } /** An interface describing the data returned by calling "notebook.toJSON()". */ export interface NotebookData { /** * * The section groups in the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupData[]; /** * * The the sections of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionData[]; /** * * The url of the site that this notebook is located. Read only * * [Api set: OneNoteApi 1.1] */ baseUrl?: string; /** * * The client url of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: string; /** * * Gets the ID of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * True if the Notebook is not created by the user (i.e. 'Misplaced Sections'). Read only * * [Api set: OneNoteApi 1.2] */ isVirtual?: boolean; /** * * Gets the name of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: string; } /** An interface describing the data returned by calling "notebookCollection.toJSON()". */ export interface NotebookCollectionData { items?: OneNote.Interfaces.NotebookData[]; } /** An interface describing the data returned by calling "sectionGroup.toJSON()". */ export interface SectionGroupData { /** * * The collection of section groups in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupData[]; /** * * The collection of sections in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionData[]; /** * * The client url of the section group. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: string; /** * * Gets the ID of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the name of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: string; } /** An interface describing the data returned by calling "sectionGroupCollection.toJSON()". */ export interface SectionGroupCollectionData { items?: OneNote.Interfaces.SectionGroupData[]; } /** An interface describing the data returned by calling "section.toJSON()". */ export interface SectionData { /** * * The collection of pages in the section. Read only * * [Api set: OneNoteApi 1.1] */ pages?: OneNote.Interfaces.PageData[]; /** * * The client url of the section. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: string; /** * * Gets the ID of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * True if this section is encrypted with a password. Read only * * [Api set: OneNoteApi 1.2] */ isEncrypted?: boolean; /** * * True if this section is locked. Read only * * [Api set: OneNoteApi 1.2] */ isLocked?: boolean; /** * * Gets the name of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: string; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: string; } /** An interface describing the data returned by calling "sectionCollection.toJSON()". */ export interface SectionCollectionData { items?: OneNote.Interfaces.SectionData[]; } /** An interface describing the data returned by calling "page.toJSON()". */ export interface PageData { /** * * The collection of PageContent objects on the page. Read only * * [Api set: OneNoteApi 1.1] */ contents?: OneNote.Interfaces.PageContentData[]; /** * * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. * * [Api set: OneNoteApi 1.1] */ inkAnalysisOrNull?: OneNote.Interfaces.InkAnalysisData; /** * * Gets the ClassNotebookPageSource to the page. * * [Api set: OneNoteApi 1.1] */ classNotebookPageSource?: string; /** * * The client url of the page. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: string; /** * * Gets the ID of the page. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets or sets the indentation level of the page. * * [Api set: OneNoteApi 1.1] */ pageLevel?: number; /** * * Gets or sets the title of the page. * * [Api set: OneNoteApi 1.1] */ title?: string; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: string; } /** An interface describing the data returned by calling "pageCollection.toJSON()". */ export interface PageCollectionData { items?: OneNote.Interfaces.PageData[]; } /** An interface describing the data returned by calling "pageContent.toJSON()". */ export interface PageContentData { /** * * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageData; /** * * Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. * * [Api set: OneNoteApi 1.1] */ ink?: OneNote.Interfaces.FloatingInkData; /** * * Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. * * [Api set: OneNoteApi 1.1] */ outline?: OneNote.Interfaces.OutlineData; /** * * Gets the ID of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets or sets the left (X-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ left?: number; /** * * Gets or sets the top (Y-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ top?: number; /** * * Gets the type of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: OneNote.PageContentType | "Outline" | "Image" | "Ink" | "Other"; } /** An interface describing the data returned by calling "pageContentCollection.toJSON()". */ export interface PageContentCollectionData { items?: OneNote.Interfaces.PageContentData[]; } /** An interface describing the data returned by calling "outline.toJSON()". */ export interface OutlineData { /** * * Gets the collection of Paragraph objects in the Outline. Read-only. * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphData[]; /** * * Gets the ID of the Outline object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; } /** An interface describing the data returned by calling "paragraph.toJSON()". */ export interface ParagraphData { /** * * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. Read-only. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageData; /** * * Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. Read-only. * * [Api set: OneNoteApi 1.1] */ inkWords?: OneNote.Interfaces.InkWordData[]; /** * * The collection of paragraphs under this paragraph. Read only * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphData[]; /** * * Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. Read-only * * [Api set: OneNoteApi 1.1] */ richText?: OneNote.Interfaces.RichTextData; /** * * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. Read-only. * * [Api set: OneNoteApi 1.1] */ table?: OneNote.Interfaces.TableData; /** * * Gets the ID of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the type of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: OneNote.ParagraphType | "RichText" | "Image" | "Table" | "Ink" | "Other"; } /** An interface describing the data returned by calling "paragraphCollection.toJSON()". */ export interface ParagraphCollectionData { items?: OneNote.Interfaces.ParagraphData[]; } /** An interface describing the data returned by calling "noteTag.toJSON()". */ export interface NoteTagData { /** * * Gets the Id of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the status of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ status?: OneNote.NoteTagStatus | "Unknown" | "Normal" | "Completed" | "Disabled" | "OutlookTask" | "TaskNotSyncedYet" | "TaskRemoved"; /** * * Gets the type of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: OneNote.NoteTagType | "Unknown" | "ToDo" | "Important" | "Question" | "Contact" | "Address" | "PhoneNumber" | "Website" | "Idea" | "Critical" | "ToDoPriority1" | "ToDoPriority2"; } /** An interface describing the data returned by calling "richText.toJSON()". */ export interface RichTextData { /** * * Gets the ID of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * The language id of the text. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: string; /** * * Gets the text content of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ text?: string; } /** An interface describing the data returned by calling "image.toJSON()". */ export interface ImageData { /** * * Gets or sets the description of the Image. * * [Api set: OneNoteApi 1.1] */ description?: string; /** * * Gets or sets the height of the Image layout. * * [Api set: OneNoteApi 1.1] */ height?: number; /** * * Gets or sets the hyperlink of the Image. * * [Api set: OneNoteApi 1.1] */ hyperlink?: string; /** * * Gets the ID of the Image object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the data obtained by OCR (Optical Character Recognition) of this Image, such as OCR text and language. * * [Api set: OneNoteApi 1.1] */ ocrData?: OneNote.ImageOcrData; /** * * Gets or sets the width of the Image layout. * * [Api set: OneNoteApi 1.1] */ width?: number; } /** An interface describing the data returned by calling "table.toJSON()". */ export interface TableData { /** * * Gets all of the table rows. Read-only. * * [Api set: OneNoteApi 1.1] */ rows?: OneNote.Interfaces.TableRowData[]; /** * * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. * * [Api set: OneNoteApi 1.1] */ borderVisible?: boolean; /** * * Gets the number of columns in the table. * * [Api set: OneNoteApi 1.1] */ columnCount?: number; /** * * Gets the ID of the table. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the number of rows in the table. * * [Api set: OneNoteApi 1.1] */ rowCount?: number; } /** An interface describing the data returned by calling "tableRow.toJSON()". */ export interface TableRowData { /** * * Gets the cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ cells?: OneNote.Interfaces.TableCellData[]; /** * * Gets the number of cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellCount?: number; /** * * Gets the ID of the row. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the index of the row in its parent table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: number; } /** An interface describing the data returned by calling "tableRowCollection.toJSON()". */ export interface TableRowCollectionData { items?: OneNote.Interfaces.TableRowData[]; } /** An interface describing the data returned by calling "tableCell.toJSON()". */ export interface TableCellData { /** * * Gets the collection of Paragraph objects in the TableCell. Read-only. * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphData[]; /** * * Gets the index of the cell in its row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellIndex?: number; /** * * Gets the ID of the cell. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: string; /** * * Gets the index of the cell's row in the table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: number; /** * * Gets and sets the shading color of the cell * * [Api set: OneNoteApi 1.1] */ shadingColor?: string; } /** An interface describing the data returned by calling "tableCellCollection.toJSON()". */ export interface TableCellCollectionData { items?: OneNote.Interfaces.TableCellData[]; } /** * * Represents the top-level object that contains all globally addressable OneNote objects such as notebooks, the active notebook, and the active section. * * [Api set: OneNoteApi 1.1] */ export interface ApplicationLoadOptions { $all?: boolean; /** * * Gets the collection of notebooks that are open in the OneNote application instance. In OneNote on the web, only one notebook at a time is open in the application instance. * * [Api set: OneNoteApi 1.1] */ notebooks?: OneNote.Interfaces.NotebookCollectionLoadOptions; } /** * * Represents ink analysis data for a given set of ink strokes. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisLoadOptions { $all?: boolean; /** * * Gets the parent page object. * * [Api set: OneNoteApi 1.1] */ page?: OneNote.Interfaces.PageLoadOptions; /** * * Gets the ID of the InkAnalysis object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents ink analysis data for an identified paragraph formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisParagraphLoadOptions { $all?: boolean; /** * * Reference to the parent InkAnalysisPage. * * [Api set: OneNoteApi 1.1] */ inkAnalysis?: OneNote.Interfaces.InkAnalysisLoadOptions; /** * * Gets the ink analysis lines in this ink analysis paragraph. * * [Api set: OneNoteApi 1.1] */ lines?: OneNote.Interfaces.InkAnalysisLineCollectionLoadOptions; /** * * Gets the ID of the InkAnalysisParagraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents a collection of InkAnalysisParagraph objects. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisParagraphCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Reference to the parent InkAnalysisPage. * * [Api set: OneNoteApi 1.1] */ inkAnalysis?: OneNote.Interfaces.InkAnalysisLoadOptions; /** * * For EACH ITEM in the collection: Gets the ink analysis lines in this ink analysis paragraph. * * [Api set: OneNoteApi 1.1] */ lines?: OneNote.Interfaces.InkAnalysisLineCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the InkAnalysisParagraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents ink analysis data for an identified text line formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisLineLoadOptions { $all?: boolean; /** * * Reference to the parent InkAnalysisParagraph. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.InkAnalysisParagraphLoadOptions; /** * * Gets the ink analysis words in this ink analysis line. * * [Api set: OneNoteApi 1.1] */ words?: OneNote.Interfaces.InkAnalysisWordCollectionLoadOptions; /** * * Gets the ID of the InkAnalysisLine object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents a collection of InkAnalysisLine objects. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisLineCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Reference to the parent InkAnalysisParagraph. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.InkAnalysisParagraphLoadOptions; /** * * For EACH ITEM in the collection: Gets the ink analysis words in this ink analysis line. * * [Api set: OneNoteApi 1.1] */ words?: OneNote.Interfaces.InkAnalysisWordCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the InkAnalysisLine object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents ink analysis data for an identified word formed by ink strokes. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisWordLoadOptions { $all?: boolean; /** * * Reference to the parent InkAnalysisLine. * * [Api set: OneNoteApi 1.1] */ line?: OneNote.Interfaces.InkAnalysisLineLoadOptions; /** * * Gets the ID of the InkAnalysisWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * The id of the recognized language in this inkAnalysisWord. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: boolean; /** * * Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. * * [Api set: OneNoteApi 1.1] */ strokePointers?: boolean; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: boolean; } /** * * Represents a collection of InkAnalysisWord objects. * * [Api set: OneNoteApi 1.1] */ export interface InkAnalysisWordCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Reference to the parent InkAnalysisLine. * * [Api set: OneNoteApi 1.1] */ line?: OneNote.Interfaces.InkAnalysisLineLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the InkAnalysisWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: The id of the recognized language in this inkAnalysisWord. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: boolean; /** * * For EACH ITEM in the collection: Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. * * [Api set: OneNoteApi 1.1] */ strokePointers?: boolean; /** * * For EACH ITEM in the collection: The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: boolean; } /** * * Represents a group of ink strokes. * * [Api set: OneNoteApi 1.1] */ export interface FloatingInkLoadOptions { $all?: boolean; /** * * Gets the strokes of the FloatingInk object. * * [Api set: OneNoteApi 1.1] */ inkStrokes?: OneNote.Interfaces.InkStrokeCollectionLoadOptions; /** * * Gets the PageContent parent of the FloatingInk object. * * [Api set: OneNoteApi 1.1] */ pageContent?: OneNote.Interfaces.PageContentLoadOptions; /** * * Gets the ID of the FloatingInk object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents a single stroke of ink. * * [Api set: OneNoteApi 1.1] */ export interface InkStrokeLoadOptions { $all?: boolean; /** * * Gets the ID of the InkStroke object. * * [Api set: OneNoteApi 1.1] */ floatingInk?: OneNote.Interfaces.FloatingInkLoadOptions; /** * * Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * Represents a collection of InkStroke objects. * * [Api set: OneNoteApi 1.1] */ export interface InkStrokeCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the InkStroke object. * * [Api set: OneNoteApi 1.1] */ floatingInk?: OneNote.Interfaces.FloatingInkLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the InkStroke object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * A container for the ink in a word in a paragraph. * * [Api set: OneNoteApi 1.1] */ export interface InkWordLoadOptions { $all?: boolean; /** * * The parent paragraph containing the ink word. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets the ID of the InkWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * The id of the recognized language in this ink word. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: boolean; /** * * The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: boolean; } /** * * Represents a collection of InkWord objects. * * [Api set: OneNoteApi 1.1] */ export interface InkWordCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: The parent paragraph containing the ink word. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the InkWord object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: The id of the recognized language in this ink word. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: boolean; /** * * For EACH ITEM in the collection: The words that were recognized in this ink word, in order of likelihood. Read-only. * * [Api set: OneNoteApi 1.1] */ wordAlternates?: boolean; } /** * * Represents a OneNote notebook. Notebooks contain section groups and sections. * * [Api set: OneNoteApi 1.1] */ export interface NotebookLoadOptions { $all?: boolean; /** * * The section groups in the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupCollectionLoadOptions; /** * * The the sections of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionCollectionLoadOptions; /** * * The url of the site that this notebook is located. Read only * * [Api set: OneNoteApi 1.1] */ baseUrl?: boolean; /** * * The client url of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * Gets the ID of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * True if the Notebook is not created by the user (i.e. 'Misplaced Sections'). Read only * * [Api set: OneNoteApi 1.2] */ isVirtual?: boolean; /** * * Gets the name of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; } /** * * Represents a collection of notebooks. * * [Api set: OneNoteApi 1.1] */ export interface NotebookCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: The section groups in the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupCollectionLoadOptions; /** * * For EACH ITEM in the collection: The the sections of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionCollectionLoadOptions; /** * * For EACH ITEM in the collection: The url of the site that this notebook is located. Read only * * [Api set: OneNoteApi 1.1] */ baseUrl?: boolean; /** * * For EACH ITEM in the collection: The client url of the notebook. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: True if the Notebook is not created by the user (i.e. 'Misplaced Sections'). Read only * * [Api set: OneNoteApi 1.2] */ isVirtual?: boolean; /** * * For EACH ITEM in the collection: Gets the name of the notebook. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; } /** * * Represents a OneNote section group. Section groups can contain sections and other section groups. * * [Api set: OneNoteApi 1.1] */ export interface SectionGroupLoadOptions { $all?: boolean; /** * * Gets the notebook that contains the section group. * * [Api set: OneNoteApi 1.1] */ notebook?: OneNote.Interfaces.NotebookLoadOptions; /** * * Gets the section group that contains the section group. Throws ItemNotFound if the section group is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroup?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * Gets the section group that contains the section group. Returns null if the section group is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroupOrNull?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * The collection of section groups in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupCollectionLoadOptions; /** * * The collection of sections in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionCollectionLoadOptions; /** * * The client url of the section group. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * Gets the ID of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the name of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; } /** * * Represents a collection of section groups. * * [Api set: OneNoteApi 1.1] */ export interface SectionGroupCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the notebook that contains the section group. * * [Api set: OneNoteApi 1.1] */ notebook?: OneNote.Interfaces.NotebookLoadOptions; /** * * For EACH ITEM in the collection: Gets the section group that contains the section group. Throws ItemNotFound if the section group is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroup?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * For EACH ITEM in the collection: Gets the section group that contains the section group. Returns null if the section group is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroupOrNull?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * For EACH ITEM in the collection: The collection of section groups in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sectionGroups?: OneNote.Interfaces.SectionGroupCollectionLoadOptions; /** * * For EACH ITEM in the collection: The collection of sections in the section group. Read only * * [Api set: OneNoteApi 1.1] */ sections?: OneNote.Interfaces.SectionCollectionLoadOptions; /** * * For EACH ITEM in the collection: The client url of the section group. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets the name of the section group. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; } /** * * Represents a OneNote section. Sections can contain pages. * * [Api set: OneNoteApi 1.1] */ export interface SectionLoadOptions { $all?: boolean; /** * * Gets the notebook that contains the section. * * [Api set: OneNoteApi 1.1] */ notebook?: OneNote.Interfaces.NotebookLoadOptions; /** * * The collection of pages in the section. Read only * * [Api set: OneNoteApi 1.1] */ pages?: OneNote.Interfaces.PageCollectionLoadOptions; /** * * Gets the section group that contains the section. Throws ItemNotFound if the section is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroup?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * Gets the section group that contains the section. Returns null if the section is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroupOrNull?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * The client url of the section. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * Gets the ID of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * True if this section is encrypted with a password. Read only * * [Api set: OneNoteApi 1.2] */ isEncrypted?: boolean; /** * * True if this section is locked. Read only * * [Api set: OneNoteApi 1.2] */ isLocked?: boolean; /** * * Gets the name of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: boolean; } /** * * Represents a collection of sections. * * [Api set: OneNoteApi 1.1] */ export interface SectionCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the notebook that contains the section. * * [Api set: OneNoteApi 1.1] */ notebook?: OneNote.Interfaces.NotebookLoadOptions; /** * * For EACH ITEM in the collection: The collection of pages in the section. Read only * * [Api set: OneNoteApi 1.1] */ pages?: OneNote.Interfaces.PageCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the section group that contains the section. Throws ItemNotFound if the section is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroup?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * For EACH ITEM in the collection: Gets the section group that contains the section. Returns null if the section is a direct child of the notebook. * * [Api set: OneNoteApi 1.1] */ parentSectionGroupOrNull?: OneNote.Interfaces.SectionGroupLoadOptions; /** * * For EACH ITEM in the collection: The client url of the section. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: True if this section is encrypted with a password. Read only * * [Api set: OneNoteApi 1.2] */ isEncrypted?: boolean; /** * * For EACH ITEM in the collection: True if this section is locked. Read only * * [Api set: OneNoteApi 1.2] */ isLocked?: boolean; /** * * For EACH ITEM in the collection: Gets the name of the section. Read-only. * * [Api set: OneNoteApi 1.1] */ name?: boolean; /** * * For EACH ITEM in the collection: The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: boolean; } /** * * Represents a OneNote page. * * [Api set: OneNoteApi 1.1] */ export interface PageLoadOptions { $all?: boolean; /** * * The collection of PageContent objects on the page. Read only * * [Api set: OneNoteApi 1.1] */ contents?: OneNote.Interfaces.PageContentCollectionLoadOptions; /** * * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. * * [Api set: OneNoteApi 1.1] */ inkAnalysisOrNull?: OneNote.Interfaces.InkAnalysisLoadOptions; /** * * Gets the section that contains the page. * * [Api set: OneNoteApi 1.1] */ parentSection?: OneNote.Interfaces.SectionLoadOptions; /** * * Gets the ClassNotebookPageSource to the page. * * [Api set: OneNoteApi 1.1] */ classNotebookPageSource?: boolean; /** * * The client url of the page. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * Gets the ID of the page. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets or sets the indentation level of the page. * * [Api set: OneNoteApi 1.1] */ pageLevel?: boolean; /** * * Gets or sets the title of the page. * * [Api set: OneNoteApi 1.1] */ title?: boolean; /** * * The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: boolean; } /** * * Represents a collection of pages. * * [Api set: OneNoteApi 1.1] */ export interface PageCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: The collection of PageContent objects on the page. Read only * * [Api set: OneNoteApi 1.1] */ contents?: OneNote.Interfaces.PageContentCollectionLoadOptions; /** * * For EACH ITEM in the collection: Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. * * [Api set: OneNoteApi 1.1] */ inkAnalysisOrNull?: OneNote.Interfaces.InkAnalysisLoadOptions; /** * * For EACH ITEM in the collection: Gets the section that contains the page. * * [Api set: OneNoteApi 1.1] */ parentSection?: OneNote.Interfaces.SectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the ClassNotebookPageSource to the page. * * [Api set: OneNoteApi 1.1] */ classNotebookPageSource?: boolean; /** * * For EACH ITEM in the collection: The client url of the page. Read only * * [Api set: OneNoteApi 1.1] */ clientUrl?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the page. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets or sets the indentation level of the page. * * [Api set: OneNoteApi 1.1] */ pageLevel?: boolean; /** * * For EACH ITEM in the collection: Gets or sets the title of the page. * * [Api set: OneNoteApi 1.1] */ title?: boolean; /** * * For EACH ITEM in the collection: The web url of the page. Read only * * [Api set: OneNoteApi 1.1] */ webUrl?: boolean; } /** * * Represents a region on a page that contains top-level content types such as Outline or Image. A PageContent object can be assigned an XY position. * * [Api set: OneNoteApi 1.1] */ export interface PageContentLoadOptions { $all?: boolean; /** * * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageLoadOptions; /** * * Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. * * [Api set: OneNoteApi 1.1] */ ink?: OneNote.Interfaces.FloatingInkLoadOptions; /** * * Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. * * [Api set: OneNoteApi 1.1] */ outline?: OneNote.Interfaces.OutlineLoadOptions; /** * * Gets the page that contains the PageContent object. * * [Api set: OneNoteApi 1.1] */ parentPage?: OneNote.Interfaces.PageLoadOptions; /** * * Gets the ID of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets or sets the left (X-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ left?: boolean; /** * * Gets or sets the top (Y-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ top?: boolean; /** * * Gets the type of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: boolean; } /** * * Represents the contents of a page, as a collection of PageContent objects. * * [Api set: OneNoteApi 1.1] */ export interface PageContentCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageLoadOptions; /** * * For EACH ITEM in the collection: Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. * * [Api set: OneNoteApi 1.1] */ ink?: OneNote.Interfaces.FloatingInkLoadOptions; /** * * For EACH ITEM in the collection: Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. * * [Api set: OneNoteApi 1.1] */ outline?: OneNote.Interfaces.OutlineLoadOptions; /** * * For EACH ITEM in the collection: Gets the page that contains the PageContent object. * * [Api set: OneNoteApi 1.1] */ parentPage?: OneNote.Interfaces.PageLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets or sets the left (X-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ left?: boolean; /** * * For EACH ITEM in the collection: Gets or sets the top (Y-axis) position of the PageContent object. * * [Api set: OneNoteApi 1.1] */ top?: boolean; /** * * For EACH ITEM in the collection: Gets the type of the PageContent object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: boolean; } /** * * Represents a container for Paragraph objects. * * [Api set: OneNoteApi 1.1] */ export interface OutlineLoadOptions { $all?: boolean; /** * * Gets the PageContent object that contains the Outline. This object defines the position of the Outline on the page. * * [Api set: OneNoteApi 1.1] */ pageContent?: OneNote.Interfaces.PageContentLoadOptions; /** * * Gets the collection of Paragraph objects in the Outline. * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphCollectionLoadOptions; /** * * Gets the ID of the Outline object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; } /** * * A container for the visible content on a page. A Paragraph can contain any one ParagraphType type of content. * * [Api set: OneNoteApi 1.1] */ export interface ParagraphLoadOptions { $all?: boolean; /** * * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageLoadOptions; /** * * Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. * * [Api set: OneNoteApi 1.1] */ inkWords?: OneNote.Interfaces.InkWordCollectionLoadOptions; /** * * Gets the Outline object that contains the Paragraph. * * [Api set: OneNoteApi 1.1] */ outline?: OneNote.Interfaces.OutlineLoadOptions; /** * * The collection of paragraphs under this paragraph. Read only * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphCollectionLoadOptions; /** * * Gets the parent paragraph object. Throws if a parent paragraph does not exist. * * [Api set: OneNoteApi 1.1] */ parentParagraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets the parent paragraph object. Returns null if a parent paragraph does not exist. * * [Api set: OneNoteApi 1.1] */ parentParagraphOrNull?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ parentTableCell?: OneNote.Interfaces.TableCellLoadOptions; /** * * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, returns null. * * [Api set: OneNoteApi 1.1] */ parentTableCellOrNull?: OneNote.Interfaces.TableCellLoadOptions; /** * * Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. * * [Api set: OneNoteApi 1.1] */ richText?: OneNote.Interfaces.RichTextLoadOptions; /** * * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. * * [Api set: OneNoteApi 1.1] */ table?: OneNote.Interfaces.TableLoadOptions; /** * * Gets the ID of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the type of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: boolean; } /** * * Represents a collection of Paragraph objects. * * [Api set: OneNoteApi 1.1] */ export interface ParagraphCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. * * [Api set: OneNoteApi 1.1] */ image?: OneNote.Interfaces.ImageLoadOptions; /** * * For EACH ITEM in the collection: Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. * * [Api set: OneNoteApi 1.1] */ inkWords?: OneNote.Interfaces.InkWordCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the Outline object that contains the Paragraph. * * [Api set: OneNoteApi 1.1] */ outline?: OneNote.Interfaces.OutlineLoadOptions; /** * * For EACH ITEM in the collection: The collection of paragraphs under this paragraph. Read only * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the parent paragraph object. Throws if a parent paragraph does not exist. * * [Api set: OneNoteApi 1.1] */ parentParagraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * For EACH ITEM in the collection: Gets the parent paragraph object. Returns null if a parent paragraph does not exist. * * [Api set: OneNoteApi 1.1] */ parentParagraphOrNull?: OneNote.Interfaces.ParagraphLoadOptions; /** * * For EACH ITEM in the collection: Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, throws ItemNotFound. * * [Api set: OneNoteApi 1.1] */ parentTableCell?: OneNote.Interfaces.TableCellLoadOptions; /** * * For EACH ITEM in the collection: Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, returns null. * * [Api set: OneNoteApi 1.1] */ parentTableCellOrNull?: OneNote.Interfaces.TableCellLoadOptions; /** * * For EACH ITEM in the collection: Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. * * [Api set: OneNoteApi 1.1] */ richText?: OneNote.Interfaces.RichTextLoadOptions; /** * * For EACH ITEM in the collection: Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. * * [Api set: OneNoteApi 1.1] */ table?: OneNote.Interfaces.TableLoadOptions; /** * * For EACH ITEM in the collection: Gets the ID of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets the type of the Paragraph object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: boolean; } /** * * A container for the NoteTag in a paragraph. * * [Api set: OneNoteApi 1.1] */ export interface NoteTagLoadOptions { $all?: boolean; /** * * Gets the Id of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the status of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ status?: boolean; /** * * Gets the type of the NoteTag object. Read-only. * * [Api set: OneNoteApi 1.1] */ type?: boolean; } /** * * Represents a RichText object in a Paragraph. * * [Api set: OneNoteApi 1.1] */ export interface RichTextLoadOptions { $all?: boolean; /** * * Gets the Paragraph object that contains the RichText object. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets the ID of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * The language id of the text. Read-only. * * [Api set: OneNoteApi 1.1] */ languageId?: boolean; /** * * Gets the text content of the RichText object. Read-only. * * [Api set: OneNoteApi 1.1] */ text?: boolean; } /** * * Represents an Image. An Image can be a direct child of a PageContent object or a Paragraph object. * * [Api set: OneNoteApi 1.1] */ export interface ImageLoadOptions { $all?: boolean; /** * * Gets the PageContent object that contains the Image. Throws if the Image is not a direct child of a PageContent. This object defines the position of the Image on the page. * * [Api set: OneNoteApi 1.1] */ pageContent?: OneNote.Interfaces.PageContentLoadOptions; /** * * Gets the Paragraph object that contains the Image. Throws if the Image is not a direct child of a Paragraph. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets or sets the description of the Image. * * [Api set: OneNoteApi 1.1] */ description?: boolean; /** * * Gets or sets the height of the Image layout. * * [Api set: OneNoteApi 1.1] */ height?: boolean; /** * * Gets or sets the hyperlink of the Image. * * [Api set: OneNoteApi 1.1] */ hyperlink?: boolean; /** * * Gets the ID of the Image object. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the data obtained by OCR (Optical Character Recognition) of this Image, such as OCR text and language. * * [Api set: OneNoteApi 1.1] */ ocrData?: boolean; /** * * Gets or sets the width of the Image layout. * * [Api set: OneNoteApi 1.1] */ width?: boolean; } /** * * Represents a table in a OneNote page. * * [Api set: OneNoteApi 1.1] */ export interface TableLoadOptions { $all?: boolean; /** * * Gets the Paragraph object that contains the Table object. * * [Api set: OneNoteApi 1.1] */ paragraph?: OneNote.Interfaces.ParagraphLoadOptions; /** * * Gets all of the table rows. * * [Api set: OneNoteApi 1.1] */ rows?: OneNote.Interfaces.TableRowCollectionLoadOptions; /** * * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. * * [Api set: OneNoteApi 1.1] */ borderVisible?: boolean; /** * * Gets the number of columns in the table. * * [Api set: OneNoteApi 1.1] */ columnCount?: boolean; /** * * Gets the ID of the table. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the number of rows in the table. * * [Api set: OneNoteApi 1.1] */ rowCount?: boolean; } /** * * Represents a row in a table. * * [Api set: OneNoteApi 1.1] */ export interface TableRowLoadOptions { $all?: boolean; /** * * Gets the cells in the row. * * [Api set: OneNoteApi 1.1] */ cells?: OneNote.Interfaces.TableCellCollectionLoadOptions; /** * * Gets the parent table. * * [Api set: OneNoteApi 1.1] */ parentTable?: OneNote.Interfaces.TableLoadOptions; /** * * Gets the number of cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellCount?: boolean; /** * * Gets the ID of the row. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the index of the row in its parent table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: boolean; } /** * * Contains a collection of TableRow objects. * * [Api set: OneNoteApi 1.1] */ export interface TableRowCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the cells in the row. * * [Api set: OneNoteApi 1.1] */ cells?: OneNote.Interfaces.TableCellCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the parent table. * * [Api set: OneNoteApi 1.1] */ parentTable?: OneNote.Interfaces.TableLoadOptions; /** * * For EACH ITEM in the collection: Gets the number of cells in the row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellCount?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the row. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets the index of the row in its parent table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: boolean; } /** * * Represents a cell in a OneNote table. * * [Api set: OneNoteApi 1.1] */ export interface TableCellLoadOptions { $all?: boolean; /** * * Gets the collection of Paragraph objects in the TableCell. * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphCollectionLoadOptions; /** * * Gets the parent row of the cell. * * [Api set: OneNoteApi 1.1] */ parentRow?: OneNote.Interfaces.TableRowLoadOptions; /** * * Gets the index of the cell in its row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellIndex?: boolean; /** * * Gets the ID of the cell. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * Gets the index of the cell's row in the table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: boolean; /** * * Gets and sets the shading color of the cell * * [Api set: OneNoteApi 1.1] */ shadingColor?: boolean; } /** * * Contains a collection of TableCell objects. * * [Api set: OneNoteApi 1.1] */ export interface TableCellCollectionLoadOptions { $all?: boolean; /** * * For EACH ITEM in the collection: Gets the collection of Paragraph objects in the TableCell. * * [Api set: OneNoteApi 1.1] */ paragraphs?: OneNote.Interfaces.ParagraphCollectionLoadOptions; /** * * For EACH ITEM in the collection: Gets the parent row of the cell. * * [Api set: OneNoteApi 1.1] */ parentRow?: OneNote.Interfaces.TableRowLoadOptions; /** * * For EACH ITEM in the collection: Gets the index of the cell in its row. Read-only. * * [Api set: OneNoteApi 1.1] */ cellIndex?: boolean; /** * * For EACH ITEM in the collection: Gets the ID of the cell. Read-only. * * [Api set: OneNoteApi 1.1] */ id?: boolean; /** * * For EACH ITEM in the collection: Gets the index of the cell's row in the table. Read-only. * * [Api set: OneNoteApi 1.1] */ rowIndex?: boolean; /** * * For EACH ITEM in the collection: Gets and sets the shading color of the cell * * [Api set: OneNoteApi 1.1] */ shadingColor?: boolean; } } } export declare namespace OneNote { export class RequestContext extends OfficeExtension.ClientRequestContext { constructor(url?: string); readonly application: Application; } /** * Executes a batch script that performs actions on the OneNote object model, using a new request context. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. * @param batch - A function that takes in an OneNote.RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the OneNote application. Since the Office add-in and the OneNote application run in two different processes, the request context is required to get access to the OneNote object model from the add-in. */ export function run<T>(batch: (context: OneNote.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the OneNote object model, using the request context of a previously-created API object. * @param object - A previously-created API object. The batch will use the same request context as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". * @param batch - A function that takes in an OneNote.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. */ export function run<T>(object: OfficeExtension.ClientObject, batch: (context: OneNote.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the OneNote object model, using the request context of previously-created API objects. * @param object - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared request context, which means that any changes applied to these objects will be picked up by "context.sync()". * @param batch - A function that takes in an OneNote.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. */ export function run<T>(objects: OfficeExtension.ClientObject[], batch: (context: OneNote.RequestContext) => Promise<T>): Promise<T>; } //////////////////////////////////////////////////////////////// /////////////////////// End OneNote APIs /////////////////////// ////////////////////////////////////////////////////////////////
the_stack
export interface NumberGenerator { random: () => number } // Added 4D noise export class SimplexNoise { private grad3 = [ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1], ] private grad4 = [ [0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], [-1, 0, 1, 1], [-1, 0, 1, -1], [-1, 0, -1, 1], [-1, 0, -1, -1], [1, 1, 0, 1], [1, 1, 0, -1], [1, -1, 0, 1], [1, -1, 0, -1], [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0], ] private p: number[] = [] // To remove the need for index wrapping, double the permutation table length private perm: number[] = [] // A lookup table to traverse the simplex around a given point in 4D. // Details can be found where this table is used, in the 4D noise method. private simplex = [ [0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 0, 3], [0, 0, 0, 0], [1, 3, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 3, 0, 1], [2, 3, 1, 0], [1, 0, 2, 3], [1, 0, 3, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 3, 1], [0, 0, 0, 0], [2, 1, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0], ] /** * You can pass in a random number generator object if you like. * It is assumed to have a random() method. */ constructor(r: NumberGenerator = Math) { for (let i = 0; i < 256; i++) { this.p[i] = Math.floor(r.random() * 256) } for (let i = 0; i < 512; i++) { this.perm[i] = this.p[i & 255] } } public dot = (g: number[], x: number, y: number): number => { return g[0] * x + g[1] * y } public dot3 = (g: number[], x: number, y: number, z: number): number => { return g[0] * x + g[1] * y + g[2] * z } public dot4 = (g: number[], x: number, y: number, z: number, w: number): number => { return g[0] * x + g[1] * y + g[2] * z + g[3] * w } public noise = (xin: number, yin: number): number => { let n0 let n1 let n2 // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in const F2 = 0.5 * (Math.sqrt(3.0) - 1.0) const s = (xin + yin) * F2 // Hairy factor for 2D const i = Math.floor(xin + s) const j = Math.floor(yin + s) const G2 = (3.0 - Math.sqrt(3.0)) / 6.0 const t = (i + j) * G2 const X0 = i - t // Unskew the cell origin back to (x,y) space const Y0 = j - t const x0 = xin - X0 // The x,y distances from the cell origin const y0 = yin - Y0 // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. // upper triangle, YX order: (0,0)->(0,1)->(1,1) let i1 = 0 // Offsets for second (middle) corner of simplex in (i,j) coords let j1 = 1 if (x0 > y0) { i1 = 1 j1 = 0 } // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 const x1 = x0 - i1 + G2 // Offsets for middle corner in (x,y) unskewed coords const y1 = y0 - j1 + G2 const x2 = x0 - 1.0 + 2.0 * G2 // Offsets for last corner in (x,y) unskewed coords const y2 = y0 - 1.0 + 2.0 * G2 // Work out the hashed gradient indices of the three simplex corners const ii = i & 255 const jj = j & 255 const gi0 = this.perm[ii + this.perm[jj]] % 12 const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12 const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12 // Calculate the contribution from the three corners let t0 = 0.5 - x0 * x0 - y0 * y0 if (t0 < 0) { n0 = 0.0 } else { t0 *= t0 n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0) // (x,y) of grad3 used for 2D gradient } let t1 = 0.5 - x1 * x1 - y1 * y1 if (t1 < 0) { n1 = 0.0 } else { t1 *= t1 n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1) } let t2 = 0.5 - x2 * x2 - y2 * y2 if (t2 < 0) { n2 = 0.0 } else { t2 *= t2 n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2) } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 70.0 * (n0 + n1 + n2) } // 3D simplex noise private noise3d = (xin: number, yin: number, zin: number): number => { // Noise contributions from the four corners let n0 let n1 let n2 let n3 // Skew the input space to determine which simplex cell we're in const F3 = 1.0 / 3.0 const s = (xin + yin + zin) * F3 // Very nice and simple skew factor for 3D const i = Math.floor(xin + s) const j = Math.floor(yin + s) const k = Math.floor(zin + s) const G3 = 1.0 / 6.0 // Very nice and simple unskew factor, too const t = (i + j + k) * G3 const X0 = i - t // Unskew the cell origin back to (x,y,z) space const Y0 = j - t const Z0 = k - t const x0 = xin - X0 // The x,y,z distances from the cell origin const y0 = yin - Y0 const z0 = zin - Z0 // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. let i1 let j1 let k1 // Offsets for second corner of simplex in (i,j,k) coords let i2 let j2 let k2 // Offsets for third corner of simplex in (i,j,k) coords if (x0 >= y0) { if (y0 >= z0) { i1 = 1 j1 = 0 k1 = 0 i2 = 1 j2 = 1 k2 = 0 // X Y Z order } else if (x0 >= z0) { i1 = 1 j1 = 0 k1 = 0 i2 = 1 j2 = 0 k2 = 1 // X Z Y order } else { i1 = 0 j1 = 0 k1 = 1 i2 = 1 j2 = 0 k2 = 1 } // Z X Y order } else { // x0<y0 if (y0 < z0) { i1 = 0 j1 = 0 k1 = 1 i2 = 0 j2 = 1 k2 = 1 // Z Y X order } else if (x0 < z0) { i1 = 0 j1 = 1 k1 = 0 i2 = 0 j2 = 1 k2 = 1 // Y Z X order } else { i1 = 0 j1 = 1 k1 = 0 i2 = 1 j2 = 1 k2 = 0 } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. const x1 = x0 - i1 + G3 // Offsets for second corner in (x,y,z) coords const y1 = y0 - j1 + G3 const z1 = z0 - k1 + G3 const x2 = x0 - i2 + 2.0 * G3 // Offsets for third corner in (x,y,z) coords const y2 = y0 - j2 + 2.0 * G3 const z2 = z0 - k2 + 2.0 * G3 const x3 = x0 - 1.0 + 3.0 * G3 // Offsets for last corner in (x,y,z) coords const y3 = y0 - 1.0 + 3.0 * G3 const z3 = z0 - 1.0 + 3.0 * G3 // Work out the hashed gradient indices of the four simplex corners const ii = i & 255 const jj = j & 255 const kk = k & 255 const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12 const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12 const gi2 = this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12 const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12 // Calculate the contribution from the four corners let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 if (t0 < 0) { n0 = 0.0 } else { t0 *= t0 n0 = t0 * t0 * this.dot3(this.grad3[gi0], x0, y0, z0) } let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 if (t1 < 0) { n1 = 0.0 } else { t1 *= t1 n1 = t1 * t1 * this.dot3(this.grad3[gi1], x1, y1, z1) } let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 if (t2 < 0) { n2 = 0.0 } else { t2 *= t2 n2 = t2 * t2 * this.dot3(this.grad3[gi2], x2, y2, z2) } let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 if (t3 < 0) { n3 = 0.0 } else { t3 *= t3 n3 = t3 * t3 * this.dot3(this.grad3[gi3], x3, y3, z3) } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.0 * (n0 + n1 + n2 + n3) } // 4D simplex noise public noise4d = (x: number, y: number, z: number, w: number): number => { // For faster and easier lookups const grad4 = this.grad4 const simplex = this.simplex const perm = this.perm // The skewing and unskewing factors are hairy again for the 4D case const F4 = (Math.sqrt(5.0) - 1.0) / 4.0 const G4 = (5.0 - Math.sqrt(5.0)) / 20.0 let n0 let n1 let n2 let n3 let n4 // Noise contributions from the five corners // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in const s = (x + y + z + w) * F4 // Factor for 4D skewing const i = Math.floor(x + s) const j = Math.floor(y + s) const k = Math.floor(z + s) const l = Math.floor(w + s) const t = (i + j + k + l) * G4 // Factor for 4D unskewing const X0 = i - t // Unskew the cell origin back to (x,y,z,w) space const Y0 = j - t const Z0 = k - t const W0 = l - t const x0 = x - X0 // The x,y,z,w distances from the cell origin const y0 = y - Y0 const z0 = z - Z0 const w0 = w - W0 // For the 4D case, the simplex is a 4D shape I won't even try to describe. // To find out which of the 24 possible simplices we're in, we need to // determine the magnitude ordering of x0, y0, z0 and w0. // The method below is a good way of finding the ordering of x,y,z,w and // then find the correct traversal order for the simplex we’re in. // First, six pair-wise comparisons are performed between each possible pair // of the four coordinates, and the results are used to add up binary bits // for an integer index. const c1 = x0 > y0 ? 32 : 0 const c2 = x0 > z0 ? 16 : 0 const c3 = y0 > z0 ? 8 : 0 const c4 = x0 > w0 ? 4 : 0 const c5 = y0 > w0 ? 2 : 0 const c6 = z0 > w0 ? 1 : 0 const c = c1 + c2 + c3 + c4 + c5 + c6 // The integer offsets for the second simplex corner let i1 let j1 let k1 let l1 // The integer offsets for the third simplex corner let i2 let j2 let k2 let l2 // The integer offsets for the fourth simplex corner let i3 let j3 let k3 let l3 // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w // impossible. Only the 24 indices which have non-zero entries make any sense. // We use a thresholding to set the coordinates in turn from the largest magnitude. // The number 3 in the "simplex" array is at the position of the largest coordinate. i1 = simplex[c][0] >= 3 ? 1 : 0 j1 = simplex[c][1] >= 3 ? 1 : 0 k1 = simplex[c][2] >= 3 ? 1 : 0 l1 = simplex[c][3] >= 3 ? 1 : 0 // The number 2 in the "simplex" array is at the second largest coordinate. i2 = simplex[c][0] >= 2 ? 1 : 0 j2 = simplex[c][1] >= 2 ? 1 : 0 k2 = simplex[c][2] >= 2 ? 1 : 0 l2 = simplex[c][3] >= 2 ? 1 : 0 // The number 1 in the "simplex" array is at the second smallest coordinate. i3 = simplex[c][0] >= 1 ? 1 : 0 j3 = simplex[c][1] >= 1 ? 1 : 0 k3 = simplex[c][2] >= 1 ? 1 : 0 l3 = simplex[c][3] >= 1 ? 1 : 0 // The fifth corner has all coordinate offsets = 1, so no need to look that up. const x1 = x0 - i1 + G4 // Offsets for second corner in (x,y,z,w) coords const y1 = y0 - j1 + G4 const z1 = z0 - k1 + G4 const w1 = w0 - l1 + G4 const x2 = x0 - i2 + 2.0 * G4 // Offsets for third corner in (x,y,z,w) coords const y2 = y0 - j2 + 2.0 * G4 const z2 = z0 - k2 + 2.0 * G4 const w2 = w0 - l2 + 2.0 * G4 const x3 = x0 - i3 + 3.0 * G4 // Offsets for fourth corner in (x,y,z,w) coords const y3 = y0 - j3 + 3.0 * G4 const z3 = z0 - k3 + 3.0 * G4 const w3 = w0 - l3 + 3.0 * G4 const x4 = x0 - 1.0 + 4.0 * G4 // Offsets for last corner in (x,y,z,w) coords const y4 = y0 - 1.0 + 4.0 * G4 const z4 = z0 - 1.0 + 4.0 * G4 const w4 = w0 - 1.0 + 4.0 * G4 // Work out the hashed gradient indices of the five simplex corners const ii = i & 255 const jj = j & 255 const kk = k & 255 const ll = l & 255 const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32 const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32 const gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32 const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32 const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32 // Calculate the contribution from the five corners let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0 if (t0 < 0) { n0 = 0.0 } else { t0 *= t0 n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0) } let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1 if (t1 < 0) { n1 = 0.0 } else { t1 *= t1 n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1) } let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2 if (t2 < 0) { n2 = 0.0 } else { t2 *= t2 n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2) } let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3 if (t3 < 0) { n3 = 0.0 } else { t3 *= t3 n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3) } let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4 if (t4 < 0) { n4 = 0.0 } else { t4 *= t4 n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4) } // Sum up and scale the result to cover the range [-1,1] return 27.0 * (n0 + n1 + n2 + n3 + n4) } }
the_stack
import { EncodedString, LinterWarning } from "../../../elements"; import { Polymer } from '../../../../../tools/definitions/polymer'; import { I18NKeys } from "../../../../_locales/i18n-keys"; declare const browserAPI: browserAPI; declare const BrowserAPI: BrowserAPI; export type MonacoEditorScriptMetaMods = MonacoEditorElement.MonacoEditorScriptMetaMods; export type MonacoEditorHookManager = typeof MonacoEditorElement.MonacoEditorHookManager; export type MonacoEditorTSLibrariesMetaMods = MonacoEditorElement.MonacoEditorTSLibrariesMetaMods; export type MetaBlock = MonacoEditorElement.MetaBlock; namespace MonacoEditorElement { function getMetaDescriptions() { return { name: window.__.sync(I18NKeys.options.editPages.metadata.name), namespace: window.__.sync(I18NKeys.options.editPages.metadata.namespace), version: window.__.sync(I18NKeys.options.editPages.metadata.version), author: window.__.sync(I18NKeys.options.editPages.metadata.author), description: window.__.sync(I18NKeys.options.editPages.metadata.description), homepage: window.__.sync(I18NKeys.options.editPages.metadata.homepage), homepageURL: window.__.sync(I18NKeys.options.editPages.metadata.homepageURL), website: window.__.sync(I18NKeys.options.editPages.metadata.website), source: window.__.sync(I18NKeys.options.editPages.metadata.source), icon: window.__.sync(I18NKeys.options.editPages.metadata.icon), iconURL: window.__.sync(I18NKeys.options.editPages.metadata.iconURL), defaulticon: window.__.sync(I18NKeys.options.editPages.metadata.defaulticon), icon64: window.__.sync(I18NKeys.options.editPages.metadata.icon64), icon64URL: window.__.sync(I18NKeys.options.editPages.metadata.icon64URL), updateURL: window.__.sync(I18NKeys.options.editPages.metadata.updateURL), downloadURL: window.__.sync(I18NKeys.options.editPages.metadata.downloadURL), supportURL: window.__.sync(I18NKeys.options.editPages.metadata.supportURL), include: window.__.sync(I18NKeys.options.editPages.metadata.include), match: window.__.sync(I18NKeys.options.editPages.metadata.match), exclude: window.__.sync(I18NKeys.options.editPages.metadata.exclude), require: window.__.sync(I18NKeys.options.editPages.metadata.require), resource: window.__.sync(I18NKeys.options.editPages.metadata.resource), connect: window.__.sync(I18NKeys.options.editPages.metadata.connect), 'run-at': window.__.sync(I18NKeys.options.editPages.metadata.runAt), 'run_at': window.__.sync(I18NKeys.options.editPages.metadata.runAt), grant: window.__.sync(I18NKeys.options.editPages.metadata.grant), noframes: window.__.sync(I18NKeys.options.editPages.metadata.noframes), CRM_contentTypes: window.__.sync(I18NKeys.options.editPages.metadata.CRMContentTypes), CRM_launchMode: window.__.sync(I18NKeys.options.editPages.metadata.CRMLaunchMode), CRM_stylesheet: window.__.sync(I18NKeys.options.editPages.metadata.CRMStylesheet), CRM_toggle: window.__.sync(I18NKeys.options.editPages.metadata.CRMToggle), CRM_defaultOn: window.__.sync(I18NKeys.options.editPages.metadata.CRMDefaultOn), CRM_libraries: window.__.sync(I18NKeys.options.editPages.metadata.CRMLibraries), license: window.__.sync(I18NKeys.options.editPages.metadata.license), preprocessor: window.__.sync(I18NKeys.options.editPages.metadata.preprocessor), var: window.__.sync(I18NKeys.options.editPages.metadata.var) }; } abstract class EventEmitter<PubL extends string, PriL extends string> { private _privateListenerMap: { [key in PriL]: ((...params: any[]) => any)[]; } = {} as any; private _publicListenerMap: { [key in PubL]: ((...params: any[]) => any)[]; } = {} as any; private _insertOnce<T extends (...args: any[]) => any>(arr: T[], value: T) { const self = (((...args: any[]) => { arr.slice(arr.indexOf(self, 1)); return value(...args); }) as any); arr.push(self); } private _assertKeyExists<E extends keyof T, T extends { [key: string]: any; }>(key: E, value: T) { if (!(key in value)) { value[key] = [] as T[E]; } } protected _listen<E extends PriL>(event: E, listener: (...args: any[]) => any, once: boolean = false) { this._assertKeyExists(event, this._privateListenerMap); if (once) { this._insertOnce(this._privateListenerMap[event], listener); } else { this._privateListenerMap[event].push(listener); } } public listen<E extends PubL>(event: E, listener: (...args: any[]) => any, once: boolean = false) { this._assertKeyExists(event, this._publicListenerMap); if (once) { this._insertOnce(this._publicListenerMap[event], listener); } else { this._publicListenerMap[event].push(listener); } } protected _clearListeners<E extends PubL|PriL>(event: E) { if (event in this._publicListenerMap) { delete this._publicListenerMap[event as PubL]; } if (event in this._privateListenerMap) { delete this._privateListenerMap[event as PriL]; } } protected _firePrivate<R, E extends PriL = PriL>(event: E, params: any[]): R[] { return !(event in this._privateListenerMap) ? [] : this._privateListenerMap[event].map((listener) => { return listener(...params); }); } protected _firePublic<R, E extends PubL>(event: E, params: any[]): R[] { return !(event in this._publicListenerMap) ? [] : this._publicListenerMap[event].map((listener) => { return listener(...params); }); } } abstract class MonacoTypeHandler<PubL extends string = '_', PriL extends string = '_'> extends EventEmitter<PubL, PriL> { /** * The editor that is currently being used */ protected _editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor; /** * The model that is currently being used in the editor */ protected _model: monaco.editor.IModel; public abstract destroy(): void; constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(); this._editor = editor; this._model = model; } protected _isTextarea() { return '__textarea' in this._editor; } } abstract class MonacoEditorEventHandler<PubL extends string = '_', PriL extends string = '_'> extends MonacoTypeHandler<PubL, PriL|'onLoad'|'onModelContentChange'> { /** * Any listeners that need to be disposed of eventually */ protected _disposables: { dispose(): void; }[] = []; /** * The editor that is currently being used */ protected _editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor; /** * The model that is currently being used in the editor */ protected _model: monaco.editor.IModel; constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(editor, model); if (this._isTextarea()) { return; } this._onCreate(); window.setTimeout(() => { if (this._model.isDisposed()) { return; } this._firePrivate('onLoad', []); this._clearListeners('onLoad'); }, 2500); } protected static _genDisposable<T>(fn: () => T, onDispose: (args: T) => void) { const res = fn(); return { dispose: () => { onDispose(res) } } } protected _isDiff(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor): editor is monaco.editor.IDiffEditor { if ('__textarea' in editor) { return '__diff' in editor; } return !('onDidChangeModel' in this._editor); } private _onCreate() { this.destroy(); this._disposables.push(this._model.onDidChangeContent((e) => { this._firePrivate('onModelContentChange', [e]); })); } destroy() { this._disposables = this._disposables.filter((listener) => { listener.dispose(); }); } } export interface MetaBlock { content: CRM.MetaTags; indexes: { start: monaco.Position; end: monaco.Position; }[]; } abstract class MonacoEditorMetaBlockMods<PubL extends string = '_', PriL extends string = '_'> extends MonacoEditorEventHandler<PubL|'metaChange', PriL|'decorate'|'shouldDecorate'> { /** * Whether the meta block could have changed since the last call */ private _hasMetaBlockChanged: boolean = true; /** * The start, end and contents of the meta block */ private _metaBlock: MetaBlock|null; /** * The decorations currently being used */ private _decorations: string[] = []; /** * Whether to disable the highlight of userscript metadata at the top of the file */ private _isMetaDataHighlightDisabled: boolean = false; protected static readonly _metaTagProvider: monaco.languages.CompletionItemProvider = { provideCompletionItems: (model, position) => { const word = model.getWordUntilPosition(position); const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn }; console.log('returning userscript') return { suggestions: [{ label: '==UserScript==', kind: monaco.languages.CompletionItemKind.Snippet, insertText: '// ==UserScript==\n// ==/UserScript==', detail: window.__.sync( I18NKeys.options.editPages.monaco.scriptStart), documentation: window.__.sync( I18NKeys.options.editPages.monaco.startTagUserscript), range }, { label: '==/UserScript==', kind: monaco.languages.CompletionItemKind.Snippet, insertText: '// ==/UserScript==', detail: window.__.sync( I18NKeys.options.editPages.monaco.scriptEnd), documentation: window.__.sync( I18NKeys.options.editPages.monaco.endTagUserscript), range }, { label: '==UserStyle==', kind: monaco.languages.CompletionItemKind.Snippet, insertText: '// ==UserStyle==\n// ==/UserStyle==', detail: window.__.sync( I18NKeys.options.editPages.monaco.styleStart), documentation: window.__.sync( I18NKeys.options.editPages.monaco.startTagUserstyle), range }, { label: '==/UserStyle==', kind: monaco.languages.CompletionItemKind.Snippet, insertText: '// ==/UserStyle==', detail: window.__.sync( I18NKeys.options.editPages.monaco.styleEnd), documentation: window.__.sync( I18NKeys.options.editPages.monaco.endTagUserstyle), range }], incomplete: true } } } private static _containsPosition(metablock: MetaBlock, position: monaco.Position): boolean { for (const { start, end } of metablock.indexes) { if (new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column) .containsPosition(position)) { return true; } } return false; } protected static readonly _metaKeyProvider: monaco.languages.CompletionItemProvider = { provideCompletionItems: (model, position) => { const word = model.getWordUntilPosition(position); const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn }; const lineRange = new monaco.Range(position.lineNumber, 0, position.lineNumber, position.column); const currentLineText = model.getValueInRange(lineRange); const metaBlock = (model as any)._metaBlock as MetaBlock; console.log('checking metablock', metaBlock) if (!metaBlock || MonacoEditorMetaBlockMods._containsPosition(metaBlock, position)) { const descriptions = getMetaDescriptions(); return { incomplete: true, suggestions: Object.getOwnPropertyNames(descriptions).map((key: keyof typeof descriptions) => { const description = descriptions[key]; return { label: `@${key}`, kind: monaco.languages.CompletionItemKind.Property, insertText: currentLineText.indexOf('@') > -1 ? `@${key}` : key, detail: window.__.sync( I18NKeys.options.editPages.monaco.metaKey), documentation: description, range } }) }; } return { suggestions: [], incomplete: true } } } constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(editor, model); if (this._isTextarea()) { return; } this._attachListeners(); } private _attachListeners() { this._listen('onLoad', () => { this._doModelUpdate(); }); this._listen('onModelContentChange', () => { this._hasMetaBlockChanged = true; this._doModelUpdate(); }); this._listen('shouldDecorate', (changeEvent: monaco.editor.IModelContentChangedEvent) => { if (this._isMetaDataHighlightDisabled) { return false; } let force: boolean = false; if (!this._metaBlock) { if (this.getMetaBlock()) { force = true; } else { return false; } } if (!force && (!changeEvent || !changeEvent.isRedoing) && (!changeEvent || changeEvent.changes.filter((change) => { return this._isInMetaRange(change.range); }).length === 0)) { return false; } return true; }); this._listen('decorate', () => { if (this._isMetaDataHighlightDisabled) { return []; } return this._userScriptGutterHighlightChange(); }); this._listen('decorate', () => { if (this._isMetaDataHighlightDisabled) { return []; } return this._userScriptHighlightChange(); }); if (window.app) { this._isMetaDataHighlightDisabled = window.app.settings.editor.disabledMetaDataHighlight; } else { this._isMetaDataHighlightDisabled = window.installPage.settings.editor.disabledMetaDataHighlight; } if (!this._isDiff(this._editor)) { this._disposables.push(this._editor.addAction({ id: 'disable-metadata-highlight', label: window.__.sync(I18NKeys.options.editPages.monaco.disableMeta), run: () => { this._isMetaDataHighlightDisabled = true; } })); }; if (!this._isDiff(this._editor)) { this._disposables.push(this._editor.addAction({ id: 'enable-metadata-highlight', label: window.__.sync(I18NKeys.options.editPages.monaco.enableMeta), run: () => { this._isMetaDataHighlightDisabled = false; } })); } this._defineMetaOnModel(); this._listen('onModelContentChange', (changeEvent: monaco.editor.IModelContentChangedEvent) => { this._hasMetaBlockChanged = true; if (this._shouldUpdateDecorations(changeEvent)) { this._doModelUpdate(); } }); } private _defineMetaOnModel() { if ('_metaBlock' in this._model) { return; } Object.defineProperty(this._model, '_metaBlock', { get: () => { return this.getMetaBlock(); } }); } private static readonly _userScriptStart = '==UserScript=='; private static readonly _userStyleStart = '==UserStyle=='; private static readonly _userScriptEnd = '==/UserScript=='; private static readonly _userStyleEnd = '==/UserStyle=='; private _getMetaOutlines(): { start: monaco.Position; end: monaco.Position; }[] { const editorContent = this._model.getValue(); if ((editorContent.indexOf(MonacoEditorMetaBlockMods._userScriptStart) === -1 || editorContent.indexOf(MonacoEditorMetaBlockMods._userScriptEnd) === -1) && (editorContent.indexOf(MonacoEditorMetaBlockMods._userStyleStart) === -1 || editorContent.indexOf(MonacoEditorMetaBlockMods._userStyleEnd) === -1)) { return (this._metaBlock = null); } const lines = editorContent.split('\n'); const indexes: { start: monaco.Position; end: monaco.Position; }[] = []; const state: { start: monaco.Position; end: monaco.Position; } = { start: null, end: null } for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { let line = lines[lineIndex]; if (line.indexOf(MonacoEditorMetaBlockMods._userScriptStart) !== -1 || line.indexOf(MonacoEditorMetaBlockMods._userStyleStart) !== -1) { let index = line.indexOf(MonacoEditorMetaBlockMods._userScriptStart); if (index === -1) { index = line.indexOf(MonacoEditorMetaBlockMods._userStyleStart); } if (!state.start) { state.start = new monaco.Position(lineIndex + 1, index); } } if (line.indexOf(MonacoEditorMetaBlockMods._userScriptEnd) !== -1 || line.indexOf(MonacoEditorMetaBlockMods._userStyleEnd) !== -1) { let index = line.indexOf(MonacoEditorMetaBlockMods._userScriptEnd); if (index === -1) { index = line.indexOf(MonacoEditorMetaBlockMods._userStyleEnd); } if (!state.end) { state.end = new monaco.Position(lineIndex + 1, index + MonacoEditorMetaBlockMods._userScriptEnd.length); } indexes.push({ start: state.start, end: state.end }); state.start = state.end = null; } } if (indexes.length === 0) { this._metaBlock = null; } return indexes; } private static readonly _metaPropRegex = /@(\w+)(\s+)(.+)?/; private _getMetaContent(outlines: { start: monaco.Position; end: monaco.Position; }[]): CRM.MetaTags { const content = this._model.getValue(); const tags: CRM.MetaTags = {}; const regex = MonacoEditorMetaBlockMods._metaPropRegex; const lines = content.split('\n'); const state: { tag: string; content: string; } = { tag: null, content: null }; for (const { start, end } of outlines) { for (let i = start.lineNumber; i < end.lineNumber; i++) { const line = lines[i]; const matches = regex.exec(line); if (matches) { if (state.tag && state.content) { if (state.tag in tags) { tags[state.tag].push(state.content); } else { tags[state.tag] = [state.content]; } state.tag = state.content = null; } const key = matches[1]; const value = matches[3]; if (!key || !value) { continue; } state.tag = key; state.content = value; } else { state.content += line; } } } return tags; } private _isDifferent(prev: MetaBlock, current: MetaBlock): boolean { if (!prev || !current) { return true; } if (prev.indexes.length !== current.indexes.length) { return false; } for (let i = 0; i < prev.indexes.length; i++) { const prevIndex = prev.indexes[i]; const currentIndex = current.indexes[i]; if (!prevIndex.start.equals(currentIndex.start) || !prevIndex.end.equals(currentIndex.end)) { return false; } } const keys: string[] = []; for (let key in prev) { if (!(key in current)) { return false; } keys.push(key); } for (let key in current) { if (!(key in prev)) { return false; } if (keys.indexOf(key) === -1) { keys.push(key); } } for (let key of keys) { const prevVal = prev.content[key as keyof typeof prev]; const currentVal = current.content[key as keyof typeof current]; const prevIsArray = Array.isArray(prevVal); const currentIsArray = Array.isArray(currentVal); if (prevIsArray !== currentIsArray) { return false; } if (prevIsArray) { for (let value of prevVal as any[]) { if (currentVal.indexOf(value) === -1) { return false; } } for (let value of currentVal as any[]) { if (prevVal.indexOf(value) === -1) { return false; } } } else if (prevVal !== currentVal) { return false; } } return true; } public getMetaBlock(): MetaBlock { if (!this._hasMetaBlockChanged) { return this._metaBlock; } let prevBlock = this._metaBlock; const outlines = this._getMetaOutlines(); if (!outlines) { return null; } const metaContent = this._getMetaContent(outlines); const metaBlock = this._metaBlock = { indexes: outlines, content: metaContent, }; if (this._isDifferent(prevBlock, metaBlock)) { if (!prevBlock) { prevBlock = { indexes: [{ start: new monaco.Position(0, 0), end: new monaco.Position(0, 0) }], content: {}, } } this._firePublic('metaChange', [prevBlock, metaBlock]); } return metaBlock; } private _getKeyDescription(metaKey: string) { const descriptions = getMetaDescriptions(); if (metaKey in descriptions) { return window.__.sync(I18NKeys.options.editPages.monaco.keyDescription, metaKey, descriptions[metaKey as keyof typeof descriptions]); } return window.__.sync(I18NKeys.options.editPages.monaco.keyDescriptionUnknown, metaKey); } private _isInMetaRange(range: monaco.IRange) { if (!this._metaBlock) { return false; } for (const { start, end } of this._metaBlock.indexes) { if (monaco.Range.areIntersectingOrTouching({ startColumn: start.column, startLineNumber: start.lineNumber, endColumn: end.column, endLineNumber: end.lineNumber }, range)) { return true; } } return false; } private _userScriptGutterHighlightChange(): monaco.editor.IModelDeltaDecoration[] { if (!this._getMetaOutlines()) { return []; } return this.getMetaBlock().indexes.map(({start, end}) => { return { range: new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column), options: { isWholeLine: true, linesDecorationsClassName: 'userScriptGutterHighlight', stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges } } }); } private _userScriptHighlightChange() { const content = this._model.getValue(); if (!this.getMetaBlock()) { return null; } const regex = MonacoEditorMetaBlockMods._metaPropRegex; const lines = content.split('\n'); const newDecorations: monaco.editor.IModelDeltaDecoration[] = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const match = regex.exec(line); if (match) { const key = match[1]; const value = match[3]; const keyStartIndex = key ? line.indexOf(key) : 0; const keyEnd = key ? (keyStartIndex + key.length) : 0; const monacoLineNumber = i + 1; if (key) { newDecorations.push({ range: new monaco.Range(monacoLineNumber, keyStartIndex, monacoLineNumber, keyEnd + 1), options: { stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, inlineClassName: 'userScriptKeyHighlight', hoverMessage: { value: this._getKeyDescription(key), isTrusted: true }, isWholeLine: false } }); } if (value) { const valueStartIndex = line.slice(keyEnd).indexOf(value) + keyEnd; const valueStartOffset = valueStartIndex + 1; newDecorations.push({ range: new monaco.Range(monacoLineNumber, valueStartOffset, monacoLineNumber, valueStartOffset + value.length), options: { stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, inlineClassName: 'userScriptValueHighlight', hoverMessage: { value: window.__.sync( I18NKeys.options.editPages.monaco.valueForKey, value, key), isTrusted: true }, isWholeLine: false } }); } } } return newDecorations; } private _doDecorationUpdate(decorations: monaco.editor.IModelDeltaDecoration[]) { if (!this._isDiff(this._editor)) { if (this._editor.getModel() === this._model) { this._decorations = this._editor.deltaDecorations(this._decorations, decorations); } else { this._decorations = this._editor.deltaDecorations(this._decorations, []); } } } private _shouldUpdateDecorations(changeEvent: monaco.editor.IModelContentChangedEvent): boolean { const results = this._firePrivate<boolean>('shouldDecorate', [changeEvent]); if (results.length > 1) { return results.reduce((left, right) => { return left || right; }); } else if (results.length === 1) { return results[0]; } else { return false; } } private _formatDecorations(decorations: monaco.editor.IModelDeltaDecoration[][]) { if (decorations.length === 0) { return []; } else if (decorations.length === 1) { return decorations[0]; } else { return decorations.reduce((prev, current) => { return prev.concat(current); }); } } private _doModelUpdate() { const decorations = this._firePrivate<monaco.editor.IModelDeltaDecoration[]>('decorate', []) .filter(decorationArr => decorationArr !== null); this._doDecorationUpdate(this._formatDecorations(decorations)); } } export class MonacoEditorScriptMetaMods<PubL extends string = '_', PriL extends string = '_'> extends MonacoEditorMetaBlockMods<PubL, PriL> { metaBlockChanged: boolean = true; constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(editor, model); if (this._isTextarea()) { return; } MonacoEditorHookManager.Completion.register('javascript', MonacoEditorMetaBlockMods._metaTagProvider); MonacoEditorHookManager.Completion.register('javascript', MonacoEditorMetaBlockMods._metaKeyProvider); MonacoEditorHookManager.Completion.register('typescript', MonacoEditorMetaBlockMods._metaTagProvider); MonacoEditorHookManager.Completion.register('typescript', MonacoEditorMetaBlockMods._metaKeyProvider); this._disposables.push({ dispose: () => { MonacoEditorHookManager.Completion.clearAll(); } }); } static getSettings(): monaco.editor.IEditorOptions { return { } } } class MonacoEditorCSSMetaMods<PubL extends string = '_', PriL extends string = '_'> extends MonacoEditorMetaBlockMods<PubL, PriL> { /** * Whether the highlighting is enabled */ private _underlineDisabled: boolean = false; /** * The currently used stylesheet rules, in order to compare to possible changes */ private _currentStylesheetRules: string = ''; /** * All lines currently containing colors */ private _styleLines: number[] = []; constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(editor, model); if (this._isTextarea()) { return; } MonacoEditorHookManager.Completion.register('css', MonacoEditorMetaBlockMods._metaTagProvider); MonacoEditorHookManager.Completion.register('css', MonacoEditorMetaBlockMods._metaKeyProvider); MonacoEditorHookManager.Completion.register('less', MonacoEditorMetaBlockMods._metaTagProvider); MonacoEditorHookManager.Completion.register('less', MonacoEditorMetaBlockMods._metaKeyProvider); this._disposables.push({ dispose: () => { MonacoEditorHookManager.Completion.clearAll(); } }); this._listen('shouldDecorate', (event: monaco.editor.IModelContentChangedEvent) => { if (event.isFlush) { return true; } for (let change of event.changes) { const lines = [change.range.startLineNumber]; if (change.range.endLineNumber !== change.range.startLineNumber) { lines.push(change.range.endLineNumber); } for (let line of lines) { if (this._styleLines.indexOf(line) > -1) { return true; } const lineContent = this._model.getLineContent(line); const cssRuleParts = this._getCssRuleParts(lineContent); for (let cssRulePart of cssRuleParts) { if (this._findColor(0, cssRulePart.text)) { return true; } } } } return false; }); this._listen('decorate', () => { return this._highlightColors(); }); this._disposables.push(MonacoEditorEventHandler._genDisposable(() => { return window.setInterval(() => { if (!this._underlineDisabled && window.app.item) { this._markUnderlines(); } }, 50); }, (timer: number) => { window.clearInterval(timer); })); if (window.app) { this._underlineDisabled = window.app.settings.editor.cssUnderlineDisabled; } else { this._underlineDisabled = window.installPage.settings.editor.cssUnderlineDisabled; } if (!this._isDiff(this._editor)) { this._disposables.push(this._editor.addAction({ id: 'disable-css-underline', label: window.__.sync( I18NKeys.options.editPages.monaco.disableUnderline), run: () => { this._underlineDisabled = true; } })); this._disposables.push(this._editor.addAction({ id: 'enable-css-underline', label: window.__.sync( I18NKeys.options.editPages.monaco.enableUnderline), run: () => { this._underlineDisabled = false; } })); } } private _getCssRuleParts(str: string) { let match: RegExpExecArray = null; const ruleParts: { text: string; start: number; }[] = []; while ((match = MonacoEditorCSSMetaMods._cssRuleRegex.exec(str))) { const startIndex = str.indexOf(match[0]); const endIndex = startIndex + match[0].length; ruleParts.push({ text: match[0], start: startIndex }); str = str.slice(0, startIndex) + this._stringRepeat('-', match[0].length) + str.slice(endIndex); } return ruleParts; } private static readonly _cssRuleRegex = /:(\s*)?(.*)(\s*);/; private static readonly _cssColorNames = [ 'AliceBlue', 'AntiqueWhite', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque', 'Black', 'BlanchedAlmond', 'Blue', 'BlueViolet', 'Brown', 'BurlyWood', 'CadetBlue', 'Chartreuse', 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan', 'DarkBlue', 'DarkCyan', 'DarkGoldenRod', 'DarkGray', 'DarkGrey', 'DarkGreen', 'DarkKhaki', 'DarkMagenta', 'DarkOliveGreen', 'DarkOrange', 'DarkOrchid', 'DarkRed', 'DarkSalmon', 'DarkSeaGreen', 'DarkSlateBlue', 'DarkSlateGray', 'DarkSlateGrey', 'DarkTurquoise', 'DarkViolet', 'DeepPink', 'DeepSkyBlue', 'DimGray', 'DimGrey', 'DodgerBlue', 'FireBrick', 'FloralWhite', 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod', 'Gray', 'Grey', 'Green', 'GreenYellow', 'HoneyDew', 'HotPink', 'IndianRed ', 'Indigo ', 'Ivory', 'Khaki', 'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue', 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey', 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue', 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime', 'LimeGreen', 'Linen', 'Magenta', 'Maroon', 'MediumAquaMarine', 'MediumBlue', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen', 'MediumTurquoise', 'MediumVioletRed', 'MidnightBlue', 'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite', 'Navy', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed', 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple', 'RebeccaPurple', 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Salmon', 'SandyBrown', 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue', 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White', 'WhiteSmoke', 'Yellow', 'YellowGreen' ].map(str => str.toLowerCase()).sort((a, b) => { return b.length - a.length }); private static readonly _hexRegex = /#((([a-f]|[A-F]){8})|(([a-f]|[A-F]){6})|(([a-f]|[A-F]){3}))[^a-f|A-F]/; private static readonly _rgbRegex = /rgb\((\d{1,3}),(\s*)?(\d{1,3}),(\s*)?(\d{1,3})\)/; private static readonly _rgbaRegex = /rgb\((\d{1,3}),(\s*)?(\d{1,3}),(\s*)?(\d{1,3})\),(\s*)?(\d{1,3})\)/; private _findColor(lineNumber: number, str: string, offset: number = 0): { pos: monaco.Range; color: string; }|null { for (let color of MonacoEditorCSSMetaMods._cssColorNames) { let index: number = -1; if ((index = str.toLowerCase().indexOf(color)) > -1) { return { pos: new monaco.Range(lineNumber + 1, index + offset + 1, lineNumber + 1, index + offset + color.length + 1), color: color } } } let match: RegExpMatchArray = null; if ((match = MonacoEditorCSSMetaMods._hexRegex.exec(str))) { const index = str.indexOf(match[1]); return { pos: new monaco.Range(lineNumber + 1, index + offset + 1, lineNumber + 1, index + offset + match[1].length + 1), color: match[1] } } if ((match = MonacoEditorCSSMetaMods._rgbRegex.exec(str))) { const index = str.indexOf(match[0]); return { pos: new monaco.Range(lineNumber + 1, index + offset + 1, lineNumber + 1, index + offset + match[0].length + 1), color: match[0] } } if ((match = MonacoEditorCSSMetaMods._rgbaRegex.exec(str))) { const index = str.indexOf(match[0]); return { pos: new monaco.Range(lineNumber + 1, index + offset + 1, lineNumber + 1, index + offset + match[0].length + 1), color: match[0] } } return null; } private _stringRepeat(str: string, amount: number) { let result: string = ''; for (let i = 0; i < amount; i++) { result = result + str; } return result; } private _getColors() { const content = this._model.getValue(); const lines = content.split('\n'); const colors: { pos: monaco.Range; color: string; }[] = []; for (let i = 0; i < lines.length; i++) { let line = lines[i]; let result: { pos: monaco.Range; color: string; } = null; const cssRuleParts = this._getCssRuleParts(line); for (let { text, start } of cssRuleParts) { if (result = this._findColor(i, text, start)) { colors.push(result); } } } return colors; } private _highlightColors() { const colors = this._getColors(); this._styleLines = colors.map(color => color.pos.startLineNumber); return colors.map((color) => { return { range: color.pos, options: { stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, beforeContentClassName: `userScriptColorUnderline color${color.color}` } } }); } private _markUnderlines() { const newRules: [string, string][] = []; let newRulesString = ''; if (this._editor.getModel() === this._model) { const underlinables = this._editor.getDomNode().querySelectorAll('.userScriptColorUnderline'); Array.prototype.slice.apply(underlinables).forEach((underlineable: HTMLElement) => { for (let i = 0; i < underlineable.classList.length; i++) { if (underlineable.classList[i].indexOf('color') === 0) { let color = underlineable.classList[i].slice(5); let className = underlineable.classList[i]; newRules.push([`.${className}::before`, `background-color: ${color}`]) newRulesString += `${className}${color}`; } } }); if (newRulesString === this._currentStylesheetRules) { return; } const stylesheet = (window.app.item.type === 'script' ? window.scriptEdit : window.stylesheetEdit) .$.editor._getStylesheet(); const sheet = stylesheet.sheet as CSSStyleSheet; while (sheet.rules.length !== 0) { sheet.deleteRule(0); } this._currentStylesheetRules = newRulesString; newRules.forEach(([selector, value]: [string, string]) => { sheet.addRule(selector, value); }); } } static getSettings(): monaco.editor.IEditorOptions { return {}; } } interface JSONSchemaMeta { title?: string; description?: string; anyOf?: JSONSchema[]; allOf?: JSONSchema[]; oneOf?: JSONSchema[]; not?: JSONSchema; } interface JSONSchemaEnum extends JSONSchemaMeta { enum: (string|number|boolean)[]; } interface JSONSchemaString extends JSONSchemaMeta { default?: string; enum?: string[]; type: 'string'; minLength?: number; maxLength?: number; pattern?: string; format?: string; } interface JSONSchemaNumber extends JSONSchemaMeta { default?: number; enum?: number[]; type: 'number'|'integer'; multipleOf?: number; minimum?: number; maximum?: number; exclusiveMinimum?: boolean; exclusiveMaximum?: boolean; } interface JSONSchemaBoolean extends JSONSchemaMeta { default?: boolean; enum?: boolean[]; type: 'boolean'; } interface JSONSchemaArray extends JSONSchemaMeta { type: 'array'|('array'|'null')[]; items: JSONSchema|JSONSchema[]; additionalItems?: false|JSONSchema; minItems?: number; maxItems?: number; uniqueItems?: boolean; } interface JSONSchemaObjectBase extends JSONSchemaMeta { properties?: { [key: string]: JSONSchema; } additionalProperties?: false|JSONSchema; required?: string[]; minProperties?: number; maxProperties?: number; dependencies?: { [key: string]: string[]|JSONSchemaObjectBase; }; patternProperties?: { [pattern: string]: JSONSchema; } } interface JSONSchemaObject extends JSONSchemaObjectBase { type: 'object'; } interface JSONSchemaNull extends JSONSchemaMeta { type: 'null'; } interface JSONSchemaMultiType extends JSONSchemaMeta { type: ('number'|'string'|'boolean'|'object'|'array'|'null')[]; } type JSONSchemaTypedef = JSONSchemaString|JSONSchemaNumber|JSONSchemaBoolean| JSONSchemaArray|JSONSchemaObject|JSONSchemaNull|JSONSchemaMultiType; /** * Rough JSON schema typing */ type JSONSchema = JSONSchemaTypedef|JSONSchemaEnum; class MonacoEditorJSONOptionsMods<PubL extends string = '_', PriL extends string = '_'> extends MonacoEditorEventHandler<PubL, PriL> { constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel) { super(editor, model); if (this._isTextarea()) { return; } const value = model.getValue() as EncodedString<CRM.Options>; if (!this._findSchema(value)) { model.setValue(this._addSchemaKey(value)); } MonacoEditorJSONOptionsMods.enableSchema(); this._disposables.push({ dispose() { MonacoEditorJSONOptionsMods.disableSchema(); } }); } private _addSchemaKey(options: string): string { const str1 = ` "$schema": "crm-settings.json"`; if (options.split('\n').join('').trim().length === 0) { //No content return `{\n${str1}\n}`; } const lines = options.split('\n'); for (const i in lines) { const line = lines[i]; if (line.trim().indexOf('{') === 0) { //First line if (line.trim().length > 1) { //More text on this line lines[i] = '{'; lines.splice(~~i + 1, 0, str1, line.trim().slice(1)); } else { lines.splice(~~i + 1, 0, str1); } } } return lines.join('\n'); } private _findSchema(str: string) { //Remove any comments str = str.replace(/\/\*.*?\*\//g, ''); const lines = str.split('\n'); for (const i in lines) { if (lines[i].indexOf('//') > -1) { let inStr = false; for (let index = 0; index < lines[i].length; index++) { const char = lines[i][index] if (char === '\\') { continue; } else if (char === '"') { inStr = !inStr; } else if (!inStr && char === '/' && lines[i][index + 1] === '/') { //Ignore the rest of this line lines[i] = lines[i].slice(0, index); } } } } try { const parsed = JSON.parse(str); if ('$schema' in parsed) { return true; } else { return false; } } catch { return true; } } static disableSchema() { monaco.languages.json.jsonDefaults.setDiagnosticsOptions({ allowComments: true }); } static enableSchema() { const schema: JSONSchema = { type: 'object', properties: { '$schema': { type: 'string', enum: ['crm-settings.json'] } }, additionalProperties: { title: window.__.sync(I18NKeys.options.editPages.monaco.optionName), type: 'object', oneOf: [{ type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.numberOption), type: 'string', enum: ['number'] }, minimum: { title: window.__.sync( I18NKeys.options.editPages.monaco.minValue), type: 'number' }, maximum: { title: window.__.sync( I18NKeys.options.editPages.monaco.maxValue), type: 'number' }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, defaultValue: { title: window.__.sync( I18NKeys.options.editPages.monaco.defaultValue), type: 'number' }, value: { title: window.__.sync( I18NKeys.options.editPages.monaco.value), description: window.__.sync( I18NKeys.options.editPages.monaco.valueExpanded), type: ['number', 'null'] } } }, { type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.stringOption), type: 'string', enum: ['string'] }, maxLength: { title: window.__.sync( I18NKeys.options.editPages.monaco.maxLength), type: 'number' }, format: { title: window.__.sync( I18NKeys.options.editPages.monaco.format), type: 'string' }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, defaultValue: { title: window.__.sync( I18NKeys.options.editPages.monaco.defaultValue), type: 'string' }, value: { title: window.__.sync( I18NKeys.options.editPages.monaco.value), description: window.__.sync( I18NKeys.options.editPages.monaco.valueExpanded), type: ['string', 'null'] } } }, { type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.choiceOption), type: 'string', enum: ['choice'] }, selected: { title: window.__.sync( I18NKeys.options.editPages.monaco.selected), type: 'number' }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, values: { title: window.__.sync( I18NKeys.options.editPages.monaco.values), type: 'array', items: { type: ['string', 'number'] } } } }, { type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.colorOption), type: 'string', enum: ['color'] }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, defaultValue: { title: window.__.sync( I18NKeys.options.editPages.monaco.defaultValue), type: 'string' }, value: { title: window.__.sync( I18NKeys.options.editPages.monaco.value), description: window.__.sync( I18NKeys.options.editPages.monaco.valueExpanded), type: ['string', 'null'] } } }, { type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.booleanOption), type: 'string', enum: ['boolean'] }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, defaultValue: { title: window.__.sync( I18NKeys.options.editPages.monaco.defaultValue), type: 'boolean' }, value: { title: window.__.sync( I18NKeys.options.editPages.monaco.value), description: window.__.sync( I18NKeys.options.editPages.monaco.valueExpanded), type: ['boolean', 'null'] } } }, { type: 'object', properties: { type: { title: window.__.sync( I18NKeys.options.editPages.monaco.arrayOption), type: 'string', enum: ['array'] }, maxItems: { title: window.__.sync( I18NKeys.options.editPages.monaco.maxItems), type: 'number' }, items: { title: window.__.sync( I18NKeys.options.editPages.monaco.items), type: 'string', enum: ['string', 'number'] }, descr: { title: window.__.sync( I18NKeys.options.editPages.monaco.descr), type: 'string' }, defaultValue: { title: window.__.sync( I18NKeys.options.editPages.monaco.defaultValue), type: 'array', items: { type: ['string', 'number'] } }, value: { title: window.__.sync( I18NKeys.options.editPages.monaco.value), description: window.__.sync( I18NKeys.options.editPages.monaco.valueExpanded), type: ['array', 'null'], items: { type: ['string', 'number'] } } }, required: ['items'] }] } }; monaco.languages.json.jsonDefaults.setDiagnosticsOptions({ allowComments: false, schemas: [{ uri: 'crm-settings.json', schema: schema }], validate: true }) } static getSettings(): monaco.editor.IEditorOptions { return { } } } export class MonacoEditorTSLibrariesMetaMods<PubL extends string = '_', PriL extends string = '_'> extends MonacoEditorScriptMetaMods<PubL, PriL> { /** * The libraries belonging to this configuration */ private _libraries: CRM.Library[] = []; /** * The node this configuration is based on */ private _node: CRM.ScriptNode; /** * Whether to use background libs */ private _isBackground: boolean; /** * The disposables generated by registering the libraries */ private _registrationDisposables: monaco.IDisposable[] = []; constructor(editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel, { node, isBackground }: { node: CRM.ScriptNode; isBackground: boolean; }) { super(editor, model); this._node = node; this._isBackground = isBackground; if (this._isTextarea()) { return; } this._enable(); if (!this._isDiff(this._editor)) { this._disposables.push(this._editor.onDidChangeModel((e) => { if (e.newModelUrl === model.uri) { this._enable(); } else { this._disable(); } })); } this._disposables.push({ dispose: () => { this._registrationDisposables.forEach((reg) => { reg.dispose(); }); } }); } private async _enable() { this._registrationDisposables = await this._registerLibraries(this._libraries); } private _disable() { this._registrationDisposables.forEach((disposable) => { disposable.dispose(); }); this._registrationDisposables = []; } updateLibraries() { this._libraries = this._getLibraries(this._node, this._isBackground); } private _getLibraries(node: CRM.ScriptNode, isBackground: boolean) { if (isBackground) { return node.value.backgroundLibraries; } return node.value.libraries; } private async _getLibrary(name: string|void): Promise<string|false> { if (!name) { return false; } const data = await browserAPI.storage.local.get<CRM.StorageLocal>(); const libs = data.libraries; for (const lib of libs) { if (lib.name === name) { if (lib.ts && lib.ts.enabled) { return lib.ts.code.compiled; } break; } } return false; } private async _registerLibrary(library: CRM.Library): Promise<monaco.IDisposable> { const content = await this._getLibrary(library.name); if (content === false) { return { dispose: () => {} }; } return monaco.languages.typescript.typescriptDefaults.addExtraLib(content, `${library.name}.ts`); } private async _registerLibraries(libraries: CRM.Library[]) { return await Promise.all(libraries.map(library => this._registerLibrary(library))); } static getSettings() { return {}; } } interface MonacoBaseEditor { updateOptions(options: monaco.editor.IEditorOptions): void; saveViewState(): monaco.editor.IEditorViewState|MonacoModel|{ original: MonacoModel; modified: MonacoModel; }; restoreViewState(state: monaco.editor.ICodeEditorViewState| monaco.editor.IDiffEditorViewState|MonacoModel|{ original: MonacoModel; modified: MonacoModel; }): void; focus(): void; layout(): void; dispose(): void; getDomNode(): HTMLElement getSelected?(): { from: { line: number; char: number; totalChar: number; }; to: { line: number; char: number; totalChar: number; } content: string }; __textarea?: boolean; } interface MonacoStandardEditor extends MonacoBaseEditor { getModel(): MonacoModel; setModel(model: MonacoModel): void; setValue(value: string): void; getValue(options?: { preserveBOM: boolean; lineEnding: string }): string; } interface MonacoDiffEditor extends MonacoBaseEditor { getModel(): { original: MonacoModel; modified: MonacoModel; } setModel(model: { original: MonacoModel; modified: MonacoModel; }): void; __diff?: boolean; } interface MonacoModel { getValue(eol?: monaco.editor.EndOfLinePreference, preserveBOM?: boolean): string; dispose(): void; setValue(value: string): void; } abstract class TextareaEditorBase implements MonacoBaseEditor { protected _textareaElements: HTMLTextAreaElement[]; protected abstract _getValue(): string; protected _models: TextareaModel[] = []; protected _model: TextareaModel|{ original: TextareaModel; modified: TextareaModel; }; protected _baseElements: { container?: HTMLElement; }; __textarea = true; protected abstract _addModelListeners(model: TextareaModel): void; protected abstract _swapToModel(model: TextareaModel|{ original: TextareaModel; modified: TextareaModel; }): void; constructor(container: HTMLElement, private _options: { model?: TextareaModel|{ original: TextareaModel; modified: TextareaModel; }; theme?: 'vs-dark'|'vs'; }) { const { model } = _options; if (model) { this._model = model; if ('original' in model) { this._models = [model.original, model.modified]; } else { this._models = [model]; } } this._genBaseElements(container); if (model) { if ('original' in model) { this._addModelListenersBase(model.original); this._addModelListenersBase(model.modified); } else { this._addModelListenersBase(model); } } } private _genBaseElements(container: HTMLElement) { const textareaContainer = document.createElement('div'); textareaContainer.classList.add('monacoTextareaContainer'); container.appendChild(textareaContainer); this._baseElements = { container: textareaContainer }; } private _totalCharIndexToPosition(content: string, total: number): { line: number; char: number; } { const lines = content.split('\n'); for (const i in lines) { const line = lines[i]; if (total - line.length <= 0) { return { line: ~~i, char: total - line.length } } } return { line: lines.length - 1, char: lines[lines.length - 1].length } } private _addModelListenersBase(model: TextareaModel) { this._models.push(model); this._addModelListeners(model); } protected _assertModelAdded(model: TextareaModel) { if (this._models.indexOf(model) === -1) { this._models.push(model); this._addModelListeners(model); } } protected _genTextarea(): HTMLTextAreaElement { const textarea = document.createElement('textarea'); textarea.classList.add('monacoEditorTextarea'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('autocomplete', 'off'); textarea.setAttribute('autocorrect', 'off'); textarea.setAttribute('autocapitalize', 'off'); if (this._options.theme === 'vs-dark') { textarea.classList.add('dark-theme'); } return textarea; } updateOptions() {} getValue() { return this._getValue(); } saveViewState() { if ('original' in this._model) { return this._model.modified; } return this._model; } restoreViewState(model: TextareaModel|{ original: TextareaModel; modified: TextareaModel; }) { this._swapToModel(model); } focus() { this._textareaElements[0] && this._textareaElements[0].focus(); } layout() {} dispose() { this._textareaElements && this._textareaElements.forEach((el) => { el && el.remove(); }); this._textareaElements = []; this._models.forEach(model => model.dispose()); this._models = []; this._baseElements.container && this._baseElements.container.remove(); this._baseElements = {}; } getDomNode() { return this._baseElements.container; } getSelected(): { from: { line: number; char: number; totalChar: number; }; to: { line: number; char: number; totalChar: number; } content: string } { for (const textarea of this._textareaElements) { if (!textarea) { continue; } const start = textarea.selectionStart; const finish = textarea.selectionEnd; const selection = textarea.value.substring(start, finish); return { from: { ...this._totalCharIndexToPosition(textarea.value, start), totalChar: start }, to: { ...this._totalCharIndexToPosition(textarea.value, finish), totalChar: finish }, content: selection }; } return null; } } class TextareaStandardEditor extends TextareaEditorBase implements MonacoStandardEditor { protected _model: TextareaModel; private _textarea: HTMLTextAreaElement; constructor(container: HTMLElement, options: { model?: TextareaModel; theme?: 'vs-dark'|'vs'; }) { super(container, options); this._genElements(container); this._textarea.addEventListener('keydown', () => { window.setTimeout(() => { this._model.setValue(this._textarea.value, this._textarea); }, 0); }); if (options.model) { this._textarea.value = options.model.getValue(); } } private _genElements(container: HTMLElement) { this._textarea = this._genTextarea(); this._textareaElements = [this._textarea]; container.appendChild(this._textarea); } private _isActiveModel(model: TextareaModel) { return this._model === model; } protected _addModelListeners(model: TextareaModel) { model.listen('change', ({ newValue, src }: { oldValue: string; newValue: string; src: HTMLTextAreaElement; }) => { if (this._isActiveModel(model)) { if (src !== this._textarea) { this._textarea.value = newValue; } } }); } protected _getValue() { return this._model.getValue(); } protected _swapToModel(model: TextareaModel) { this.setModel(model); } getModel(): TextareaModel { return this._model; }; setModel(model: TextareaModel): void { this._assertModelAdded(model); this._model = model; this._textarea.value = model.getValue(); }; setValue(value: string) { this._model.setValue(value); } } class TextareaDiffEditor extends TextareaEditorBase implements MonacoDiffEditor { protected _model: { original: TextareaModel; modified: TextareaModel; }; private _textareas: { original: HTMLTextAreaElement; modified: HTMLTextAreaElement; } __diff = true; constructor(container: HTMLElement, options: { model?: { original: TextareaModel; modified: TextareaModel; } theme?: 'vs-dark'|'vs'; }) { super(container, options); this._genElements(); if (options.model) { this._textareas.original.value = options.model.original.getValue(); this._textareas.modified.value = options.model.modified.getValue(); } } private _genElements() { const originalTextarea = this._genTextarea(); const modifiedTextarea = this._genTextarea(); originalTextarea.classList.add('monacoOriginalTextarea'); modifiedTextarea.classList.add('monacoModifiedTextarea'); this._textareas = { original: originalTextarea, modified: modifiedTextarea }; this._textareaElements = [originalTextarea, modifiedTextarea]; this._baseElements.container.classList.add('diffContainer'); this._baseElements.container.appendChild(originalTextarea); this._baseElements.container.appendChild(modifiedTextarea); } private _setTextareaValues(model: { original: TextareaModel; modified: TextareaModel; }) { this._textareas.original.value = model.original.getValue(); this._textareas.modified.value = model.modified.getValue(); } private _isActiveOriginalModel(model: TextareaModel) { return this._model.original === model; } private _isActiveModifiedModel(model: TextareaModel) { return this._model.modified === model; } protected _addModelListeners(model: TextareaModel) { model.listen('change', ({ newValue, src }: { oldValue: string; newValue: string; src: HTMLTextAreaElement; }) => { if (this._isActiveOriginalModel(model)) { if (src !== this._textareas.original) { this._textareas.original.value = newValue; } } else if (this._isActiveModifiedModel(model)) { if (src !== this._textareas.modified) { this._textareas.modified.value = newValue; } } }); } protected _getValue() { return this._model.modified.getValue(); } protected _swapToModel(model: { original: TextareaModel; modified: TextareaModel; }) { this.setModel(model); } getModel() { return this._model; } setModel(model: { original: TextareaModel; modified: TextareaModel; }) { this._assertModelAdded(model.original); this._assertModelAdded(model.modified); this._model = model; this._setTextareaValues(model); } } class TextareaModel extends EventEmitter<'change', 'none'> implements MonacoModel { private _value: string; constructor(value: string) { super(); this.setValue(value); } getValue(): string { return this._value; } setValue(value: string, src?: HTMLTextAreaElement) { const oldValue = this._value; this._value = value; if (this._value !== oldValue) { this._firePublic('change', [{ oldValue, newValue: this._value, src }]); } } dispose() {} } const monacoEditorProperties: { noSpinner: boolean; } = { noSpinner: { type: Boolean, notify: true, value: false } } as any; enum EditorMode { CSS, JS, TS, JSON, JSON_OPTIONS, JS_META, TS_META, CSS_META, LESS, LESS_META, PLAIN_TEXT } enum CustomEditorModes { TS_LIBRARIES_META } type CustomEditorModeTSLibrariesMeta = { custom: true; mode: CustomEditorModes.TS_LIBRARIES_META; config: { node: CRM.ScriptNode; isBackground: boolean; } } type EditorConfig = EditorMode|CustomEditorModeTSLibrariesMeta; class MOE { static is: string = 'monaco-editor'; static EditorMode: typeof EditorMode = EditorMode; static CustomEditorModes: typeof CustomEditorModes = CustomEditorModes; static properties = monacoEditorProperties; /** * The editor associated with this element */ static editor: MonacoStandardEditor|MonacoDiffEditor; /** * The stylesheet used by the CSS editor */ private static _stylesheet: HTMLStyleElement; /** * The options used on this editor */ static options: monaco.editor.IStandaloneEditorConstructionOptions = null; /** * Whether this is a typescript instance */ private static _isTypescript: boolean; /** * Whether this is a LESS instance */ private static _isLess: boolean; /** * All models currently used in this editor instance */ private static _models: { [id: string]: { models: MonacoModel[]; handlers: MonacoTypeHandler[]; state: monaco.editor.ICodeEditorViewState|monaco.editor.IDiffEditorViewState; editorType: EditorConfig; } }; /** * An array of all elements created from this one */ private static _children: MonacoEditor[]; private static _createInfo: { method: 'create'; options: monaco.editor.IEditorConstructionOptions; override: monaco.editor.IEditorOverrideServices; }|{ method: 'from'; from: MonacoEditor; modelId: string; }|{ method: 'diff'; values: [string, string]; language: 'css'|'javascript'|'typescript'|'json'|'text/plain'; editorType: EditorConfig; options: monaco.editor.IEditorConstructionOptions; override: monaco.editor.IEditorOverrideServices; } = null; /** * Info about a temporary layout change and how to get back */ private static _tempLayoutInfo: { previous: number; current: number; } = null; private static _typeIsCss(editorType: EditorConfig) { switch (editorType) { case EditorMode.CSS: case EditorMode.CSS_META: case EditorMode.LESS: case EditorMode.LESS_META: return true; } return false; } private static _typeIsTS(editorType: EditorConfig) { switch (editorType) { case EditorMode.TS: case EditorMode.TS_META: return true; } return false; } private static _typeIsLESS(editorType: EditorConfig) { switch (editorType) { case EditorMode.LESS: case EditorMode.LESS_META: return true; } return false; } private static _typeIsJS(editorType: EditorConfig) { switch (editorType) { case EditorMode.JS: case EditorMode.JS_META: return true; } return false; } private static _typeIsJSON(editorType: EditorConfig) { switch (editorType) { case EditorMode.JSON: case EditorMode.JSON_OPTIONS: return true; } return false; } private static _getSettings(editorType: EditorConfig): monaco.editor.IEditorOptions { switch (editorType) { case EditorMode.CSS_META: case EditorMode.LESS_META: return MonacoEditorCSSMetaMods.getSettings(); case EditorMode.TS_META: return MonacoEditorScriptMetaMods.getSettings(); case EditorMode.JSON_OPTIONS: return MonacoEditorJSONOptionsMods.getSettings(); } if (typeof editorType === 'object') { switch (editorType.mode) { case CustomEditorModes.TS_LIBRARIES_META: return MonacoEditorTSLibrariesMetaMods.getSettings(); } } return {}; } private static _getTypeHandler(editorType: EditorConfig, editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor, model: monaco.editor.IModel): MonacoTypeHandler { switch (editorType) { case EditorMode.CSS_META: case EditorMode.LESS_META: return new MonacoEditorCSSMetaMods(editor, model); case EditorMode.JS_META: case EditorMode.TS_META: return new MonacoEditorScriptMetaMods(editor, model); case EditorMode.JSON_OPTIONS: return new MonacoEditorJSONOptionsMods(editor, model); } if (typeof editorType === 'object') { switch (editorType.mode) { case CustomEditorModes.TS_LIBRARIES_META: return new MonacoEditorTSLibrariesMetaMods(editor, model, editorType.config); } } return null; } private static _getLanguage(editorType: EditorConfig) { if (this._typeIsCss(editorType)) { return 'css'; } if (this._typeIsJS(editorType)) { return 'javascript'; } if (this._typeIsTS(editorType)) { return 'typescript'; } if (this._typeIsJSON(editorType)) { return 'json'; } return 'text/plain'; } static getValue(this: MonacoEditor) { if (this.isDiff(this.editor)) { return ''; } return this.editor.getValue(); } static initTSLibrariesMode(this: MonacoEditor, node: CRM.ScriptNode, isBackground: boolean): CustomEditorModeTSLibrariesMeta { return { custom: true, config: { node, isBackground }, mode: CustomEditorModes.TS_LIBRARIES_META } } /** * Merges two arrays */ private static _mergeArrays<T extends T[]|U[], U>(mainArray: T, additionArray: T): T { for (let i = 0; i < additionArray.length; i++) { if (mainArray[i] && typeof additionArray[i] === 'object' && mainArray[i] !== undefined && mainArray[i] !== null) { if (Array.isArray(additionArray[i])) { mainArray[i] = this._mergeArrays<T, U>(mainArray[i] as T, additionArray[i] as T); } else { mainArray[i] = this._mergeObjects(mainArray[i], additionArray[i]); } } else { mainArray[i] = additionArray[i]; } } return mainArray; }; /** * Merges two objects */ private static _mergeObjects<T extends { [key: string]: any; [key: number]: any; }, Y extends Partial<T>>(mainObject: T, additions: Y): T & Y { for (let key in additions) { if (additions.hasOwnProperty(key)) { if (typeof additions[key] === 'object' && typeof mainObject[key] === 'object' && mainObject[key] !== undefined && mainObject[key] !== null) { if (Array.isArray(additions[key])) { mainObject[key] = this._mergeArrays(mainObject[key], (additions as any)[key]); } else { mainObject[key] = this._mergeObjects(mainObject[key], additions[key]); } } else { (mainObject as any)[key] = (additions[key] as any) as T[keyof T]; } } } return mainObject as T & Y; }; static async setMonacoEditorScopes<T>(this: MonacoEditor, getEditor: () => T): Promise<T> { if (this._supportsMonaco()) { await MonacoEditorHookManager.monacoReady; MonacoEditorHookManager.setScope(this); } const result = getEditor(); if (this._supportsMonaco()) { MonacoEditorHookManager.registerScope(this, this.editor); } this._hideSpinner(); return result; } private static _getChromeVersion() { if (BrowserAPI.getBrowser() === 'chrome') { return parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10); } return 1000; } private static _supportsMonaco() { return this._getChromeVersion() >= 30; } static async create(this: MonacoEditor, editorType: EditorConfig, options?: monaco.editor.IStandaloneEditorConstructionOptions, override?: monaco.editor.IEditorOverrideServices): Promise<MonacoEditor> { const language = this._getLanguage(editorType); this._createInfo = { method: 'create', options, override } this._isTypescript = this._typeIsTS(editorType); this._isLess = this._typeIsLESS(editorType); this.options = options; const model = await this.setMonacoEditorScopes(() => { if (this._supportsMonaco()) { const model = monaco.editor.createModel(options.value, language); this.editor = window.monaco.editor.create(this.$.editorElement, this._mergeObjects({ model: model }, options), override) as MonacoStandardEditor; return model } else { const model = new TextareaModel(options.value); this.editor = new TextareaStandardEditor(this.$.editorElement, { model }); return model; } }); this.editor.updateOptions(this._getSettings(editorType)); const typeHandler = this._getTypeHandler(editorType, this.editor as any, model as any); this._models['default'] = { models: [this.editor.getModel() as MonacoModel], handlers: [typeHandler], state: null, editorType } return this; } static async createDiff(this: MonacoEditor, [oldValue, newValue]: [string, string], editorType: EditorConfig, options?: monaco.editor.IDiffEditorOptions, override?: monaco.editor.IEditorOverrideServices): Promise<MonacoEditor> { const language = this._getLanguage(editorType); this._createInfo = { method: 'diff', values: [oldValue, newValue], language, editorType, options, override } this._isTypescript = this._typeIsTS(editorType); this._isLess = this._typeIsLESS(editorType); this.options = options; await this.setMonacoEditorScopes(() => { if (this._supportsMonaco()) { this.editor = monaco.editor.createDiffEditor(this.$.editorElement, options, override) as MonacoDiffEditor; } else { this.editor = new TextareaDiffEditor(this.$.editorElement, {}); } }); let originalModel: MonacoModel; let modifiedModel: MonacoModel; if (this._supportsMonaco()) { originalModel = monaco.editor.createModel(oldValue, language); modifiedModel = monaco.editor.createModel(newValue, language); } else { originalModel = new TextareaModel(oldValue); modifiedModel = new TextareaModel(newValue); } this.editor.updateOptions(this._getSettings(editorType)); (this.editor as MonacoDiffEditor).setModel({ original: originalModel, modified: modifiedModel }); let typeHandlers: [ MonacoTypeHandler, MonacoTypeHandler ] = [ this._getTypeHandler(editorType, this.editor as any, originalModel as any), this._getTypeHandler(editorType, this.editor as any, modifiedModel as any) ]; this._models['default'] = { editorType, handlers: typeHandlers, models: [originalModel, modifiedModel], state: null } return this; } static async createFrom(this: MonacoEditor, from: MonacoEditor) { if (this._createInfo && this._createInfo.method === 'from') { this._createInfo.from.removeChild(this); } const { editor } = from; const editorType = from.getCurrentModel().editorType; this._createInfo = { method: 'from', from, modelId: from.getCurrentModelId() } this._isTypescript = this._typeIsTS(editorType); this._isLess = this._typeIsLESS(editorType); await this.setMonacoEditorScopes(() => { if (this._supportsMonaco()) { editor.getModel this.editor = window.monaco.editor.create(this.$.editorElement, this._mergeObjects({ model: this.isDiff(editor) ? undefined : editor.getModel() as monaco.editor.ITextModel, }, this.options)) as MonacoStandardEditor; } else { this.editor = new TextareaStandardEditor(this.$.editorElement, { model: editor.getModel() as TextareaModel }); } }); this.editor.updateOptions(this._getSettings(editorType)); let typeHandler = this._getTypeHandler(editorType, this.editor as any, this.editor.getModel() as any); this._models['default'] = { models: [this.editor.getModel() as MonacoModel], handlers: [typeHandler], state: null, editorType } from.addChild(this); return this; } static isDiff(this: MonacoEditor, _editor: MonacoStandardEditor|MonacoDiffEditor): _editor is MonacoDiffEditor; static isDiff(this: MonacoEditor, _editor: TextareaStandardEditor|TextareaDiffEditor): _editor is TextareaDiffEditor; static isDiff(this: MonacoEditor, _editor: monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor): _editor is monaco.editor.IDiffEditor; static isDiff(this: MonacoEditor, _editor: MonacoStandardEditor|MonacoDiffEditor|TextareaStandardEditor|TextareaDiffEditor|monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor): _editor is MonacoDiffEditor|TextareaDiffEditor { return this._createInfo.method === 'diff'; } static isTextarea(this: MonacoEditor, _editor: TextareaStandardEditor|TextareaDiffEditor|monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor): _editor is TextareaStandardEditor|TextareaDiffEditor { return '__textarea' in this.editor; } static getEditorAsMonaco(this: MonacoEditor): TextareaStandardEditor|TextareaDiffEditor|monaco.editor.IStandaloneCodeEditor|monaco.editor.IDiffEditor { return this.editor as any; } static setValue(this: MonacoEditor, value: string) { if (!this.isDiff(this.editor)) { this.editor.setValue(value); } } static async reset(this: MonacoEditor) { const createInfo = this._createInfo; const currentModel = this.getCurrentModel(); if (!currentModel) { return null; } const editorType = currentModel.editorType; this.destroy(); if (createInfo.method === 'create') { return await this.create(editorType, createInfo.options, createInfo.override); } else if (createInfo.method === 'diff') { return await this.createDiff(createInfo.values, createInfo.editorType, createInfo.options, createInfo.override); } else { return await this.createFrom(createInfo.from); } } static addChild(this: MonacoEditor, child: MonacoEditor) { this._children.push(child); } static removeChild(this: MonacoEditor, child: MonacoEditor) { this._children.splice(this._children.indexOf(child), 1); } private static setNewModels(this: MonacoEditor, models: Array<MonacoModel>) { const editor = this.editor; if (this.isDiff(editor)) { editor.setModel({ original: models[0], modified: models[1] }); } else { editor.setModel(models[0]); } } static setLess(this: MonacoEditor, enabled: boolean) { if (this._isLess === enabled) { return; } if (this._createInfo.method === 'from') { this._createInfo.from.setLess(enabled); return; } const currentModelId = this.getCurrentModelId(); const currentModel = this.getCurrentModel(); const lang = enabled ? 'less' : 'javascript'; const oldModels = currentModel.models; currentModel.handlers.forEach((handler) => { if (handler) { handler.destroy(); } }); const newModels = oldModels.map((oldModel) => { return monaco.editor.createModel(oldModel.getValue(), lang); }); if (MonacoEditorHookManager.hasScope(this)) { this.setNewModels(newModels); } else { this.setNewModels([MonacoEditorHookManager.getNullModel()]); MonacoEditorHookManager.onHasScope(this, () => { this.setNewModels(newModels); }); } oldModels.forEach((oldModel) => oldModel.dispose()); currentModel.handlers = newModels.map((newModel) => { return this._getTypeHandler(currentModel.editorType, this.editor as any, newModel); }); currentModel.models = newModels; for (let modelId in this._models) { if (modelId !== currentModelId) { delete this._models[modelId]; } } this._isLess = enabled; this._children.forEach((child) => { child._isLess = enabled; const copiedModelName: string = (child._createInfo as any).modelId; const model = this.getModel(copiedModelName); if (!this.isDiff(child.editor)) { child.editor.setModel(model.models[0]); } }) } static setTypescript(this: MonacoEditor, enabled: boolean) { if (this._isTypescript === enabled) { return; } if (this._createInfo.method === 'from') { this._createInfo.from.setTypescript(enabled); return; } const currentModelId = this.getCurrentModelId(); const currentModel = this.getCurrentModel(); const lang = enabled ? 'typescript' : 'javascript'; const oldModels = currentModel.models; currentModel.handlers.forEach((handler) => { handler.destroy(); }); const newModels = oldModels.map((oldModel) => { return monaco.editor.createModel(oldModel.getValue(), lang); }); if (MonacoEditorHookManager.hasScope(this)) { this.setNewModels(newModels); } else { this.setNewModels([MonacoEditorHookManager.getNullModel()]); MonacoEditorHookManager.onHasScope(this, () => { this.setNewModels(newModels); }); } oldModels.forEach((oldModel) => oldModel.dispose()); currentModel.handlers = newModels.map((newModel) => { return this._getTypeHandler(currentModel.editorType, this.editor as any, newModel); }); currentModel.models = newModels; for (let modelId in this._models) { if (modelId !== currentModelId) { delete this._models[modelId]; } } this._isTypescript = enabled; this._children.forEach((child) => { child._isTypescript = enabled; const copiedModelName: string = (child._createInfo as any).modelId; const model = this.getModel(copiedModelName); if (!this.isDiff(child.editor)) { child.editor.setModel(model.models[0]); } }) } static addModel(this: MonacoEditor, identifier: string, value: string, editorType: EditorConfig) { if (this.hasModel(identifier)) { return; } const model = monaco.editor.createModel(value, this._getLanguage(editorType)); let handler = this._getTypeHandler(editorType, this.editor as any, model); this._models[identifier] = { models: [model], handlers: [handler], state: null, editorType } } static hasModel(this: MonacoEditor, identifier: string): boolean { return identifier in this._models; } static getModel(this: MonacoEditor, identifier: string): { models: MonacoModel[]; handlers: MonacoTypeHandler[]; state: monaco.editor.ICodeEditorViewState|monaco.editor.IDiffEditorViewState; editorType: EditorConfig; } { return this._models[identifier]; } static switchToModel(this: MonacoEditor, identifier: string, value: string, editorType: EditorConfig) { if (!this.hasModel(identifier)) { this.addModel(identifier, value, editorType); } if (this.getCurrentModelId() === identifier) { return; } const currentState = this.editor.saveViewState(); const currentModel = this.getCurrentModelId(); if (currentModel in this._models) { this._models[currentModel].state = currentState as any; } const newModel = this._models[identifier]; (this.editor.setModel as any)(newModel.models[0] as MonacoModel); (this.editor.restoreViewState as any)(newModel.state as any); this.editor.focus(); } static getCurrentModelId(this: MonacoEditor) { for (let modelId in this._models) { const { models: [firstModel] } = this._models[modelId]; if (firstModel === this. editor.getModel()) { return modelId; } } return null; } static getCurrentModel(this: MonacoEditor) { return this._models[this.getCurrentModelId()]; } static destroy(this: MonacoEditor) { this.editor.dispose(); for (const modelId in this._models) { const model = this._models[modelId]; model.handlers.forEach((handler) => { handler.destroy(); }); model.handlers = null; delete this._models[modelId]; } this._showSpinner(); } private static _runJsLint(this: MonacoEditor): LinterWarning[] { const code = this.getCurrentModel().models[0].getValue(); const { warnings } = window.jslint(code, {}, [...window.app.jsLintGlobals]); return warnings.map(({ column, line, message }) => ({ col: column, line: line, message: message })); } private static _runCssLint(this: MonacoEditor): LinterWarning[] { const code = this.getCurrentModel().models[0].getValue(); const { messages } = window.CSSLint.verify(code); return messages.map(({ col, line, message }) => ({ col: col, line: line, message: message })); } private static _showLintResults(this: MonacoEditor, name: string, messages: LinterWarning[]) { if ('__textarea' in this.editor) { return; } monaco.editor.setModelMarkers(this.getCurrentModel().models[0] as monaco.editor.IModel, name, messages.map(message => ({ startLineNumber: message.line, endLineNumber: message.line, startColumn: message.col, endColumn: message.col, message: message.message, severity: 2 }))); } static async runLinter(this: MonacoEditor) { const type = this._models[this.getCurrentModelId()].editorType; if (this._typeIsJS(type)) { await MonacoEditorHookManager.Libraries.runFile('js/libraries/jslint.js'); this._showLintResults('jslint', this._runJsLint()); } else if (this._typeIsTS(type)) { alert(await window.__(I18NKeys.options.editPages.monaco.lintingDisabled, 'typescript')); } else if (this._typeIsLESS(type)) { alert(await window.__(I18NKeys.options.editPages.monaco.lintingDisabled, 'LESS/stylus')); } else if (this._typeIsCss(type)) { await MonacoEditorHookManager.Libraries.runFile('js/libraries/csslint.js'); this._showLintResults('csslint', this._runCssLint()); } } static getTypeHandler(this: MonacoEditor) { return this._models[this.getCurrentModelId()].handlers; } static _showSpinner(this: MonacoEditor) { window.setDisplayFlex(this.$.placeholder); this.$.spinner && (this.$.spinner.active = true); this.$.placeholder.classList.remove('hidden') } static async _hideSpinner(this: MonacoEditor) { this.$.spinner && (this.$.spinner.active = false); this.$.placeholder.classList.add('hidden'); await new window.Promise((resolve) => { window.setTimeout(() => { resolve(null); }, 1000); }); this.$.placeholder.style.display = 'none'; } static _getStylesheet(this: MonacoEditor) { if (this._stylesheet) { return this._stylesheet; } const el = document.createElement('style'); this.shadowRoot.appendChild(el); return (this._stylesheet = el); } static claimScope(this: MonacoEditor) { MonacoEditorHookManager.setScope(this); } static setDefaultHeight(this: MonacoEditor) { let previous: number = this.$.editorElement.getBoundingClientRect().height; if (this._tempLayoutInfo) { previous = this._tempLayoutInfo.previous; } this._tempLayoutInfo = { previous, current: previous } } static setTempLayout(this: MonacoEditor) { let current: number = this.$.editorElement.getBoundingClientRect().height; let previous = current; if (this._tempLayoutInfo) { previous = this._tempLayoutInfo.previous; } this._tempLayoutInfo = { previous, current } this.editor && this.editor.layout(); } static stopTempLayout(this: MonacoEditor) { if (!this._tempLayoutInfo) { return; } const previous = this._tempLayoutInfo.previous; this.$.editorElement.style.maxHeight = `${previous}px`; this.editor.layout(); this._tempLayoutInfo.current = previous; this.$.editorElement.style.maxHeight = 'none'; } static ready(this: MonacoEditor) { this._showSpinner(); this._models = {}; this._children = []; MonacoEditorHookManager.setup(); } } export class MonacoEditorHookManager { /** * Whether this was set up already */ private static _setup: boolean = false; /** * A promise keeping track of the status of the editor */ static monacoReady: Promise<void> = null; /** * The scope that the current editor is active in */ static currentScope: MonacoEditor = null; /** * Listeners for a changing scope */ private static _scopeListeners: { scope: MonacoEditor; listener: () => void; }[] = []; /** * An empty model used as a transition model */ private static _nullModel: MonacoModel = null; /** * Any registered scopes */ private static _scopes: [MonacoEditor, MonacoStandardEditor|MonacoDiffEditor][] = []; static Caret = class MonacoEditorCaret { /** * A cache containing the width of chars */ private static _charCache: { [key: string]: number; } = {} /** * A canvas used for calculating char width */ private static _charCanvas: HTMLCanvasElement = document.createElement('canvas') static getCharWidth(char: string, font: string) { const cacheKey = char + font; if (this._charCache[cacheKey]) { return this._charCache[cacheKey]; } var context = this._charCanvas.getContext("2d"); context.font = font; var metrics = context.measureText(char); var width = metrics.width; this._charCache[cacheKey] = width; return width; } static caretRangeFromPoint(this: ShadowRoot, x: number, y: number) { // Get the element under the point let el = this.elementFromPoint(x, y) as HTMLElement; // Get the last child of the element until its firstChild is a text node // This assumes that the pointer is on the right of the line, out of the tokens // and that we want to get the offset of the last token of the line while (el.firstChild.nodeType !== el.firstChild.TEXT_NODE) { el = el.lastChild as HTMLElement; } // Grab its rect var rect = el.getBoundingClientRect(); // And its font var font = window.getComputedStyle(el, null).getPropertyValue('font'); // And also its txt content var text = el.innerText; // Poisition the pixel cursor at the left of the element var pixelCursor = rect.left; var offset = 0; var step; // If the point is on the right of the box put the cursor after the last character if (x > rect.left + rect.width) { offset = text.length; } else { // Goes through all the characters of the innerText, and checks if the x of the point // belongs to the character. for (var i = 0; i < text.length + 1; i++) { // The step is half the width of the character step = MonacoEditorHookManager.Caret.getCharWidth(text.charAt(i), font) / 2; // Move to the center of the character pixelCursor += step; // If the x of the point is smaller that the position of the cursor, the point is over that character if (x < pixelCursor) { offset = i; break; } // Move between the current character and the next pixelCursor += step; } } // Creates a range with the text node of the element and set the offset found var range = document.createRange(); range.setStart(el.firstChild, offset); range.setEnd(el.firstChild, offset); return range; }; } static setScope(scope: MonacoEditor) { this.currentScope = scope; window.setTimeout(() => { scope.editor.getDomNode() && scope.editor.getDomNode().addEventListener('mouseover', () => { this.currentScope = scope; }); }, 500); this._scopeListeners = this._scopeListeners.filter(({scope: listenerScope, listener}) => { if (listenerScope === scope) { listener(); return false; } return true; }); } static hasScope(scope: MonacoEditor) { return this.currentScope === scope; } static onHasScope(scope: MonacoEditor, listener: () => void) { if (scope === this.currentScope) { listener(); return; } this._scopeListeners.push({ scope, listener }); } static registerScope(scope: MonacoEditor, editor: MonacoStandardEditor|MonacoDiffEditor) { this._scopes.push([scope, editor]) } private static _setupRequire() { return new window.Promise<void>(async (resolve) => { const require = await window.onExistsChain(window, 'AMDLoader', 'global', 'require'); require.config({ paths: { 'vs': '../elements/options/editpages/monaco-editor/src/min/vs' } }); require(['vs/editor/editor.main'], () => { resolve(null); }); }); } private static _getShadowRoot() { return this.currentScope.shadowRoot; } private static _defineProperties() { const tagCompletions = [{ label: '==UserScript==', kind: monaco.languages.CompletionItemKind.Property, insertText: '// ==UserScript==\n// ==/UserScript==', detail: 'UserScript start tag', documentation: window.__.sync( I18NKeys.options.editPages.monaco.startTagUserscript) }, { label: '==/UserScript==', kind: monaco.languages.CompletionItemKind.Property, insertText: '// ==/UserScript==', detail: 'UserScript end tag', documentation: window.__.sync( I18NKeys.options.editPages.monaco.endTagUserscript) }] as monaco.languages.CompletionItem[]; const descriptions = getMetaDescriptions(); const keyCompletions = { isIncomplete: true, suggestions: Object.getOwnPropertyNames(descriptions).map((key: keyof typeof descriptions) => { const description = descriptions[key]; return { label: `@${key}`, kind: monaco.languages.CompletionItemKind.Property, insertText: `@${key}`, detail: window.__.sync( I18NKeys.options.editPages.monaco.metaKey), documentation: description, range: undefined as any } }) } as monaco.languages.CompletionList; Object.defineProperties(this, { getLocalBodyShadowRoot: { get: () => { return this._getShadowRoot(); } }, caretRangeFromPoint: { get: () => { return (context: { model: monaco.editor.IStandaloneCodeEditor; viewDomNode: HTMLElement; }) => { for (const [ scope, editor ] of this._scopes) { if (context.viewDomNode === editor.getDomNode()) { return this.Caret.caretRangeFromPoint.bind(scope.shadowRoot); } } return document.caretRangeFromPoint.bind(document); } } }, _metaTagCompletions: { get: () => { return tagCompletions; } }, _metaKeyCompletions: { get: () => { return keyCompletions; } } }); } static Completion = class MonacoEditorCompletions { private static _enabledCompletions: { [language: string]: { completion: monaco.languages.CompletionItemProvider; disposable: monaco.IDisposable }[]; } = {}; static register(language: 'less'|'javascript'|'css'|'typescript'|'json', item: monaco.languages.CompletionItemProvider) { this._enabledCompletions[language] = this._enabledCompletions[language] || []; for (let completionData of this._enabledCompletions[language]) { if (completionData.completion === item) { return; } } this._enabledCompletions[language].push({ completion: item, disposable: monaco.languages.registerCompletionItemProvider(language, item) }); } static clearAll() { for (let lang in this._enabledCompletions) { for (let completion of this._enabledCompletions[lang]) { completion.disposable.dispose(); } } } } static Fetching = class MonacoEditorFetches { private static _fetchedFiles: { [lib: string]: string; } = {}; private static _isWebPageEnv() { return location.protocol === 'http:' || location.protocol === 'https:'; } private static readonly BASE = '../'; static loadFile(name: string): Promise<string> { return new window.Promise((resolve, reject) => { const xhr: XMLHttpRequest = new window.XMLHttpRequest(); const url = this._isWebPageEnv() ? `${this.BASE}${name}` : browserAPI.runtime.getURL(name); xhr.open('GET', url); xhr.onreadystatechange = () => { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { this._fetchedFiles[name] = xhr.responseText; resolve(xhr.responseText); } else { reject(new Error('Failed XHR')); } } } xhr.send(); }); } static isLoaded(name: string): boolean { return name in this._fetchedFiles; } static getLoadedFile(name: string): string { return this._fetchedFiles[name]; } } static Libraries = class MonacoEditorLibraries { static async readFile(path: string): Promise<string> { if (this._parent().Fetching.isLoaded(path)) { return this._parent().Fetching.getLoadedFile(path); } return await this._parent().Fetching.loadFile(path); } static async runFile(path: string, global?: keyof Window): Promise<void> { if (this._parent().Fetching.isLoaded(path)) { return; } const el = document.createElement('script'); el.src = browserAPI.runtime.getURL(path); document.body.appendChild(el); if (global) { await window.onExists(global); } } private static _parent() { return window.MonacoEditorHookManager; } } private static async _loadCRMAPI() { return await this.Libraries.readFile('js/libraries/crmapi.d.ts'); } private static async _setupCRMDefs() { const fileContent = await this._loadCRMAPI(); monaco.languages.typescript.javascriptDefaults.addExtraLib(fileContent, 'crmapi.d.ts'); monaco.languages.typescript.typescriptDefaults.addExtraLib(fileContent, 'crmapi.d.ts'); } private static _captureMonacoErrors() { window.onerror = (_msg, filename) => { if (filename.indexOf('vs/editor/editor.main.js') > -1) { console.log(window.__.sync( I18NKeys.options.editPages.monaco.monacoError)); return true; } return undefined; } } private static _createNullModel() { this._nullModel = monaco.editor.createModel(''); } static getNullModel() { return this._nullModel; } static setup() { if (this._setup) { return; } this._setup = true; this._captureMonacoErrors(); this.monacoReady = new window.Promise<void>(async (resolve) => { this._setupRequire(); window.onExists('monaco').then(() => { MonacoEditorJSONOptionsMods.enableSchema(); this._defineProperties(); this._createNullModel(); this._setupCRMDefs(); resolve(null); }); }); } }; window.MonacoEditorHookManager = MonacoEditorHookManager; export type MonacoEditor = Polymer.El<'monaco-editor', typeof MOE & { EditorMode: typeof EditorMode; CustomEditorModes: typeof CustomEditorModes; }>; if (window.objectify) { window.register(MOE); } else { window.addEventListener('RegisterReady', () => { window.register(MOE); }); } } export type MonacoEditor = MonacoEditorElement.MonacoEditor;
the_stack
export const schemaVer = '2.1.0' // To parse this data: // // import { Convert, AgeDistributionArray, AgeDistributionData, AgeDistributionDatum, AgeGroup, CaseCountsArray, CaseCountsData, CaseCountsDatum, DateRange, MitigationInterval, NumericRangeNonNegative, PercentageRange, ScenarioArray, ScenarioData, ScenarioDatum, ScenarioDatumEpidemiological, ScenarioDatumMitigation, ScenarioDatumPopulation, ScenarioDatumSimulation, SeverityDistributionArray, SeverityDistributionData, SeverityDistributionDatum, Shareable } from "./file"; // // const ageDistributionArray = Convert.toAgeDistributionArray(json); // const ageDistributionData = Convert.toAgeDistributionData(json); // const ageDistributionDatum = Convert.toAgeDistributionDatum(json); // const ageGroup = Convert.toAgeGroup(json); // const caseCountsArray = Convert.toCaseCountsArray(json); // const caseCountsData = Convert.toCaseCountsData(json); // const caseCountsDatum = Convert.toCaseCountsDatum(json); // const colorHex = Convert.toColorHex(json); // const dateRange = Convert.toDateRange(json); // const integer = Convert.toInteger(json); // const integerNonNegative = Convert.toIntegerNonNegative(json); // const integerPositive = Convert.toIntegerPositive(json); // const mitigationInterval = Convert.toMitigationInterval(json); // const numericRangeNonNegative = Convert.toNumericRangeNonNegative(json); // const percentage = Convert.toPercentage(json); // const percentageRange = Convert.toPercentageRange(json); // const scenarioArray = Convert.toScenarioArray(json); // const scenarioData = Convert.toScenarioData(json); // const scenarioDatum = Convert.toScenarioDatum(json); // const scenarioDatumEpidemiological = Convert.toScenarioDatumEpidemiological(json); // const scenarioDatumMitigation = Convert.toScenarioDatumMitigation(json); // const scenarioDatumPopulation = Convert.toScenarioDatumPopulation(json); // const scenarioDatumSimulation = Convert.toScenarioDatumSimulation(json); // const severityDistributionArray = Convert.toSeverityDistributionArray(json); // const severityDistributionData = Convert.toSeverityDistributionData(json); // const severityDistributionDatum = Convert.toSeverityDistributionDatum(json); // const shareable = Convert.toShareable(json); // const schemaVer = Convert.toSchemaVer(json); // // These functions will throw an error if the JSON doesn't // match the expected interface, even if the JSON is valid. export interface AgeDistributionArray { all: AgeDistributionData[]; } export interface AgeDistributionData { data: AgeDistributionDatum[]; name: string; } export interface AgeDistributionDatum { ageGroup: AgeGroup; population: number; } export enum AgeGroup { The09 = "0-9", The1019 = "10-19", The2029 = "20-29", The3039 = "30-39", The4049 = "40-49", The5059 = "50-59", The6069 = "60-69", The7079 = "70-79", The80 = "80+", } export interface CaseCountsArray { all: CaseCountsData[]; } export interface CaseCountsData { data: CaseCountsDatum[]; name: string; } export interface CaseCountsDatum { cases: number | null; deaths?: number | null; hospitalized?: number | null; icu?: number | null; recovered?: number | null; time: Date; } export interface ScenarioArray { all: ScenarioData[]; } export interface ScenarioData { data: ScenarioDatum; name: string; } export interface ScenarioDatum { epidemiological: ScenarioDatumEpidemiological; mitigation: ScenarioDatumMitigation; population: ScenarioDatumPopulation; simulation: ScenarioDatumSimulation; } export interface ScenarioDatumEpidemiological { hospitalStayDays: number; icuStayDays: number; infectiousPeriodDays: number; latencyDays: number; overflowSeverity: number; peakMonth: number; r0: NumericRangeNonNegative; seasonalForcing: number; } export interface NumericRangeNonNegative { begin: number; end: number; } export interface ScenarioDatumMitigation { mitigationIntervals: MitigationInterval[]; } export interface MitigationInterval { color: string; name: string; timeRange: DateRange; transmissionReduction: PercentageRange; } export interface DateRange { begin: Date; end: Date; } export interface PercentageRange { begin: number; end: number; } export interface ScenarioDatumPopulation { ageDistributionName: string; caseCountsName: string; hospitalBeds: number; icuBeds: number; importsPerDay: number; initialNumberOfCases: number; populationServed: number; } export interface ScenarioDatumSimulation { numberStochasticRuns: number; simulationTimeRange: DateRange; } export interface SeverityDistributionArray { all: SeverityDistributionData[]; } export interface SeverityDistributionData { data: SeverityDistributionDatum[]; name: string; } export interface SeverityDistributionDatum { ageGroup: AgeGroup; confirmed: number; critical: number; fatal: number; isolated: number; palliative: number; severe: number; } export interface Shareable { ageDistributionData: AgeDistributionData; scenarioData: ScenarioData; schemaVer: string; severityDistributionData: SeverityDistributionData; } // Converts JSON strings to/from your types // and asserts the results of JSON.parse at runtime export class Convert { public static toAgeDistributionArray(json: string): AgeDistributionArray { return cast(JSON.parse(json), r("AgeDistributionArray")); } public static ageDistributionArrayToJson( value: AgeDistributionArray ): string { return JSON.stringify(uncast(value, r("AgeDistributionArray")), null, 2); } public static toAgeDistributionData(json: string): AgeDistributionData { return cast(JSON.parse(json), r("AgeDistributionData")); } public static ageDistributionDataToJson(value: AgeDistributionData): string { return JSON.stringify(uncast(value, r("AgeDistributionData")), null, 2); } public static toAgeDistributionDatum(json: string): AgeDistributionDatum { return cast(JSON.parse(json), r("AgeDistributionDatum")); } public static ageDistributionDatumToJson( value: AgeDistributionDatum ): string { return JSON.stringify(uncast(value, r("AgeDistributionDatum")), null, 2); } public static toCaseCountsArray(json: string): CaseCountsArray { return cast(JSON.parse(json), r("CaseCountsArray")); } public static caseCountsArrayToJson(value: CaseCountsArray): string { return JSON.stringify(uncast(value, r("CaseCountsArray")), null, 2); } public static toCaseCountsData(json: string): CaseCountsData { return cast(JSON.parse(json), r("CaseCountsData")); } public static caseCountsDataToJson(value: CaseCountsData): string { return JSON.stringify(uncast(value, r("CaseCountsData")), null, 2); } public static toCaseCountsDatum(json: string): CaseCountsDatum { return cast(JSON.parse(json), r("CaseCountsDatum")); } public static caseCountsDatumToJson(value: CaseCountsDatum): string { return JSON.stringify(uncast(value, r("CaseCountsDatum")), null, 2); } public static toScenarioArray(json: string): ScenarioArray { return cast(JSON.parse(json), r("ScenarioArray")); } public static scenarioArrayToJson(value: ScenarioArray): string { return JSON.stringify(uncast(value, r("ScenarioArray")), null, 2); } public static toScenarioData(json: string): ScenarioData { return cast(JSON.parse(json), r("ScenarioData")); } public static scenarioDataToJson(value: ScenarioData): string { return JSON.stringify(uncast(value, r("ScenarioData")), null, 2); } public static toScenarioDatum(json: string): ScenarioDatum { return cast(JSON.parse(json), r("ScenarioDatum")); } public static scenarioDatumToJson(value: ScenarioDatum): string { return JSON.stringify(uncast(value, r("ScenarioDatum")), null, 2); } public static toScenarioDatumEpidemiological( json: string ): ScenarioDatumEpidemiological { return cast(JSON.parse(json), r("ScenarioDatumEpidemiological")); } public static scenarioDatumEpidemiologicalToJson( value: ScenarioDatumEpidemiological ): string { return JSON.stringify( uncast(value, r("ScenarioDatumEpidemiological")), null, 2 ); } public static toNumericRangeNonNegative( json: string ): NumericRangeNonNegative { return cast(JSON.parse(json), r("NumericRangeNonNegative")); } public static numericRangeNonNegativeToJson( value: NumericRangeNonNegative ): string { return JSON.stringify(uncast(value, r("NumericRangeNonNegative")), null, 2); } public static toScenarioDatumMitigation( json: string ): ScenarioDatumMitigation { return cast(JSON.parse(json), r("ScenarioDatumMitigation")); } public static scenarioDatumMitigationToJson( value: ScenarioDatumMitigation ): string { return JSON.stringify(uncast(value, r("ScenarioDatumMitigation")), null, 2); } public static toMitigationInterval(json: string): MitigationInterval { return cast(JSON.parse(json), r("MitigationInterval")); } public static mitigationIntervalToJson(value: MitigationInterval): string { return JSON.stringify(uncast(value, r("MitigationInterval")), null, 2); } public static toDateRange(json: string): DateRange { return cast(JSON.parse(json), r("DateRange")); } public static dateRangeToJson(value: DateRange): string { return JSON.stringify(uncast(value, r("DateRange")), null, 2); } public static toPercentageRange(json: string): PercentageRange { return cast(JSON.parse(json), r("PercentageRange")); } public static percentageRangeToJson(value: PercentageRange): string { return JSON.stringify(uncast(value, r("PercentageRange")), null, 2); } public static toScenarioDatumPopulation( json: string ): ScenarioDatumPopulation { return cast(JSON.parse(json), r("ScenarioDatumPopulation")); } public static scenarioDatumPopulationToJson( value: ScenarioDatumPopulation ): string { return JSON.stringify(uncast(value, r("ScenarioDatumPopulation")), null, 2); } public static toScenarioDatumSimulation( json: string ): ScenarioDatumSimulation { return cast(JSON.parse(json), r("ScenarioDatumSimulation")); } public static scenarioDatumSimulationToJson( value: ScenarioDatumSimulation ): string { return JSON.stringify(uncast(value, r("ScenarioDatumSimulation")), null, 2); } public static toSeverityDistributionArray( json: string ): SeverityDistributionArray { return cast(JSON.parse(json), r("SeverityDistributionArray")); } public static severityDistributionArrayToJson( value: SeverityDistributionArray ): string { return JSON.stringify( uncast(value, r("SeverityDistributionArray")), null, 2 ); } public static toSeverityDistributionData( json: string ): SeverityDistributionData { return cast(JSON.parse(json), r("SeverityDistributionData")); } public static severityDistributionDataToJson( value: SeverityDistributionData ): string { return JSON.stringify( uncast(value, r("SeverityDistributionData")), null, 2 ); } public static toSeverityDistributionDatum( json: string ): SeverityDistributionDatum { return cast(JSON.parse(json), r("SeverityDistributionDatum")); } public static severityDistributionDatumToJson( value: SeverityDistributionDatum ): string { return JSON.stringify( uncast(value, r("SeverityDistributionDatum")), null, 2 ); } public static toShareable(json: string): Shareable { return cast(JSON.parse(json), r("Shareable")); } public static shareableToJson(value: Shareable): string { return JSON.stringify(uncast(value, r("Shareable")), null, 2); } } function invalidValue(typ: any, val: any): never { throw Error( `Invalid value ${JSON.stringify(val)} for type ${JSON.stringify(typ)}` ); } function jsonToJSProps(typ: any): any { if (typ.jsonToJS === undefined) { const map: any = {}; typ.props.forEach((p: any) => (map[p.json] = { key: p.js, typ: p.typ })); typ.jsonToJS = map; } return typ.jsonToJS; } function jsToJSONProps(typ: any): any { if (typ.jsToJSON === undefined) { const map: any = {}; typ.props.forEach((p: any) => (map[p.js] = { key: p.json, typ: p.typ })); typ.jsToJSON = map; } return typ.jsToJSON; } function transform(val: any, typ: any, getProps: any): any { function transformPrimitive(typ: string, val: any): any { if (typeof typ === typeof val) return val; return invalidValue(typ, val); } function transformUnion(typs: any[], val: any): any { // val must validate against one typ in typs const l = typs.length; for (let i = 0; i < l; i++) { const typ = typs[i]; try { return transform(val, typ, getProps); } catch (_) {} } return invalidValue(typs, val); } function transformEnum(cases: string[], val: any): any { if (cases.indexOf(val) !== -1) return val; return invalidValue(cases, val); } function transformArray(typ: any, val: any): any { // val must be an array with no invalid elements if (!Array.isArray(val)) return invalidValue("array", val); return val.map((el) => transform(el, typ, getProps)); } function transformDate(val: any): any { if (val === null) { return null; } const d = new Date(val); if (isNaN(d.valueOf())) { return invalidValue("Date", val); } return d; } function transformObject( props: { [k: string]: any }, additional: any, val: any ): any { if (val === null || typeof val !== "object" || Array.isArray(val)) { return invalidValue("object", val); } const result: any = {}; Object.getOwnPropertyNames(props).forEach((key) => { const prop = props[key]; const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; result[prop.key] = transform(v, prop.typ, getProps); }); Object.getOwnPropertyNames(val).forEach((key) => { if (!Object.prototype.hasOwnProperty.call(props, key)) { result[key] = transform(val[key], additional, getProps); } }); return result; } if (typ === "any") return val; if (typ === null) { if (val === null) return val; return invalidValue(typ, val); } if (typ === false) return invalidValue(typ, val); while (typeof typ === "object" && typ.ref !== undefined) { typ = typeMap[typ.ref]; } if (Array.isArray(typ)) return transformEnum(typ, val); if (typeof typ === "object") { return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) : invalidValue(typ, val); } // Numbers can be parsed by Date but shouldn't be. if (typ === Date && typeof val !== "number") return transformDate(val); return transformPrimitive(typ, val); } function cast<T>(val: any, typ: any): T { return transform(val, typ, jsonToJSProps); } function uncast<T>(val: T, typ: any): any { return transform(val, typ, jsToJSONProps); } function a(typ: any) { return { arrayItems: typ }; } function u(...typs: any[]) { return { unionMembers: typs }; } function o(props: any[], additional: any) { return { props, additional }; } function m(additional: any) { return { props: [], additional }; } function r(name: string) { return { ref: name }; } const typeMap: any = { AgeDistributionArray: o( [{ json: "all", js: "all", typ: a(r("AgeDistributionData")) }], false ), AgeDistributionData: o( [ { json: "data", js: "data", typ: a(r("AgeDistributionDatum")) }, { json: "name", js: "name", typ: "" }, ], false ), AgeDistributionDatum: o( [ { json: "ageGroup", js: "ageGroup", typ: r("AgeGroup") }, { json: "population", js: "population", typ: 0 }, ], false ), CaseCountsArray: o( [{ json: "all", js: "all", typ: a(r("CaseCountsData")) }], false ), CaseCountsData: o( [ { json: "data", js: "data", typ: a(r("CaseCountsDatum")) }, { json: "name", js: "name", typ: "" }, ], false ), CaseCountsDatum: o( [ { json: "cases", js: "cases", typ: u(0, null) }, { json: "deaths", js: "deaths", typ: u(undefined, u(0, null)) }, { json: "hospitalized", js: "hospitalized", typ: u(undefined, u(0, null)), }, { json: "icu", js: "icu", typ: u(undefined, u(0, null)) }, { json: "recovered", js: "recovered", typ: u(undefined, u(0, null)) }, { json: "time", js: "time", typ: Date }, ], false ), ScenarioArray: o( [{ json: "all", js: "all", typ: a(r("ScenarioData")) }], false ), ScenarioData: o( [ { json: "data", js: "data", typ: r("ScenarioDatum") }, { json: "name", js: "name", typ: "" }, ], false ), ScenarioDatum: o( [ { json: "epidemiological", js: "epidemiological", typ: r("ScenarioDatumEpidemiological"), }, { json: "mitigation", js: "mitigation", typ: r("ScenarioDatumMitigation"), }, { json: "population", js: "population", typ: r("ScenarioDatumPopulation"), }, { json: "simulation", js: "simulation", typ: r("ScenarioDatumSimulation"), }, ], false ), ScenarioDatumEpidemiological: o( [ { json: "hospitalStayDays", js: "hospitalStayDays", typ: 3.14 }, { json: "icuStayDays", js: "icuStayDays", typ: 3.14 }, { json: "infectiousPeriodDays", js: "infectiousPeriodDays", typ: 3.14 }, { json: "latencyDays", js: "latencyDays", typ: 3.14 }, { json: "overflowSeverity", js: "overflowSeverity", typ: 3.14 }, { json: "peakMonth", js: "peakMonth", typ: 0 }, { json: "r0", js: "r0", typ: r("NumericRangeNonNegative") }, { json: "seasonalForcing", js: "seasonalForcing", typ: 3.14 }, ], false ), NumericRangeNonNegative: o( [ { json: "begin", js: "begin", typ: 3.14 }, { json: "end", js: "end", typ: 3.14 }, ], false ), ScenarioDatumMitigation: o( [ { json: "mitigationIntervals", js: "mitigationIntervals", typ: a(r("MitigationInterval")), }, ], false ), MitigationInterval: o( [ { json: "color", js: "color", typ: "" }, { json: "name", js: "name", typ: "" }, { json: "timeRange", js: "timeRange", typ: r("DateRange") }, { json: "transmissionReduction", js: "transmissionReduction", typ: r("PercentageRange"), }, ], false ), DateRange: o( [ { json: "begin", js: "begin", typ: Date }, { json: "end", js: "end", typ: Date }, ], false ), PercentageRange: o( [ { json: "begin", js: "begin", typ: 3.14 }, { json: "end", js: "end", typ: 3.14 }, ], false ), ScenarioDatumPopulation: o( [ { json: "ageDistributionName", js: "ageDistributionName", typ: "" }, { json: "caseCountsName", js: "caseCountsName", typ: "" }, { json: "hospitalBeds", js: "hospitalBeds", typ: 0 }, { json: "icuBeds", js: "icuBeds", typ: 0 }, { json: "importsPerDay", js: "importsPerDay", typ: 3.14 }, { json: "initialNumberOfCases", js: "initialNumberOfCases", typ: 0 }, { json: "populationServed", js: "populationServed", typ: 0 }, ], false ), ScenarioDatumSimulation: o( [ { json: "numberStochasticRuns", js: "numberStochasticRuns", typ: 0 }, { json: "simulationTimeRange", js: "simulationTimeRange", typ: r("DateRange"), }, ], false ), SeverityDistributionArray: o( [{ json: "all", js: "all", typ: a(r("SeverityDistributionData")) }], false ), SeverityDistributionData: o( [ { json: "data", js: "data", typ: a(r("SeverityDistributionDatum")) }, { json: "name", js: "name", typ: "" }, ], false ), SeverityDistributionDatum: o( [ { json: "ageGroup", js: "ageGroup", typ: r("AgeGroup") }, { json: "confirmed", js: "confirmed", typ: 3.14 }, { json: "critical", js: "critical", typ: 3.14 }, { json: "fatal", js: "fatal", typ: 3.14 }, { json: "isolated", js: "isolated", typ: 3.14 }, { json: "palliative", js: "palliative", typ: 3.14 }, { json: "severe", js: "severe", typ: 3.14 }, ], false ), Shareable: o( [ { json: "ageDistributionData", js: "ageDistributionData", typ: r("AgeDistributionData"), }, { json: "scenarioData", js: "scenarioData", typ: r("ScenarioData") }, { json: "schemaVer", js: "schemaVer", typ: "" }, { json: "severityDistributionData", js: "severityDistributionData", typ: r("SeverityDistributionData"), }, ], false ), AgeGroup: [ "0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80+", ], };
the_stack
import * as React from "react"; import ModalContent from "components/ModalContent.tsx"; import client from "js/slycat-web-client"; import RemoteLoginTab from 'plugins/slycat-timeseries-model/plugin-components/RemoteLoginTab.tsx'; import HPCParametersTab from 'plugins/slycat-timeseries-model/plugin-components/HPCParametersTab.tsx'; import ModelNamingTab from 'plugins/slycat-timeseries-model/plugin-components/ModelNamingTab.tsx'; import TimeseriesParametersTab from 'plugins/slycat-timeseries-model/plugin-components/TimeseriesParametersTab.tsx'; import SlycatFormRadioCheckbox from 'components/SlycatFormRadioCheckbox.tsx'; import SlycatNumberInput from 'components/SlycatNumberInput.tsx'; import SlycatTextInput from 'components/SlycatTextInput.tsx'; import SlycatFormDropDown from 'components/SlycatFormDropDown.tsx'; import SlycatTimeInput from 'components/SlycatTimeInput.tsx'; import SlycatRemoteControls from 'components/SlycatRemoteControls.jsx'; import ConnectButton from 'components/ConnectButton.tsx'; import RemoteFileBrowser from 'components/RemoteFileBrowser.tsx' import SlycatSelector from 'components/SlycatSelector.tsx'; import server_root from "js/slycat-server-root"; import cloneDeep from "lodash"; import markings from "js/slycat-markings"; /** * not used */ export interface TimeseriesWizardProps { project: any; markings: any; } /** * not used */ export interface TimeseriesWizardState { project: any; model: { _id: string }; modalId: string; jid: string; visibleTab: string; selectedOption: string; loadingData: boolean; hostname: string; sessionExists: boolean; username: string; password: string; hdf5Directory: string; selectedTablePath: string; selectedXycePath: string; inputDirectory: string; parserType: string; columnNames: { text: string, value: string }[]; timeseriesColumn: string; binCount: number; resamplingAlg: string; clusterLinkageMeasure: string; clusterMetric: string; accountId: string; partition: string; numNodes: number; cores: number; jobHours: number; jobMin: number; workDir: string; userConfig: { 'slurm': {}, 'timeseries-wizard': {} }, idCol: string; delimiter: string; timeseriesName: string; modelDescription: string; TimeSeriesLocalStorage: any; validForms: boolean; marking: { text: string, value: string}[]; selectedMarking: {text: string, value: string}[]; } /** * modal wizard for the timeseries model creation */ let initialState = {}; export default class TimeseriesWizard extends React.Component< TimeseriesWizardProps, TimeseriesWizardState > { public constructor(props: TimeseriesWizardProps) { super(props); this.state = { project: props.project, model: { _id: '' }, modalId: "slycat-wizard", jid: '', visibleTab: '0', selectedOption: 'xyce', loadingData: false, hostname: '', sessionExists: false, username: '', password: '', hdf5Directory: '', selectedTablePath: '', selectedXycePath: '', inputDirectory: '', parserType: '', columnNames: [], timeseriesColumn: '', binCount: 500, resamplingAlg: 'uniform-paa', clusterLinkageMeasure: 'average', clusterMetric: 'euclidean', accountId: '', partition: '', numNodes: 1, cores: 2, jobHours: 0, jobMin: 30, workDir: '', userConfig: { 'slurm': {}, 'timeseries-wizard': {} }, idCol: '%eval_id', delimiter: ',', timeseriesName: '', modelDescription: '', TimeSeriesLocalStorage: localStorage.getItem("slycat-timeseries-wizard") as any, validForms: true, marking: [], selectedMarking: [], }; initialState = cloneDeep(this.state); this.getMarkings(); } getBodyJsx(): JSX.Element { return ( <div> <ul className="nav nav-pills"> <li className={this.state.visibleTab == '0' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Find Data</a></li> {this.state.selectedOption != 'hdf5' ? <li className={this.state.visibleTab == '1' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Select Table File</a></li> : null} <li className={this.state.visibleTab == '2' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Timeseries Parameters</a></li> {this.state.selectedOption == 'xyce' ? <li className={this.state.visibleTab == '3' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Select Timeseries File</a></li> : null} {this.state.selectedOption == 'hdf5' ? <li className={this.state.visibleTab == '4' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Select HDF5 Directory</a></li> : null} <li className={this.state.visibleTab == '5' ? 'nav-item active' : 'nav-item'}><a className="nav-link">HPC Parameters</a></li> <li className={this.state.visibleTab == '6' ? 'nav-item active' : 'nav-item'}><a className="nav-link">Name Model</a></li> </ul> {this.state.visibleTab === "0" ? <div> <RemoteLoginTab onChange={(value: string) => { this.setState({ selectedOption: value }); }} checked={this.state.selectedOption} loadingData={this.state.loadingData} callBack={(newHostname: string, newUsername: string, newPassword: string, sessionExists: boolean) => { this.setState({ hostname: newHostname, sessionExists: sessionExists, username: newUsername, password: newPassword }); }} /> </div> : null} {this.state.visibleTab === "1" ? <div> <RemoteFileBrowser selectedOption={this.state.selectedOption} onSelectFileCallBack={this.onSelectTableFile} onReauthCallBack={this.onReauth} onSelectParserCallBack={this.onSelectParser} hostname={this.state.hostname} /> </div> : null} {this.state.visibleTab === "2"? <div> <TimeseriesParametersTab fileType={this.state.selectedOption} delimiter={this.state.delimiter} columnNames={this.state.columnNames} delimiterCallback={(delim: string) => { this.setState({ delimiter: delim }); }} columnCallback={(type: string) => { this.setState({ timeseriesColumn: type }); }} bincountCallback={(count: number) => { this.setState({ binCount: count }); }} resamplingCallback={(alg: string) => { this.setState({ resamplingAlg: alg }); }} linkageCallback={(clusterLinkage: string) => { this.setState({ clusterLinkageMeasure: clusterLinkage }); }} metricCallback={(metric: string) => { this.setState({ clusterMetric: metric }); }} /> </div> : null} {this.state.visibleTab === "3" ? <div> <RemoteFileBrowser selectedOption={this.state.selectedOption} onSelectFileCallBack={this.onSelectTimeseriesFile} onReauthCallBack={this.onReauth} onSelectParserCallBack={this.onSelectParser} hostname={this.state.hostname} /> </div> : null} {this.state.visibleTab === "4" ? <div> <RemoteFileBrowser selectedOption={this.state.selectedOption} onSelectFileCallBack={this.onSelectHDF5Directory} onReauthCallBack={this.onReauth} onSelectParserCallBack={this.onSelectParser} hostname={this.state.hostname} /> </div> : null} {this.state.visibleTab === "5" ? <div> <HPCParametersTab accountId={this.state.accountId} partition={this.state.partition} numNodes={this.state.numNodes} cores={this.state.cores} jobHours={this.state.jobHours} jobMin={this.state.jobMin} workDir={this.state.workDir} accountIdCallback={(id: string) => { this.setState({ accountId: id }); }} partitionCallback={(part: string) => { this.setState({ partition: part }); }} nodesCallback={(num: number) => { this.setState({ numNodes: num }); }} coresCallback={(numCores: number) => { this.setState({ cores: numCores }); }} hoursCallback={(hours: number) => { this.setState({ jobHours: hours }); }} minutesCallback={(mins: number) => { this.setState({ jobMin: mins }); }} workDirCallback={(dir: string) => { this.setState({ workDir: dir }); }} /> </div> : null} {this.state.visibleTab === "6" ? <div> <ModelNamingTab marking={this.state.marking} nameCallback={(name: string) => { this.setState({ timeseriesName: name }); }} descriptionCallback={(description: string) => { this.setState({ modelDescription: description }); }} markingCallback={(marking: any) => { this.setState({ selectedMarking: marking }); }} /> </div> : null} </div> ); } getFooterJSX(): JSX.Element[] { let footerJSX = []; if (this.state.visibleTab != "0") { footerJSX.push( <button key={1} type='button' className='btn btn-light mr-auto' onClick={this.back}> Back </button> ); } const isDisabled = this.state.visibleTab === '1' && this.state.selectedTablePath === '' const continueClassNames = isDisabled ? 'btn btn-primary disabled' : 'btn btn-primary'; if (this.state.visibleTab == '0' && this.state.sessionExists != true) { footerJSX.push( <ConnectButton key={3} text='Continue' loadingData={this.state.loadingData} hostname={this.state.hostname} username={this.state.username} password={this.state.password} callBack={this.connectButtonCallBack} />); } else { footerJSX.push( <button disabled={isDisabled} key={4} type='button' className={continueClassNames} onClick={this.continue}> Continue </button> ) } return footerJSX; } validateFields = () => { if (this.state.visibleTab === '1' && this.state.selectedTablePath === '') { return false; } else if (this.state.visibleTab === '2' && this.state.delimiter === '') { $('#delimiter').addClass('is-invalid'); return false; } else if (this.state.visibleTab === '3' && this.state.selectedXycePath === '') { return false; } else if (this.state.visibleTab === '4' && this.state.hdf5Directory === '') { return false; } else if (this.state.visibleTab === '5' && (this.state.accountId === '' || this.state.partition === '' || this.state.workDir === '')) { this.state.accountId === '' ? $('#account-id').addClass('is-invalid') : $('#account-id').removeClass('is-invalid') this.state.partition === '' ? $('#partition').addClass('is-invalid') : $('#partition').removeClass('is-invalid') this.state.workDir === '' ? $('#work-dir').addClass('is-invalid') : $('#work-dir').removeClass('is-invalid') return false; } else if (this.state.visibleTab === '6' && this.state.timeseriesName === '') { this.state.timeseriesName === '' ? $('#timeseries-name').addClass('is-invalid') : $('#timeseries-name').removeClass('is-invalid') return false; } else { return true; } } continue = () => { if (this.validateFields()) { if (this.state.visibleTab === '0' && this.state.selectedOption != 'hdf5') { this.setState({ visibleTab: '1' }, () => { client.get_user_config_fetch({ hostname: this.state.hostname }) .then((results) => { this.setState({ numNodes: results["config"]["slurm"]["nnodes"], cores: results["config"]["slurm"]["ntasks-per-node"], partition: results["config"]["slurm"]["partition"], jobHours: results["config"]["slurm"]["time-hours"], jobMin: results["config"]["slurm"]["time-minutes"], accountId: results["config"]["slurm"]["wcid"], workDir: results["config"]["slurm"]["workdir"], idCol: results["config"]["timeseries-wizard"]["id-column"], delimiter: results["config"]["timeseries-wizard"]["inputs-file-delimiter"], timeseriesColumn: results["config"]["timeseries-wizard"]["timeseries-name"] }); }); }); } else if (this.state.visibleTab === '0' && this.state.selectedOption == 'hdf5') { this.setState({ visibleTab: '2' }); } else if (this.state.visibleTab === '1') { this.setState({ visibleTab: '2' }); } else if (this.state.visibleTab === '2' && this.state.selectedOption == 'xyce') { this.setState({ visibleTab: '3' }); } else if (this.state.visibleTab === '2' && this.state.selectedOption == 'csv') { this.setState({ visibleTab: '5' }); } else if (this.state.visibleTab === '2' && this.state.selectedOption == 'hdf5') { this.setState({ visibleTab: '4' }); } else if (this.state.visibleTab === '3') { this.setState({ visibleTab: '5' }); } else if (this.state.visibleTab === '4') { this.setState({ visibleTab: '5' }); } else if (this.state.visibleTab === '5') { this.compute(); this.setState({ visibleTab: '6' }); } else if (this.state.visibleTab === '6') { this.name_model(); } } }; back = () => { if (this.state.visibleTab === '1') { this.setState({ visibleTab: '0' }); } else if (this.state.visibleTab === '2' && this.state.selectedOption != 'hdf5') { this.setState({ visibleTab: '1' }); } else if (this.state.visibleTab === '2' && this.state.selectedOption == 'hdf5') { this.setState({ visibleTab: '0' }); } else if (this.state.visibleTab === '3') { this.setState({ visibleTab: '2' }); } else if (this.state.visibleTab === '4') { this.setState({ visibleTab: '2' }); } else if (this.state.visibleTab === '5' && this.state.selectedOption == 'xyce') { this.setState({ visibleTab: '3' }); } else if (this.state.visibleTab === '5' && this.state.selectedOption == 'csv') { this.setState({ visibleTab: '2' }); } else if (this.state.visibleTab === '5' && this.state.selectedOption == 'hdf5') { this.setState({ visibleTab: '4' }); } else if (this.state.visibleTab === '6') { this.setState({ visibleTab: '5' }); } } getMarkings = () => { client.get_configuration_markings_fetch().then((markings) => { markings.sort(function (left: any, right: any) { return left.type == right.type ? 0 : left.type < right.type ? -1 : 1; }); if (markings.length) { const configured_markings = markings.map((marking:any) => {return {text: marking["label"], value: marking["type"]} }); this.setState({ marking: configured_markings }); this.create_model(); } }); } compute = () => { let userConfig: any = { "slurm": {}, "timeseries-wizard": {} }; userConfig["slurm"]["wcid"] = this.state.accountId; userConfig["slurm"]["partition"] = this.state.partition; userConfig["slurm"]["workdir"] = this.state.workDir; userConfig["slurm"]["time-hours"] = this.state.jobHours; userConfig["slurm"]["time-minutes"] = this.state.jobMin; userConfig["slurm"]["nnodes"] = this.state.numNodes; userConfig["slurm"]["ntasks-per-node"] = this.state.cores; userConfig["timeseries-wizard"]["id-column"] = this.state.idCol; userConfig["timeseries-wizard"]["inputs-file-delimiter"] = this.state.delimiter; userConfig["timeseries-wizard"]["timeseries-name"] = this.state.timeseriesColumn; client.set_user_config({ hostname: this.state.hostname, config: userConfig, success: function (response: any) { }, error: function (request: Request, status: any, reason_phrase: any) { console.log(reason_phrase); } }); this.on_slycat_fn(); } connectButtonCallBack = (sessionExists: boolean, loadingData: boolean) => { this.setState({ sessionExists, loadingData, }, () => { if (this.state.sessionExists) { this.continue(); } }); } onReauth = () => { // Session has been lost, so update state to reflect this. this.setState({ sessionExists: false, }); // Switch to login controls this.setState({ visibleTab: "2" }); } onSelectTableFile = (selectedPath: string, selectedPathType: string) => { // type is either 'd' for directory or 'f' for file if (selectedPathType === 'f') { var inputDirectory = selectedPath.substring(0, selectedPath.lastIndexOf('/') + 1); this.setState({ selectedTablePath: selectedPath }); this.setState({ inputDirectory: inputDirectory }); } if (this.state.selectedOption === 'csv') { client.get_time_series_names_fetch({ hostname: this.state.hostname, path: selectedPath, }).then((result) => { this.handleColumnNames(result); }) } } onSelectTimeseriesFile = (selectedPath: string, selectedPathType: string) => { // type is either 'd' for directory or 'f' for file if (selectedPathType === 'f') { this.setState({ selectedXycePath: selectedPath }); } } onSelectHDF5Directory = (selectedPath: string, selectedPathType: string) => { if (selectedPathType === 'd') { this.setState({ hdf5Directory: selectedPath }); } } onSelectParser = (selectedParser: string) => { this.setState({ parserType: selectedParser }); } handleColumnNames = (names: []) => { const columnNames = []; for (let i = 0; i < names.length; i++) { columnNames.push({ text: names[i], value: names[i] }); } this.setState({ columnNames: columnNames }); this.setState({ timeseriesColumn: columnNames[0]['value'] }); } cleanup = () => { this.setState(initialState); client.delete_model_fetch({ mid: this.state.model['id'] }); }; create_model = () => { client.post_project_models_fetch({ pid: this.state.project._id(), type: 'timeseries', name: this.state.timeseriesName, description: '', marking: this.state.marking[0]['value'], }).then((result) => { this.setState({ model: result }); }) }; generateUniqueId = () => { var d = Date.now(); var uid = 'xxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uid; }; on_slycat_fn = () => { let agent_function = 'timeseries-model'; let uid = this.generateUniqueId(); let fn_params = { 'timeseries_type': this.state.selectedOption, 'inputs_file': this.state.selectedTablePath, 'input_directory': this.state.inputDirectory, 'id_column': this.state.idCol, 'inputs_file_delimiter': this.state.delimiter, 'xyce_timeseries_file': this.state.selectedXycePath, 'timeseries_name': this.state.timeseriesColumn, 'cluster_sample_count': this.state.binCount, 'cluster_sample_type': this.state.resamplingAlg, 'cluster_type': this.state.clusterLinkageMeasure, 'cluster_metric': this.state.clusterMetric, 'workdir': this.state.workDir, 'hdf5_directory': this.state.hdf5Directory, 'retain_hdf5': true } var fn_params_copy = $.extend(true, {}, fn_params); if (fn_params.timeseries_type !== 'csv') { // Blank out timeseries_name fn_params_copy.timeseries_name = ""; } let json_payload: any = { "scripts": [ ], "hpc": { "is_hpc_job": true, "parameters": { "wckey": this.state.accountId, "nnodes": this.state.numNodes, "partition": this.state.partition, "ntasks_per_node": this.state.cores, "time_hours": this.state.jobHours, "time_minutes": this.state.jobMin, "time_seconds": 0, "working_dir": fn_params.workdir + "/slycat/" } } }; var hdf5_dir = fn_params.workdir + "/slycat/" + uid + "/" + "hdf5"; var pickle_dir = fn_params.workdir + "/slycat/" + uid + "/" + "pickle"; if (fn_params.timeseries_type === "csv") { json_payload.scripts.push({ "name": "timeseries_to_hdf5", "parameters": [ { "name": "--output-directory", "value": hdf5_dir }, { "name": "--id-column", "value": fn_params.id_column }, { "name": "--inputs-file", "value": fn_params.inputs_file }, { "name": "--inputs-file-delimiter", "value": fn_params.inputs_file_delimiter }, { "name": "--force", "value": "" } ] }); } else if (fn_params.timeseries_type === "xyce") { json_payload.scripts.push({ "name": "xyce_timeseries_to_hdf5", "parameters": [ { "name": "--output-directory", "value": hdf5_dir }, { "name": "--id-column", "value": fn_params.id_column }, { "name": "--timeseries-file", "value": fn_params.xyce_timeseries_file }, { "name": "--input-directory", "value": fn_params.input_directory }, { "name": "--force", "value": "" } ] }); } // # check if we have a pre-set hdf5 directory // if "hdf5_directory" in params and params["hdf5_directory"] != "": // hdf5_dir = params["hdf5_directory"] if (fn_params.timeseries_type === "csv") { json_payload.scripts.push({ "name": "compute_timeseries", "parameters": [ { "name": "--directory", "value": hdf5_dir }, { "name": "--timeseries-name", "value": fn_params.timeseries_name }, { "name": "--cluster-sample-count", "value": fn_params.cluster_sample_count }, { "name": "--cluster-sample-type", "value": fn_params.cluster_sample_type }, { "name": "--cluster-type", "value": fn_params.cluster_type }, { "name": "--cluster-metric", "value": fn_params.cluster_metric }, { "name": "--workdir", "value": pickle_dir }, { "name": "--hash", "value": uid } ] }); } else { json_payload.scripts.push({ "name": "compute_timeseries", "parameters": [ { "name": "--directory", "value": hdf5_dir }, { "name": "--cluster-sample-count", "value": fn_params.cluster_sample_count }, { "name": "--cluster-sample-type", "value": fn_params.cluster_sample_type }, { "name": "--cluster-type", "value": fn_params.cluster_type }, { "name": "--cluster-metric", "value": fn_params.cluster_metric }, { "name": "--workdir", "value": pickle_dir }, { "name": "--hash", "value": uid } ] }); } client.post_remote_command_fetch({ hostname: this.state.hostname, command: json_payload, }).then((results) => { const splitResult = results.errors.replace(/(\r\n\t|\n|\r\t)/gm, "").split(" "); const newJid = splitResult[splitResult.length - 1]; this.setState({ jid: newJid }); this.server_update_model_info(uid); }) }; server_update_model_info = (uid: string) => { if (!this.state.model["id"]) return void 0; var working_directory = this.state.workDir + "/slycat/" + uid + "/"; let agent_function_params = { "timeseries_type": this.state.selectedOption, "inputs_file": this.state.selectedTablePath, // "input_directory": this.state.selected_path, "input_directory": '', "id_column": this.state.idCol, "inputs_file_delimeter": this.state.delimiter, // "xyce_timeseries_file": this.state.timeseriesFile, "xyce_timeseries_file": '', "timeseries_name": this.state.timeseriesColumn, "cluster_sample_count": this.state.binCount, "cluster_sample_type": this.state.resamplingAlg, "cluster_metric": this.state.clusterMetric, "workdir": this.state.workDir, "hdf5_directory": this.state.hdf5Directory, "retain_hdf5": true }; client.put_model_parameter({ mid: this.state.model["id"], aid: 'jid', value: this.state.jid, input: true }); client.post_sensitive_model_command_fetch( { mid: this.state.model["id"], type: "timeseries", command: "update-model-info", parameters: { working_directory: working_directory, jid: this.state.jid, fn: "timeseries-model", hostname: this.state.hostname, username: this.state.username, fn_params: agent_function_params, uid: uid }, }).then((result) => { console.log(result); }); }; name_model = () => { // Validating // formElement.classList.add('was-validated'); // If valid... // if (formElement.checkValidity() === true) // { // Clearing form validation // formElement.classList.remove('was-validated'); // Creating new model client.put_model_fetch({ mid: this.state.model["id"], name: this.state.timeseriesName, description: this.state.modelDescription, marking: this.state.selectedMarking, }).then((result) => { this.go_to_model(); }) // } } go_to_model = () => { location = (server_root + 'models/' + this.state.model["id"]) as any; }; render() { return ( <ModalContent modalId={this.state.modalId} closingCallBack={this.cleanup} title={"Timeseries Wizard"} body={this.getBodyJsx()} footer={this.getFooterJSX()} /> ); } }
the_stack
import * as test_util from '../../test_util'; import * as conv_util from '../conv_util'; import {NDArrayMathCPU} from '../math_cpu'; import {Array1D, Array3D, Array4D, NDArray} from '../ndarray'; import * as conv_gpu from './conv_gpu'; import {GPGPUContext} from './gpgpu_context'; describe('conv_gpu', () => { function uploadConvolveDownload( x: Float32Array, aShapeRowColDepth: [number, number, number], weights: Float32Array, biases: Float32Array|null, resultDepth: number, fieldSize: number, stride: number, zeroPad?: number): Float32Array { zeroPad = zeroPad != null ? zeroPad : conv_util.computeDefaultPad(aShapeRowColDepth, fieldSize, stride); const xTexShapeRC: [number, number] = conv_util.computeTexShapeFrom3D(aShapeRowColDepth); const resultShapeRCD: [number, number, number] = conv_util.computeOutputShape3D( aShapeRowColDepth, fieldSize, resultDepth, stride, zeroPad); const weightsTexShapeRC: [number, number] = conv_util.computeWeightsTexShape( aShapeRowColDepth[2], resultDepth, fieldSize); const biasesTexShapeRC: [number, number] = [1, resultDepth]; const resultTexShapeRC: [number, number] = conv_util.computeTexShapeFrom3D(resultShapeRCD); const gpgpu = new GPGPUContext(); gpgpu.enableAutomaticDebugValidation(true); const shaderSource = conv_gpu.getFragmentShaderSource( aShapeRowColDepth, resultDepth, fieldSize, stride, zeroPad, biases != null); const program = gpgpu.createProgram(shaderSource); const xTex = gpgpu.createMatrixTexture(xTexShapeRC[0], xTexShapeRC[1]); const weightsTex = gpgpu.createMatrixTexture(weightsTexShapeRC[0], weightsTexShapeRC[1]); const biasesTex = biases != null ? gpgpu.createMatrixTexture(biasesTexShapeRC[0], biasesTexShapeRC[1]) : null; const resultTex = gpgpu.createMatrixTexture(resultTexShapeRC[0], resultTexShapeRC[1]); gpgpu.uploadMatrixToTexture(xTex, xTexShapeRC[0], xTexShapeRC[1], x); gpgpu.uploadMatrixToTexture( weightsTex, weightsTexShapeRC[0], weightsTexShapeRC[1], weights); if (biases != null) { gpgpu.uploadMatrixToTexture( biasesTex!, biasesTexShapeRC[0], biasesTexShapeRC[1], biases); } conv_gpu.convolve( gpgpu, program, xTex, weightsTex, biasesTex, resultTex, resultTexShapeRC); const result = gpgpu.downloadMatrixFromTexture( resultTex, resultTexShapeRC[0], resultTexShapeRC[1]); gpgpu.deleteMatrixTexture(resultTex); if (biasesTex != null) { gpgpu.deleteMatrixTexture(biasesTex); } gpgpu.deleteMatrixTexture(weightsTex); gpgpu.deleteMatrixTexture(xTex); gpgpu.deleteProgram(program); gpgpu.dispose(); return result; } function compareToCPU( xShape: [number, number, number], fSize: number, resultDepth: number, stride: number, pad: number) { const x = NDArray.randNormal<Array3D>(xShape); const weightsShape: [number, number, number, number] = [fSize, fSize, xShape[2], resultDepth]; const weights = NDArray.randNormal<Array4D>(weightsShape); const biases = NDArray.randNormal<Array1D>([weightsShape[3]]); const mathCPU = new NDArrayMathCPU(); const yCPU = mathCPU.conv2d(x, weights, biases, stride, pad); const yGPU = uploadConvolveDownload( x.getValues(), xShape, weights.getValues(), biases.getValues(), resultDepth, fSize, stride, pad); test_util.expectArraysClose(yGPU, yCPU.getValues(), 1e-5); } it('1x1x1 in, 1d out, 1x1 filter, 1 stride: [0] => [0]', () => { const a = new Float32Array([0]); const weights = new Float32Array([1]); const biases = new Float32Array([0]); const result = uploadConvolveDownload(a, [1, 1, 1], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(0); }); it('1x1x1 in, 1d out, 1x1 filter, 1 stride: [1] => [1]', () => { const a = new Float32Array([1]); const weights = new Float32Array([1]); const biases = new Float32Array([0]); const result = uploadConvolveDownload(a, [1, 1, 1], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(1); }); it('1x1x1 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([2]); const weights = new Float32Array([3]); const biases = new Float32Array([0]); const result = uploadConvolveDownload(a, [1, 1, 1], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(6); }); it('1x1x1 in, 1d out, 1x1 filter, 1 stride, null bias', () => { const a = new Float32Array([2]); const weights = new Float32Array([3]); const biases: Float32Array|null = null; const result = uploadConvolveDownload(a, [1, 1, 1], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(6); }); it('1x1x1 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([2]); const weights = new Float32Array([3]); const biases = new Float32Array([Math.PI]); const result = uploadConvolveDownload(a, [1, 1, 1], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(6 + Math.PI); }); it('1x1x2 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 1]); const weights = new Float32Array([3, 5]); const biases = new Float32Array([0, 0]); const result = uploadConvolveDownload(a, [1, 1, 2], weights, biases, 1, 1, 1); expect(result).toBeCloseTo(8); }); it('2x1x1 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2]); const weights = new Float32Array([5]); const biases = new Float32Array([0]); const result = uploadConvolveDownload(a, [2, 1, 1], weights, biases, 1, 1, 1); expect(result.length).toEqual(2); expect(result[0]).toBeCloseTo(5); expect(result[1]).toBeCloseTo(10); }); it('2x1x1 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2]); const weights = new Float32Array([5]); const biases = new Float32Array([Math.PI]); const result = uploadConvolveDownload(a, [2, 1, 1], weights, biases, 1, 1, 1); expect(result.length).toEqual(2); expect(result[0]).toBeCloseTo(5 + Math.PI); expect(result[1]).toBeCloseTo(10 + Math.PI); }); it('2x1x1 in, 2d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2]); const weights = new Float32Array([5, 6]); const biases = new Float32Array([0, 0]); const result = uploadConvolveDownload(a, [2, 1, 1], weights, biases, 2, 1, 1); expect(result.length).toEqual(4); expect(result[0]).toBeCloseTo(a[0] * weights[0]); expect(result[1]).toBeCloseTo(a[0] * weights[1]); expect(result[2]).toBeCloseTo(a[1] * weights[0]); expect(result[3]).toBeCloseTo(a[1] * weights[1]); }); it('2x1x1 in, 2d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2]); const weights = new Float32Array([5, 6]); const biases = new Float32Array([100, 200]); const result = uploadConvolveDownload(a, [2, 1, 1], weights, biases, 2, 1, 1); expect(result.length).toEqual(4); expect(result[0]).toBeCloseTo((a[0] * weights[0]) + biases[0]); expect(result[1]).toBeCloseTo((a[0] * weights[1]) + biases[1]); expect(result[2]).toBeCloseTo((a[1] * weights[0]) + biases[0]); expect(result[3]).toBeCloseTo((a[1] * weights[1]) + biases[1]); }); it('2x1x1 in, 3d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([2, 4]); const weights = new Float32Array([3, 5, 7]); const biases = new Float32Array([0, 0, 0]); const result = uploadConvolveDownload(a, [2, 1, 1], weights, biases, 3, 1, 1, 0); expect(result.length).toEqual(2 * 3); expect(result[0]).toBeCloseTo(a[0] * weights[0]); expect(result[1]).toBeCloseTo(a[0] * weights[1]); expect(result[2]).toBeCloseTo(a[0] * weights[2]); expect(result[3]).toBeCloseTo(a[1] * weights[0]); expect(result[4]).toBeCloseTo(a[1] * weights[1]); expect(result[5]).toBeCloseTo(a[1] * weights[2]); }); it('1x2x1 in, 1d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2]); const weights = new Float32Array([5]); const biases = new Float32Array([0]); const result = uploadConvolveDownload(a, [1, 2, 1], weights, biases, 1, 1, 1); expect(result.length).toEqual(2); expect(result[0]).toBeCloseTo(5); expect(result[1]).toBeCloseTo(10); }); it('2x1x2 in, 3d out, 1x1 filter, 1 stride', () => { const a = new Float32Array([1, 2, 3, 4]); const weights = new Float32Array([10, 11, 12, 13, 14, 15]); const biases = new Float32Array([0, 0, 0]); const result = uploadConvolveDownload(a, [2, 1, 2], weights, biases, 3, 1, 1); expect(result.length).toEqual(6); expect(result[0]).toBeCloseTo(a[0] * weights[0] + a[1] * weights[3]); expect(result[1]).toBeCloseTo(a[0] * weights[1] + a[1] * weights[4]); expect(result[2]).toBeCloseTo(a[0] * weights[2] + a[1] * weights[5]); expect(result[3]).toBeCloseTo(a[2] * weights[0] + a[3] * weights[3]); expect(result[4]).toBeCloseTo(a[2] * weights[1] + a[3] * weights[4]); expect(result[5]).toBeCloseTo(a[2] * weights[2] + a[3] * weights[5]); }); it('2x2x1 in, 1d out, 2x2 filter, 1 stride', () => { const x = new Float32Array([1, 2, 3, 4]); const w = new Float32Array([3, 1, 5, 0]); const bias = new Float32Array([0]); const result = uploadConvolveDownload(x, [2, 2, 1], w, bias, 1, 2, 2, 1); expect(result.length).toEqual(4); expect(result[0]).toBe(0); expect(result[1]).toBe(10); expect(result[2]).toBe(3); expect(result[3]).toBe(12); }); it('2x2x1 in, 1d out, 2x2 filter, 1 stride', () => { const x = new Float32Array([1, 2, 3, 4]); const w = new Float32Array([3, 1, 5, 0]); const bias = new Float32Array([-1]); const result = uploadConvolveDownload(x, [2, 2, 1], w, bias, 1, 2, 1, 0); expect(result.length).toEqual(1); expect(result[0]).toBe(19); }); it('2x2x1 in, 1d out, 2x2 filter, 1 stride, null bias', () => { const x = new Float32Array([1, 2, 3, 4]); const w = new Float32Array([3, 1, 5, 0]); const bias: Float32Array|null = null; const result = uploadConvolveDownload(x, [2, 2, 1], w, bias, 1, 2, 1, 0); expect(result.length).toEqual(1); expect(result[0]).toBe(20); }); it('2x2x1 in, 1d out, 2x2 filter, 1 stride, zeropad = 1', () => { const x = new Float32Array([1, 2, 3, 4]); const w = new Float32Array([3, 1, 5, 0]); const bias = new Float32Array([0]); const result = uploadConvolveDownload(x, [2, 2, 1], w, bias, 1, 2, 2, 1); expect(result.length).toEqual(4); expect(result[0]).toBe(0); expect(result[1]).toBe(10); expect(result[2]).toBe(3); expect(result[3]).toBe(12); }); it('5x5x3 in, 2d out, 3x3 filter, 2 stride', () => { /* weights: input: [ 1, -1, [1, 2, 2, 0, 0, 2, 2, 2, 1, 1, 2, 1, 1, 1, 2, 1, 0, 1, 2, 2, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, -1, 1, 2, 2, 0, 0, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, -1, 0, 1, 0, 0, 2, 0, 0, 0, 2, 0, 2, 0, 1, 0, 1, 2, -1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 2, 1, 0, 2, 0, 0, 0] 0, 1, -1, 1, biases: 1, 1, [1, 0] 1, 1, 0, 1, 0, 0, 0, 1, -1, -1, 1, 0, 1, -1, 1, 1, 1, 1, 1, -1, -1, 0, 1, 0, 0, 0, 1, -1, -1, -1, 1, 0, -1, 1, 0, -1, 0, 1] */ const input = new Float32Array([ 1, 2, 2, 0, 0, 2, 2, 2, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 0, 2, 2, 1, 1, 0, 0, 2, 1, 1, 0, 1, 2, 2, 0, 0, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 1, 0, 0, 2, 0, 0, 0, 2, 0, 2, 0, 1, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 2, 2, 1, 0, 2, 0, 0, 0 ]); const weights = new Float32Array([ 1, -1, 1, 0, -1, 1, -1, 0, -1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, -1, -1, 1, 0, 1, -1, 1, 1, 1, 1, 1, -1, -1, 0, 1, 0, 0, 0, 1, -1, -1, -1, 1, 0, -1, 1, 0, -1, 0, 1 ]); const biases = new Float32Array([1, 0]); const result = uploadConvolveDownload(input, [5, 5, 3], weights, biases, 2, 3, 2, 1); /* Filter centered at [0,0], zero-pad 1 column and 1 row 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 0 0 2 0 0 0 1 2 2 0 2 2 Weights, column [0] 1 1 -1 -1 -1 0 -1 1 1 0 0 0 -1 1 1 1 1 1 -1 1 0 1 -1 1 -1 0 0 Element-wise product (dot product before summation) 0 0 0 0 0 0 0 0 0 0 0 0 -1 2 2 0 0 2 0 0 0 1 -2 2 0 0 0 Sum of elements, plus bias of 1 (-1 + 2 + 2 + 2 + 1 + -2 + 2) + 1 == 7 */ expect(result[0]).toBeCloseTo(7); test_util.expectArraysClose( result, new Float32Array( [7, -8, 8, -2, 7, -2, 5, 5, 4, 6, 1, 2, -1, 3, 7, -2, 1, 4]), 0.00001); }); it('matches CPU on random input, d1=1,d2=1,f=2,s=1,p=0', () => { const inputDepth = 1; const inputShape: [number, number, number] = [8, 8, inputDepth]; const fSize = 2; const outputDepth = 1; const stride = 1; const zeroPad = 0; compareToCPU(inputShape, fSize, outputDepth, stride, zeroPad); }); it('matches CPU on random input, d1=1,d2=1,f=3,s=2,p=1', () => { const inputDepth = 1; const inputShape: [number, number, number] = [7, 7, inputDepth]; const fSize = 3; const outputDepth = 1; const stride = 2; const zeroPad = 1; compareToCPU(inputShape, fSize, outputDepth, stride, zeroPad); }); it('matches CPU on random input, d1=4,d2=3,f=2,s=1,p=0', () => { const inputDepth = 4; const inputShape: [number, number, number] = [8, 8, inputDepth]; const fSize = 2; const outputDepth = 3; const stride = 1; const zeroPad = 0; compareToCPU(inputShape, fSize, outputDepth, stride, zeroPad); }); it('matches CPU on random input, d1=3,d2=4,f=3,s=3,p=1', () => { const inputDepth = 3; const inputShape: [number, number, number] = [7, 7, inputDepth]; const fSize = 3; const outputDepth = 4; const stride = 3; const zeroPad = 1; compareToCPU(inputShape, fSize, outputDepth, stride, zeroPad); }); });
the_stack
import { DataCache, ListGetter, ServerError } from "@batch-flask/core"; import { Activity } from "@batch-flask/ui/activity"; import { LoadingStatus } from "@batch-flask/ui/loading/loading-status"; import { CloudPathUtils, StringUtils, log } from "@batch-flask/utils"; import { List } from "immutable"; import { AsyncSubject, BehaviorSubject, Observable, Subscription, interval, of, throwError } from "rxjs"; import { catchError, flatMap, map, mergeMap, share, shareReplay, switchMap, take, tap } from "rxjs/operators"; import { FileLoader } from "../file-loader"; import { File } from "../file.model"; import { FileTreeNode, FileTreeStructure } from "./file-tree.model"; export interface DeleteProgress { current: string; deleted: number; total: number; } export interface FileNavigatorConfig<TParams = any> { /** * Method that return the cache given the params. * This allow the use of targeted data cache which depends on some params. */ cache?: DataCache<File>; /** * Base path for the navigation. If you need to only show a sub folder. * If given it will act as if the root is that base path * and will not be aware of anyother folder at the same level and above */ basePath?: string; /** * Params to pass to the getter */ params: TParams; /** * List getter that is used to load the data */ getter: ListGetter<File, TParams>; /** * Callback called when navigating to a file. * @param filename Fullpath to the file to load. * @returns a new file loader */ getFile: (filename: string) => FileLoader; /** * Optional function to handle delete in the file navigator */ delete?: (filename: string) => Observable<any>; /** * Optional function to handle delete in the file navigator */ upload?: (path: string, localPath: string) => Observable<any>; /** * Optional callback that gets called when an error is returned listing files. * You can that way ignore the error or modify it. * Return null to ignore error. */ onError?: (error: ServerError) => ServerError; /** * Optional wildcard filter that will client side match files/blobs that end with * this filter. */ wildcards?: string; /** * Optional flag to tell the navigator to fetch all items. */ fetchAll?: boolean; } /** * Generic navigator class for a file explorer. * This can be extended for a node, task or blob file list */ export class FileNavigator<TParams = any> { public loadingStatus = LoadingStatus.Ready; public basePath: string; public tree: Observable<FileTreeStructure>; public error: ServerError; private _tree = new BehaviorSubject<FileTreeStructure>(null); private _getter: ListGetter<File, TParams>; private _deleteFile?: (filename: string) => Observable<any>; private _uploadFile?: (path: string, localPath: string) => Observable<any>; private _params: TParams; private _cache: DataCache<File>; private _fileDeletedSub: Subscription; private _wildcards: string; private _fetchAll: boolean; private _getFileLoader: (filename: string) => FileLoader; private _onError: (error: ServerError) => ServerError; constructor(config: FileNavigatorConfig<TParams>) { this.basePath = config.basePath || ""; this._getter = config.getter; this._params = config.params; this._getFileLoader = config.getFile; this._deleteFile = config.delete; this._uploadFile = config.upload; this._onError = config.onError; this._tree.next(new FileTreeStructure(this.basePath)); this.tree = this._tree.asObservable(); this._cache = config.cache; this._wildcards = config.wildcards; this._fetchAll = config.fetchAll; } /** * If this file navigator has delete file implemented */ public get canDeleteFile(): boolean { return Boolean(this._deleteFile); } /** * Load the inital data */ public init(): Observable<any> { if (this._cache) { this._fileDeletedSub = this._cache.deleted.subscribe((key: string) => { this._removeFile(key); }); } return this._loadFilesInPath(""); } /** * @param path Path of the file/directory to navigate to * @param openInNewTab If its the path to a file it will open the file in a new tab */ public loadPath(path: string) { const obs = this.getNode(path).pipe( mergeMap((node) => { return this._loadFilesInPath(path); }), shareReplay(1), ); obs.subscribe({ error: () => null }); // Make sure it trigger at least once return obs; } public loadFile(path: string) { return this._loadFilesInPath(path, true); } public listAllFiles(path: string = ""): Observable<List<File>> { return this._loadPath(path, true); } public listFiles(path: string = "", limit?: number): Observable<List<File>> { return this._loadPath(path, true, limit); } /** * Get the node at the path. If the node is not in the tree it will list * @param path Path of the node * @returns the node if it exsits or null if not */ public getNode(path: string): Observable<FileTreeNode> { const node = this._tree.value.getNode(path); if (node.isUnknown) { return this._checkIfDirectory(node).pipe( map(() => { return this._tree.value.getNode(path); }), catchError((e) => { return of(null); }), ); } else { return of(node); } } public getFile(path: string): FileLoader { const node = this._tree.value.getNode(path); const loader = this._getFileLoader(node.originalPath); loader.basePath = this.basePath; return loader; } public refresh(path: string = ""): Observable<any> { return this._loadFilesInPath(path); } public loadFilesInPath(path: string = ""): Observable<any> { const node = this._tree.value.getNode(path); if (node.isDirectory) { if (!this._tree.value.isPathLoaded(path)) { return this._loadFilesInPath(path); } } return of(node); } public isDirectory(path: string): Observable<boolean> { const node = this._tree.value.getNode(path); return this._checkIfDirectory(node); } /** * Add a folder to the navigator that is only visible from the UI until some files get added to it * @param path Path to the folder */ public addVirtualFolder(path: string) { const tree = this._tree.value; tree.addVirtualFolder(path); this._tree.next(tree); } public deleteFile(filename: string): Observable<any> { if (!this._deleteFile) { log.error("Cannot delete file with this file navigator has delete is not implemented"); return; } return this._deleteFile(filename); } public uploadFile(path: string, localPath: string): Observable<any> { if (!this._uploadFile) { log.error("Cannot delete file with this file navigator has delete is not implemented"); return; } return this._uploadFile(path, localPath); } public deleteFiles(files: string[]): Observable<DeleteProgress> { if (!this._deleteFile) { log.error("Cannot delete file with this file navigator has delete is not implemented"); return; } return interval(100).pipe( take(files.length), switchMap((i) => { return this._deleteFile(files[i]).pipe(map(() => { this._removeFile(files[i]); return { deleted: i, total: files.length, current: files[i] }; })); }), share(), ); } public deleteFolder(folder: string): Observable<DeleteProgress> { if (!this._deleteFile) { log.error("Cannot delete file with this file navigator has delete is not implemented"); return; } return this.listAllFiles(CloudPathUtils.asBaseDirectory(folder)).pipe( flatMap((files) => { return this.deleteFiles(files.map(x => x.name).toArray()); }), tap(() => { this._removeFile(folder); }), share(), ); } public createFolderDeletionActivityInitializer(folder: string): Observable<Activity[]> { return this.listAllFiles(CloudPathUtils.asBaseDirectory(folder)).pipe( map(fileList => { return fileList.toArray().map(file => { let name; let obs; // check whether the given filepath is to a file or a directory if (file.isDirectory) { name = `Deleting folder ${file.name}`; obs = this.createFolderDeletionActivityInitializer(file.name); } else { name = `Deleting file ${file.name}`; obs = this.deleteFile(file.name); } // map the file/folder to a file/folder deletion activity const initializer = () => { return obs; }; return new Activity(name, initializer); }); }), tap(() => { this._removeFile(folder); }), ); } public dispose() { if (this._fileDeletedSub) { this._fileDeletedSub.unsubscribe(); } } private _removeFile(key: string) { const tree = this._tree.value; tree.deleteNode(key); this._tree.next(tree); } /** * Given a path will return all the files underneath * @param path Path to the folder to load * @param recursive If it should list sub folders content too(Default: false) * @param limit If it should limit the results */ private _loadPath(path: string, recursive = false, limit?: number): Observable<List<File>> { let obs: Observable<List<File>>; if (limit) { obs = this._getter.fetch(this._params, { recursive: recursive || this._fetchAll, folder: path, limit, }, true).pipe(map(x => x.items)); } else { obs = this._getter.fetchAll(this._params, { recursive: recursive || this._fetchAll, folder: path, }); } return obs.pipe( map((files) => { if (!this._wildcards) { return files; } const filtered = files.filter((file) => file.isDirectory || this._checkWildcardMatch(file.name)); return List(filtered); }), ); } private _checkWildcardMatch(filename: string): boolean { const result = this._wildcards.split(",").find(wildcard => { return StringUtils.matchWildcard(filename, wildcard, false); }); return Boolean(result); } private _checkIfDirectory(node: FileTreeNode): Observable<boolean> { if (!node.isUnknown) { return of(node.isDirectory); } return this._loadPath(this._getFolderToLoad(node.path, false), false, 1).pipe( map((files: List<File>) => { const tree = this._tree.value; if (files.size === 0) { tree.markFileAsLoadedAndUnkown(node.path); this._tree.next(tree); return false; } const file = files.first(); tree.addFiles(files); this._tree.next(tree); return file.isDirectory; }), catchError((e) => { const tree = this._tree.value; tree.markFileAsLoadedAndUnkown(node.path); this._tree.next(tree); return throwError(e); }), share(), ); } private _loadFilesInPath(path: string, isFile = false): Observable<FileTreeNode> { this.loadingStatus = LoadingStatus.Loading; const tree = this._tree.value; const node = tree.getNode(path); if (node.loadingStatus === LoadingStatus.Loading && !node.virtual) { return of(null); } node.markAsLoading(); const output = new AsyncSubject<FileTreeNode>(); this._loadPath(isFile ? path : this._getFolderToLoad(path)).subscribe({ next: (files: List<File>) => { this.loadingStatus = LoadingStatus.Ready; const tree = this._tree.value; tree.setFilesAt(path, files); const node = tree.getNode(path); node.markAsLoaded(); this._tree.next(tree); output.next(node); output.complete(); }, error: (error) => { if (this._onError) { error = this._onError(error); if (!error) { return; } } this.error = error; const tree = this._tree.value; const node = tree.getNode(path); node.loadingStatus = LoadingStatus.Error; this._tree.next(tree); output.next(node); output.complete(); }, }); return output; } private _getFolderToLoad(path: string, asDirectory = true) { const fullPath = [this._normalizedBasePath, path].filter(x => Boolean(x)).join(""); if (fullPath) { if (asDirectory) { return CloudPathUtils.asBaseDirectory(fullPath); } else { return fullPath; } } return null; } private get _normalizedBasePath() { return this.basePath ? CloudPathUtils.asBaseDirectory(this.basePath) : this.basePath; } }
the_stack
declare namespace Editor { /** MAIN PROCESS */ export const argv:number; export const dev:string; export const frameworkPath:string; export const isClosing:boolean; export const lang:string; export const logfile:string; export const versions:string; export function init(opts:{i18n?:any[],layout?:string,'main-menu'?:Function,profile?:object}) export function run(url:string,opts:object); export function reset(); export function loadPackagesAt(path:string,callback:Function); export function loadAllPackages(callback:Function); export function require(url:string); export function url(url:string); export function watchPackages(callback:Function); /** Console Module */ export function clearLog(pattern:string,useRegex:boolean); export function connectToConsole(); export function fatal(...args:any[]); export class App { static focused:boolean; static home:string; static name:string; static path:string; static version:string; static emit(eventName:string,...arg: any); static extends(proto:object); static off(eventName:string,listener:Function); static on(eventName:string,listener:Function); static once(eventName:string,listener:Function); } export class Debugger { static debugPort:string; static isNodeInspectorEnabled:boolean; static isReplEnabled:boolean; static activeDevtron(); static toggleNodeInspector(); static toggleRepl(); static startNodeInspector(); static startRepl(); static stopNodeInspector(); static stopRepl(); } export class DevTools { static focus(editorWin:Editor.Window); static executeJavaScript(editorWin:Editor.Window,script:string); static enterInspectElementMode(editorWin:Editor.Window); } export class Profile { static load(name:string,defaultProfile:object); static register(type:string,path:string); static reset(); } export class Worker { constructor(name:string,options?:{workerType:'renderer'|'main',url:string}); close(); dispose(); on(message:string,...args: any[]); start(argb:object,cb:Function); } /** RENDERER PROCESS (WEB PAGE) */ export function log(msg: string|any, ...subst: any[]): void; export function info(msg: string|any, ...subst: any[]): void; export function warn(msg: any, ...subst: any[]): void; export function error(msg: any, ...subst: any[]): void; export function trace(level?:string, ...args: any[]): void; export function success(...args: any[]): void; export function failed(...args: any[]): void; /** * Returns the file path (if it is registered in custom protocol) or url (if it is a known public protocol). * @param url */ export function url(url:string): string; /** * * @param url * @param cb */ export function loadProfile(url:string,cb?:Function): void; // export function import(urls:string|string[]); export class Dialog { static openFile(...args: any[]): void; static savaFile(...args: any[]): void; static messageBox(...args: any[]): void; }; export class Ipc { static cancelRequest(sessionID:string): void; static option(opts:{excludeSelf:boolean} | object): void; static sendToAll(message:string,...args: any[],option?:object): void; static sendToMain(message:string,...args: any[],callback?:Function,timeout?:number): void; static sendToMainWin(message:string,...args: any[]): void; static sendToPackage(pgkName:string,message:string,...args: any[]):void; static sendToPanel(panelID:string,message:string,...args: any[],callback?:Function,timeout?:number); static sendToWins(message:string,...args: any[],option?:object) }; export class MainMenu { static apply(): void; static add(path:string,template:array|object): void; static init(): void; static remove(path:string): void; static set(path:string,options:object | {icon:any,enabled:boolean,visible:boolean,checked:boolean}): void; static update(path:string,template:array|object): void; } export class Menu { constructor(template:array|object,webContents?:{path?:string,message?:string,command?:string,params?:any[],panel?:string,dev?:string}); add(path:string,template:array|object); clear(); dispose(); insert(path:string,pos:number,template:array|object); remove(path:string); reset(template:array|object); set(path:string,options?:{icon?:any,enabled?:boolean,visible?:boolean,checked?:boolean}) update(path:string,template:array|object); static showDev:boolean; static convert(template:array|object,webContents:object); static getMenu(name:string); static register(name:string,fn:Function,force:boolean); static unregister(name:string); /** renderer process */ popup(template:{x:number,y:number}): void; register(name:string,tmpl:object,force?:boolean): void; walk(template:array|object,fn:Function): void; } export class Package { static load(path:string,callback:Function); static unload(path,callback:Function); static reload(path:string,callback:Function); static panelInfo(panelID:string); static packageInfo(path:string); static packagePath(name:string); static addPath(path:string); static removePath(path:string); static resetPath(); static find(name:string); static lang:string; static path:string; static versions:string; /** renderer process */ static reload(name:string): void; static queryInfo(name:string,cb:Function): void; static queryInfos(cb:Function): void; } export class Panel { static close(panelId:string,cb:Function); static findWindow(panelID:string); static templateUrl:string; /** renderer process */ static close(panelID:string): void; static dock(panelID:string,frameEl:HTMLElement): void; static dumpLayout(): void; static newFrame(panelID:string,cb:Function): void; static extend(proto:object): void; static find(panelID:string); static focus(panelID:string): void; static getFocusedPanel(); static getPanelInfo(panelID:string); static isDirty(panelID:string): boolean; static open(panelID:string,argv:object):void; static popup(panelID:string):void; static undock(panelID:string); static panels:any[]; } export class Protocol { static register(protocol:string,fn:Function): void; } export class Window { constructor(name:string,options?:{windowType?:'dockable'|'float'|'fixed-size'|'quick',save?:boolean}); adjust(x:number,y:number,w:number,h:number); close(); closeDevTools(); dispose(); emptyLayout(); focus(); forceClose(); hide(); load(editorUrl:string,argv:object); minimize(); openDevTools(options?:{mode?:'right'|'bottom',undocked?:any,detach?:any}) popupMenu(template:object,x?:number,y?:number); resetLayout(url:string); restore(); show(); send(message:string,...args: any[]); isFocused:boolean; isLoaded:boolean; isMainWindow:boolean; isMinimized:boolean; panels:string[]; static defaultLayoutUrl:string; static main:Editor.Window; static windows:Editor.Window[]; static addWindow(win:Editor.Window) static find(param:string|BrowserWindow|WebContents) static removeWindow(win:Editor.Window) /** renderer process */ static open(name:string,url:string,options:object): void; static focus(): void; static load(url:string,argb:object): void; static resize(w:number,h:number,useContentSize:boolean): void; static resizeSync(w:number,h:number,useContentSize:boolean): void; static center():void; } export class UI { /** DOM Utils Module */ static createStyleElement(url:string): void; static clear(element:HTMLElement): void; static index(element:HTMLElement): void; static parentElement(element:HTMLElement): void; static offsetTo(el:HTMLElement,parentEl:HTMLElement):void; static walk(el:HTMLElement,opts?:object,cb?:Function):void; static fire(element:HTMLElement,eventName:string,opts:object): void; static acceptEvent(event); static installDownUpEvent(element:HTMLElement): void; static inDocument(el:HTMLElement):boolean; static inPanel(el:HTMLElement):boolean; static isVisible(el:HTMLElement):boolean; static isVisibleInHierarchy(el:HTMLElement):boolean; static startDrag(cursor:string,event,onMove:Function,onEnd:Function,onWheel:Function): void; static cancelDrag(): void; static addDragGhost(cursor:stirng): void; static removeDragGhost(): void; static addHitGhost(cursor:string,zindex:number,onhit:Function); static removeHitGhost(): void; static addLoadingMask(options:object,onclick:Function); static removeLoadingMask(): void; static toHumanText(text:string): void; static camelCase(text:string): void; static kebabCase(text:string): void; /** Element Utils Module */ static getProperty(type:string); static parseArray(txt:string): array; static parseBoolean(txt:string):boolean; static parseColor(txt:string):object; static parseObject(txt:string):object; static parseString(txt:string):string; static regenProperty(propEl:HTMLElement,cb:Function):void; static registerElement(name:string,def:object):void; static registerProperty(type:string,protoOrUrl:object|string):void; static unregisterProperty(type:string):void; /** Focus Module */ static focus(element:HTMLElement):void; static focusParent(element:HTMLElement):void; static focusNext():void; static focusPrev():void; static focusedElement:HTMLElement; static focusedPanelFrame:any; static lastFocusedElement:HTMLElement; static lastFocusedPanelFrame:any; /** Resources Module */ static getResource(url:string); static importResource(url:string):Promise<any>; static importScript(url:string):Promise<any>; static importScripts(urls:string[]):Promise<any>; static importStylesheet(url:string):Promise<any>; static importStylesheets(urls:string[]):Promise<any>; static importTemplate(url:string):Promise<any>; static loadGlobalScript(url:string,cb:Function) /** Settings */ static Settings:{stepFloat:Function,stepInt:Function,shiftStep:Function}; /** DragDrop */ /** 暂无 */ } export class Dockutils { root:HTMLElement; resizerSpace:object; } /** RENDERER PROCESS (WEB PAGE) END */ /** -------------------------------------------------------------------------------------- */ /** MODULES FOR BOTH PROCESSES */ export function KeyCode(key:number|string); export const isDarwin:boolean; export const isElectron:boolean; export const isMainProcess:boolean; export const isNative:boolean; export const isNode:boolean; export const isPureWeb:boolean; export const isRendererProcess:boolean; export const isRetina:boolean; export const isWin32:boolean; export class Easing { static linear(k:number); static fade(k:number); static quadIn(k:number); static quadOut(k:number); static quadInOut(k:number); static quadOutIn(k:number); static cubicIn(k:number); static cubicOut(k:number); static cubicInOut(k:number); static cubicOutIn(k:number); static quartIn(k:number); static quartOut(k:number); static quartInOut(k:number); static quartOutIn(k:number); static quintIn(k:number); static quintOut(k:number); static quintInOut(k:number); static quintOutIn(k:number); static sineIn(k:number); static sineOut(k:number); static sineInOut(k:number); static sineOutIn(k:number); static expoIn(k:number); static expoOut(k:number); static expoInout(k:number); static expoOutIn(k:number); static circIn(k:number); static circOut(k:number); static circInOut(k:number); static circOutIn(k:number); static elasticIn(k:number); static elasticOut(k:number); static elasticInOut(k:number); static elasticOutIn(k:number); static backIn(k:number); static backOut(k:number); static backInOut(k:number); static backOutIn(k:number); static bounceIn(k:number); static bounceOut(k:number); static bounceInOut(k:number); static bounceOutIn(k:number); } export class IpcListener { on(message:string,callback:Function); once(message:string,callback:Function); clear(); } export class JS { static addon(obj:object,...args: object[]); static assign(obj:object,...args: object[]); static assignExcept(obj:object,src:object,except:array); static clear(obj:object); static copyprop(name:string,source:objcet,target:object); static extend(cls:Function,base:Function); static extract(obj:object,propNames:string[]); static getPropertyByPath(obj:object,path:string); } export class Math { static EPSILON:number; static MACHINE_EPSILON:number; static TWO_PI:number; static HALF_PI:number; static D2R:number; static R2D:number; static deg2rad(degree:number):number; static rad2deg(radius:number):number; static rad180(radius:number):number; static rad360(radius:number):number; static deg180(degree:number):number; static deg360(degree:number):number; static randomRange(min:number,max:number):number; static randomRangeInt(min:number,max:number):number; static clamp(val:number,min:number,max:number):number; static clamp01(val:number,min:number,max:number):number; static randomRangeInt(min:number,max:number):number; static calculateMaxRect(out,p0,p1,p2,p3):any; static lerp(from:number,to:number,ratio:number):number; static numOfDecimals(val:number):number; static numOfDecimalsF(val:number):number; static toPrecision(val:number,precision:number):number; static bezier(c0:number,c1:number,c2:number,c3:number,t:number); static solveCubicBezier(c0:number,c1:number,c2:number,c3:number,x:number); } export class Selection { static register(type:string); static reset(); static local(); static confirm(); static cancel(); static confirmed(type:string): boolean; static select(type:string,id:string,unselectOthers?:boolean,confirm?:boolean); static unselect(type:string,id:string,confirm:boolean); static hover(type:string,id:string); static setContext(type:string,id:string); static patch(type:string,srcID:string,destID:string); static clear(type:string); static hovering(type:string); static contexts(type:string); static curActivate(type:string); static curGlobalActivate(type:string); static curSelection(type:string); static filter(items:string[],mode:string,func:Function); } export class Undo { static undo(); static redo(); static add(id:string,info:string); static commit(); static cancel(); static collapseTo(index:number); static save(); static clear(); static reset(); static dirty(); static setCurrentDescription(desc:string); static register(id:string,cdm:{undo:Function,redo:Function,dirty:Function}) static Command:{ undo:Function; redo:Function; dirty:Function; } } export class Utils { static padLeft(text:string,width:number,ch:string); static toFixed(value:number,precision:number,optionals:number) static formatFrame(frame:number,frameRate:number) static smoothScale(curScale:number,delta:number) static wrapError(err:Error) static arrayCmpFilter(items:any[],func:Function) static fitSize(srcWidth:number,srcHeight:number,destWidth:number,destHeight:number) static prettyBytes(num:number) static run(execFile:string,...args:any[]); } export class i18n { static format(text:string):string; static formatPath(path:string):string; static t(key:string,option:object); static extend(phrases:object); static replace(phrases:object); static unset(phrases:object); static clear(); } /** MODULES FOR BOTH PROCESSES END*/ /** -------------------------------------------------------------------------------------------- */ } declare namespace Editor.assetdb { export function _checkIfMountValid(assetdb, fspath) export function _deleteImportedAssets(); export function _removeUnusedMeta(assetdb, metapath) export function _backupUnusedMeta(assetdb, metapath, force):string; export function _backupAsset(assetdb, filePath) export function _removeUnusedImportFiles() export function _removeUnusedMtimeInfo() export function _scan(assetdb, fspath, opts, cb) export function _checkIfReimport(assetdb, fspath, cb) export function _initMetas(assetdb, fspath, cb) export function _importAsset(assetdb, fspath, cb) export function _postImportAsset(assetdb, assetInfo, cb) export function _fillInResults(assetdb, path, meta, results) export function _refresh() export function _preProcessMoveInput() export function _copyFiles() export function _generateSubMetaDiff() export function _deleteAsset() export function init(cb?:Function) export function refresh(url, cb?:Function) export function deepQuery(cb?:Function) export function queryAssets(pattern:string, assetTypes:string,cb) export function queryMetas(pattern:string, type:string, cb?:Function) export function move(srcUrl, destUrl, cb?:Function) // export function delete(urls, cb?:Function) export function create(url, data, cb?:Function) export function saveExists(url, data, cb?:Function) // export function import(rawfiles, url, cb?:Function) export function saveMeta(uuid, jsonString, cb?:Function) export function exchangeUuid(urlA, urlB, cb?:Function) export function clearImports(url, cb?:Function) export function register(extname, folder, metaCtor) export function unregister(metaCtor) export function getRelativePath(fspath):string export function getAssetBackupPath(filePath) export function setEventCallback(cb) export class remote { static urlToUuid(url):string; static fspathToUuid(fspath):string; static uuidToFspath(uuid):string; static uuidToUrl(uuid):string; static fspathToUrl(fspath):string; static urlToFspath(url):string; static exists(url):string; static existsByUuid(uuid):string; static existsByPath(fspath):string; static isSubAsset(url):boolean; static isSubAssetByUuid(uuid):boolean; static isSubAssetByPath(fspath):boolean; static containsSubAssets(url):boolean; static containsSubAssetsByUuid(uuid):boolean; static containsSubAssetsByPath(path):boolean; static assetInfo(url):object; static assetInfoByUuid(uuid):object; static assetInfoByPath(fspath):object; static subAssetInfos(url):any[]; static subAssetInfosByUuid(uuid):any[]; static subAssetInfosByPath(fspath):any[]; static loadMeta(url):object; static loadMetaByUuid(uuid):object; static loadMetaByPath(fspath):object; static isMount(url):boolean; static isMountByPath(fspath):boolean; static isMountByUuid(uuid):boolean; static mountInfo(url) static mountInfoByUuid(uuid) static mountInfoByPath(fspath) static mount(path, mountPath, opts, cb?:Function) static attachMountPath(mountPath, cb?:Function) static unattachMountPath(mountPath, cb?:Function) static unmount(mountPath, cb?:Function) } };
the_stack
import { createI18n } from 'vue-i18n/dist/vue-i18n.cjs.js' const i18n = createI18n({ locale: 'eng', fallbackLocale: 'eng', messages: { chs: { manager: { level: { primary: '初级', intermediate: '中级', senior: '高级', super: '管理员', unknown : '未知' } }, node: { state: { not:'未知', normal : '在线', warn : '异常', error : '停机', unknown : '离线' }, card:{ state:'状态', nodeFunc:'方法', nodeReport:'报告' } }, nodeFunc:{ card:{ level: '权限', call: '方法', node: '节点' }, parameterTypeName: { form : '表单', unknown : '未知' }, returnTypeName: { notReturn: '无', error: '错误', text: '文本', json: '对象', link: '链接', image: '图片', media: '媒体', file: '文件', table : '表格', charts : '图表', unknown : '未知' } }, nodeFuncCall:{ state: { normal : '成功', warn : '异常', error : '失败', timeout : '超时', unknown : '未知' }, card:{ call: '请求方法', history: '历史记录' }, table:{ id:'编号', caller:'请求者', state:'状态', parameter:'参数', returnVal:'返回值', date:'日期' } }, nodeReport:{ card:{ level: '权限', call: '方法', interval: '频率', node: '节点', viewReport:'查看报告' } }, nodeReportVal:{ table:{ id:'编号', date:'日期' } }, nodeNotify:{ table:{ id:'编号', sender:'通知者', sendType:'通知源', message:'消息', date:'日期' }, senderType:{ user: "用户", node: "节点", unknown : '未知' }, state: { not : '信息', unknown : '未知', normal : '成功', warn : '警告', error : '错误' }, }, nodeResource:{ table:{ id:'编号', uploader:'上传者', uploaderType:'上传源', name:'资源名', size:'资源大小', downLoadCnt:'下载次数', state:'状态', date:'上传日期' }, uploaderType:{ user: "用户", node: "节点", unknown : '未知' }, state:{ normal:'正常', invalid:'已失效' } }, defaultVal:{ unknown : '未知' }, time: { manual: '手动', ms : '毫秒', s : '秒', min : '分', hour : '时', day : '天', once :'次' }, filter:{ invalidTag: '无效的标签', existTag: ' 已添加在<{name}>中', start:'过滤器已激活', stop:'过滤器未激活', tagName: { ID: 'ID', nodeID: '节点ID', }, tips:{ select: '请选择', submit: '提交', startTime: '起始时间', endTime: '结束时间', timeError:'起始时间不能超过结束时间', clearTags: '清空{msg}标签', }, node:{ name:'节点名', state:'状态', time:'更新时间', }, nodeFunc:{ nodeID:'节点ID', nodeName:'节点名', name:'节点方法名', level:'权限', time:'更新时间', }, nodeReport:{ nodeID:'节点ID', nodeName:'节点名', name:'节点报告名', level:'权限', time:'更新时间', }, nodeNotify:{ message:'通知消息', sender:'通知者', senderType:'通知源', state:'状态', time:'通知时间', }, nodeResource:{ name:'资源名', uploader:'上传者', uploaderType:'上传源', state:'状态', time:'上传时间', } }, request:{ error:{ fail: '请求失败 ({msg})', header: '读取信息错误 ({msg})', body: '读取数据错误 ({msg})', file: '读取文件数据错误 ({msg})', checkFile: '文件信息校验失败 ({msg})', marshal: '数据编码失败 ({msg})', unmarshal: '数据解码失败 ({msg})', register: '注册失败 ({msg})', loginWithAccount: '登录失败 ({msg})', passwordWithAccount: '登录失败 ({msg})', loginWithToken: '登录信息校验失败 ({msg})', levelLow: '权限不足 ({msg})', request: '请求错误 ({msg})', } }, websocket:{ notSupport: '当前浏览器不支持websocket协议, 部分功能将无法使用', initError:'websocket初始化错误: ', reconnect:'正在尝试重新连接服务器......{msg}次', reconnectSuccess:'网络连接成功', disConnect:'网络连接已断开: ', orderError:'错误的websocket指令: ', deleteNotify:'您的帐号 {msg} 已被管理员注销', levelChanged:'您的帐号 {msg} 发生权限变更, 请重新登录' }, confirm:{ delete:'此操作将永久删除相关数据, 是否继续?', warn: '警告', ok:'确定', cancel:'取消' }, setting:{ system:'系统设置', user:'用户设置', topLink:'顶栏设置', systemSet:{ user:'用户:', level:'权限:', fixPage:'固定分页:', language:'语言选择:', modifyPassword:'修改密码:', modifyPasswordButton:'修改', modifyPasswordDialog:'修改密码', loginOut:'退出登录:', loginOutButton:'退出', autoRefresh:'数据同步(秒/次):', }, topMenuSet:{ id:'外链ID', name:'名称', link:'链接', operate:'操作', deleteSuccess:'删除成功', createSuccess:'创建成功', updateSuccess:'更新成功' }, userSet:{ id:'用户ID', userName:'用户名', nickName:'昵称', level:'权限', operate:'操作', addUser:'新增帐号', deleteSuccess:'删除成功', updateSuccess:'更新成功' } }, file:{ downloadTips:'点击下载文件', uploadTips:'点击上传', exceedTips:'上传文件数量超出最大限制', failTips:'上传文件失败', forbidDelHistoryFile:'禁止删除历史文件' }, autoRefresh:{ start:'自动同步已开启', stop:'自动同步已停止' }, json:{ formatFail:'json格式化失败: ' }, level:{ selectTips:'请选择权限等级' }, passwordReset:{ originalPassword:'原密码', newPassword:'新密码', confirmPassword:'确认密码', passwordInconsistent:'两次输入密码不一致', passwordModifySuccess:'密码修改成功, 请重新登录', modifyButton: '修改' }, sideBar:{ node:'节点', nodeFunc:'方法', nodeReport:'报告', nodeResource:'资源', nodeNotify:'通知', nodeTest:'测试', errorKey:'错误的侧边栏菜单选项: ' }, dialog:{ frame:{ setting:'设置(ctrl+q)', sync:'同步(ctrl+space)', update:'刷新(~)', fullScreen:'全屏(ctrl+enter)', close:'关闭(esc)' }, nodeFuncCall:{ form: '表单', json: 'JSON', emptyParameter:'此方法沒有设置参数', emptyReturnVal:'此次调用方法沒有返回值', resetButton:'重置', submitButton:'提交', jsonCheckFail:'参数校验失败' }, nodeReportVal:{ waitResult:'请等待结果返回...', setting:'设置', resultSet:'结果集(条):', sync:'数据同步(秒/次):', okButton:'确定' } }, home:{ parseConfigFail:'用户配置解析失败, 将使用默认配置' }, login:{ userName:'用户名', password:'密码', login:'登录', logining:'登录中...', autoLogin:'自动登录', register:'注册帐号', createManager:'创建管理员', loginSuccess:'登录成功' }, register:{ nickName:'昵称', userName:'用户名', password:'密码', level:'权限', confirmPassword:'确认密码', registerButton:'注册', registerSuccess:'注册成功', passwordInconsistent:'两次输入密码不一致' }, empty:{ emptyData:'暂无数据' }, notFound:'抱歉, 您访问的页面不存在', notFoundToHome:'返回至首页', notFoundToUp:'返回上一级' }, eng: { manager: { level: { primary: 'Primary', intermediate: 'Intermediate', senior: 'Advanced', super: 'Administrators', unknown : 'Unknown' } }, node: { state: { not:'Unknown', normal : 'Online', warn : 'Abnormal', error : 'Shutdown', unknown : 'Offline' }, card:{ state:'State', nodeFunc:'Method', nodeReport:'Report' } }, nodeFunc:{ card:{ level: 'Level', call: 'Method', node: 'Node' }, parameterTypeName: { form : 'Form', unknown : 'Unknown' }, returnTypeName: { notReturn: 'Nothing', error: 'Error', text: 'Text', json: 'Object', link: 'Link', image: 'Picture', media: 'Media', file: 'File', table : 'Table', charts : 'Chart', unknown : 'Unknown' } }, nodeFuncCall:{ state: { normal : 'Success', warn : 'Abnormal', error : 'Fail', timeout : 'Timeout', unknown : 'Unknown' }, card:{ call: 'Request', history: 'History' }, table:{ id:'ID', caller:'Requester', state:'State', parameter:'Parameter', returnVal:'ReturnVal', date:'Date' } }, nodeReport:{ card:{ level: 'Level', call: 'Method', interval: 'Rate', node: 'Node', viewReport:'ViewReport' } }, nodeReportVal:{ table:{ id:'ID', date:'Date' } }, nodeNotify:{ table:{ id:'ID', sender:'Sender', sendType:'Source', message:'Message', date:'Date' }, senderType:{ user: "User", node: "Node", unknown : 'Unknown' }, state: { not : 'Info', unknown : 'Unknown', normal : 'Success', warn : 'Warn', error : 'Error' }, }, nodeResource:{ table:{ id:'ID', uploader:'Uploader', uploaderType:'Source', name:'Name', size:'Size', downLoadCnt:'DownLoads', state:'State', date:'Date' }, uploaderType:{ user: "User", node: "Node", unknown : 'Unknown' }, state:{ normal:'Valid', invalid:'Invalid' } }, defaultVal:{ unknown : 'Unknown' }, time: { manual: 'manual', ms : 'ms', s : 's', min : 'min', hour : 'hour', day : 'day', once :'t' }, filter:{ invalidTag: 'Invalid tag', existTag: ' Added in<{name}>', start:'Filter activated', stop:'Filter not active', tagName: { ID: 'ID', nodeID: 'Node ID', }, tips:{ select: 'Please select', submit: 'Submit', startTime: 'Start time', endTime: 'End time', timeError:'The start time cannot exceed the end time', clearTags: 'Clear {msg} tags', }, node:{ name:'Node name', state:'State', time:'Update time', }, nodeFunc:{ nodeID:'Node ID', nodeName:'Node name', name:'Node method name', level:'Level', time:'Update time', }, nodeReport:{ nodeID:'Node ID', nodeName:'Node name', name:'Node report name', level:'Level', time:'Update time', }, nodeNotify:{ message:'Message', sender:'Sender', senderType:'Send source', state:'State', time:'Send time', }, nodeResource:{ name:'Resource name', uploader:'Uploader', uploaderType:'Upload source', state:'State', time:'Update time', } }, request:{ error:{ fail: 'Request failure ({msg})', header: 'Error reading information ({msg})', body: 'Error reading data ({msg})', file: 'Error reading file data ({msg})', checkFile: 'File information verification failed ({msg})', marshal: 'Data encoding failed ({msg})', unmarshal: 'Data decoding failed ({msg})', register: 'Register failed ({msg})', loginWithAccount: 'Login failed ({msg})', passwordWithAccount: 'Login failed ({msg})', loginWithToken: 'Login information verification failed ({msg})', levelLow: 'Insufficient permissions ({msg})', request: 'Request error ({msg})', } }, websocket:{ notSupport: 'The current browser does not support websocket protocol, and some functions will not be available', initError:'Websocket initialization error: ', reconnect:'Attempting to reconnect to the server......{msg} time', reconnectSuccess:'Network connection succeeded', disConnect:'The network connection has been disconnected: ', orderError:'Bad websocket instruction: ', deleteNotify:'Your account {msg} has been cancelled by the administrator', levelChanged:'Your account {msg} has changed permissions. Please log in again' }, confirm:{ delete:'This operation will permanently delete relevant data. Do you want to continue?', warn: 'Warn', ok:'Confirm', cancel:'Cancel' }, setting:{ system:'System set', user:'User set', topLink:'Top bar set', systemSet:{ user:'User:', level:'Level:', fixPage:'Fixed paging:', language:'Choose language:', modifyPassword:'Modify password:', modifyPasswordButton:'Modify', modifyPasswordDialog:'Modify Password', loginOut:'Logout:', loginOutButton:'Quit', autoRefresh:'Data sync(s/t):', }, topMenuSet:{ id:'ID', name:'Name', link:'Link', operate:'Operate', deleteSuccess:'Delete success', createSuccess:'Create success', updateSuccess:'Update success' }, userSet:{ id:'ID', userName:'Name', nickName:'Nickname', level:'Level', operate:'Operate', addUser:'Add user', deleteSuccess:'Delete success', updateSuccess:'Update success' } }, file:{ downloadTips:'Click to download the file', uploadTips:'Click upload', exceedTips:'The number of uploaded files exceeds the maximum limit', failTips:'Failed to upload file', forbidDelHistoryFile:'Prohibit deleting history files' }, autoRefresh:{ start:'Auto sync on', stop:'Auto sync off' }, json:{ formatFail:'JSON formatting failed: ' }, level:{ selectTips:'Please select permission level' }, passwordReset:{ originalPassword:'Original password', newPassword:'New password', confirmPassword:'Confirm password', passwordInconsistent:'The two passwords are inconsistent', passwordModifySuccess:'Password changed successfully, please login again', modifyButton: 'Modify' }, sideBar:{ node:'Node', nodeFunc:'Method', nodeReport:'Report', nodeResource:'Resource', nodeNotify:'Notify', nodeTest:'Test', errorKey:'Wrong sidebar menu option: ' }, dialog:{ frame:{ setting:'Set up(ctrl+q)', sync:'Synchronization(ctrl+space)', update:'Refresh(~)', fullScreen:'Full screen(ctrl+enter)', close:'Close(esc)' }, nodeFuncCall:{ form: 'Form', json: 'JSON', emptyParameter:'This method has no parameters set', emptyReturnVal:'The method called this time has no return value', resetButton:'Reset', submitButton:'Submit', jsonCheckFail:'Parameter verification failed' }, nodeReportVal:{ waitResult:'Please wait for the result to return...', setting:'Set up', resultSet:'Result set(p):', sync:'Data sync(s/t):', okButton:'Confirm' } }, home:{ parseConfigFail:'User configuration resolution failed. The default configuration will be used' }, login:{ userName:'User name', password:'Password', login:'Login', logining:'Logging...', autoLogin:'Auto login', register:'Register account', createManager:'Create administrator', loginSuccess:'Login succeeded' }, register:{ nickName:'Nick name', userName:'User name', password:'Password', level:' level', confirmPassword:'Confirm password', registerButton:'Register', registerSuccess:'Register succeeded', passwordInconsistent:'The two passwords are inconsistent' }, empty:{ emptyData:'No data' }, notFound:'Sorry, the page you visited does not exist', notFoundToHome:'Return to login page', notFoundToUp:'Return to previous page' }, }, }) export default i18n
the_stack
import cloneDeep from "lodash/cloneDeep"; import { TAbstractFile, App, normalizePath, TFile, TFolder, Vault, } from "obsidian"; import { get, Unsubscriber } from "svelte/store"; import { pluginSettings, projectMetadata, currentProjectPath, currentDraftPath, } from "../view/stores"; import { buildDraftsLookup } from "./index-file"; import type { DraftsMetadata, IndexFileMetadata } from "./types"; enum DraftsMembership { Draft, Scene, None, } interface ProjectFolderContents { [projectPath: string]: { [draftName: string]: string[]; }; } function membership( abstractFile: TAbstractFile, draftsPath: string ): DraftsMembership { if ( abstractFile instanceof TFolder && abstractFile.parent && abstractFile.parent.path === draftsPath ) { return DraftsMembership.Draft; } else if ( abstractFile instanceof TFile && abstractFile.parent && abstractFile.parent.parent && abstractFile.parent.parent.path === draftsPath ) { return DraftsMembership.Scene; } return DraftsMembership.None; } export class FolderObserver { private vault: Vault; private watchedDraftFolders: { draftsPath: string; projectPath: string; }[]; private unsubscribeSettings: Unsubscriber; constructor(app: App) { this.vault = app.vault; // Load project paths this.unsubscribeSettings = pluginSettings.subscribe((settings) => { this.watchedDraftFolders = Object.keys(settings.projects).map( (projectPath) => ({ draftsPath: normalizePath( `${projectPath}/${settings.projects[projectPath].draftsPath}` ), projectPath, }) ); }); } loadProjects(renameInfo?: { newFile: TAbstractFile; oldPath: string }): void { const toStore: ProjectFolderContents = {}; this.watchedDraftFolders.forEach(({ draftsPath, projectPath }) => { toStore[projectPath] = {}; const folder = this.vault.getAbstractFileByPath(draftsPath); if (!(folder instanceof TFolder)) { return; } // Recurse all watched projects' draft folders. // Because recursion, we know drafts will be encountered before their children. Vault.recurseChildren(folder, (abstractFile) => { const status = membership(abstractFile, draftsPath); if (status === DraftsMembership.Draft) { toStore[projectPath][abstractFile.name] = []; // We only care about folders if they're draft folders } else if ( status === DraftsMembership.Scene && abstractFile instanceof TFile ) { // We only care about files if they're members of a draft toStore[projectPath][abstractFile.parent.name].push( abstractFile.basename ); } }); }); projectMetadata.update((metadata) => { // Sync files on disk with scenes in metadata; // Existing files are sorted by scene order, // new ones are added to the bottom. let newMetadata = cloneDeep(metadata); // javascript is stupid. // eslint-disable-next-line const functionalSplice = (arr: any[], index: number, value: any) => { const v = [...arr]; v.splice(index, 1, value); return v; }; const cleanlyReplaceDraft = ( meta: Record<string, IndexFileMetadata>, _projectPath: string, _draftIndex: number, _draft: DraftsMetadata ) => ({ ...meta, [_projectPath]: { ...meta[_projectPath], drafts: functionalSplice( newMetadata[_projectPath].drafts, _draftIndex, _draft ), }, }); Object.keys(toStore).forEach((projectPath) => { // Handle cases where the metadata cache hasn't caught up to disk yet // and thus no project exists there at all. if (!newMetadata[projectPath]) { return; } // If a draft has been renamed, sub in the renamed draft in metadata if (renameInfo && renameInfo.newFile instanceof TFolder) { const oldFolder = renameInfo.oldPath.split("/").slice(-1)[0]; const newFolder = renameInfo.newFile.name; const draftIndex = newMetadata[projectPath].drafts.findIndex( (d) => d.folder === oldFolder ); if (draftIndex >= 0) { const draft = newMetadata[projectPath].drafts[draftIndex]; newMetadata = cleanlyReplaceDraft( newMetadata, projectPath, draftIndex, { ...draft, folder: newFolder, name: newFolder, } ); } } const metadataLookup = buildDraftsLookup( newMetadata[projectPath].drafts ); Object.keys(toStore[projectPath]).forEach((draftPath) => { const metadataDraft = metadataLookup[draftPath]; const metadataScenes = metadataDraft ? metadataDraft.scenes : []; const fileScenes = toStore[projectPath][draftPath]; const existingScenes: string[] = []; metadataScenes.forEach((s) => { if (fileScenes.contains(s)) { // Retain existing scene existingScenes.push(s); } else if ( renameInfo && renameInfo.newFile instanceof TFile && fileScenes.contains(renameInfo.newFile.basename) ) { // Swap in a renamed file if it matches the full path const f = this.watchedDraftFolders.find( (f) => f.projectPath === projectPath ); if ( f && normalizePath(`${f.draftsPath}/${draftPath}/${s}.md`) === renameInfo.oldPath ) { existingScenes.push(renameInfo.newFile.basename); } } }); const newScenes: string[] = fileScenes.filter( (s) => !existingScenes.contains(s) ); const scenes = [...existingScenes, ...newScenes]; const draftIndex = newMetadata[projectPath].drafts.findIndex( (d) => d.folder === draftPath ); if (draftIndex >= 0) { const draft = newMetadata[projectPath].drafts[draftIndex]; newMetadata = cleanlyReplaceDraft( newMetadata, projectPath, draftIndex, { ...draft, scenes, } ); } else { const draft = { name: draftPath, folder: draftPath, scenes, }; newMetadata = cleanlyReplaceDraft( newMetadata, projectPath, newMetadata[projectPath].drafts.length, draft ); } }); // Delete any orphaned drafts that are in metadata but no longer on disk const fileDrafts = Object.keys(toStore[projectPath]); newMetadata = { ...newMetadata, [projectPath]: { ...newMetadata[projectPath], drafts: newMetadata[projectPath].drafts.filter((d) => fileDrafts.contains(d.folder) ), }, }; }); return newMetadata; }); } destroy(): void { this.unsubscribeSettings(); } fileCreated(abstractFile: TAbstractFile): void { const status = this.anyMembership(abstractFile); if (status === DraftsMembership.None) { return; } // We could do this more intelligently by making minimal edits to the store, // but for now let's just recalculate it. It's not clear to me yet how expensive // recursing children is. this.loadProjects(); } fileDeleted(abstractFile: TAbstractFile): void { // We can't do normal status test here because a deleted file's parent is null. const reload = !!this.watchedDraftFolders.find(({ draftsPath }) => abstractFile.path.startsWith(draftsPath) ); if (!reload) { return; } // We could do this more intelligently by making minimal edits to the store, // but for now let's just recalculate it. It's not clear to me yet how expensive // recursing children is. this.loadProjects(); } fileRenamed(abstractFile: TAbstractFile, oldPath: string): void { const newPath = abstractFile.path; // First handle any project renames, as those happen in settings const folder = this.watchedDraftFolders.find( (f) => f.projectPath === oldPath ); if (folder) { console.log("[Longform] A project has been renamed; updating caches…"); pluginSettings.update((s) => { const projects = s.projects; const project = s.projects[oldPath]; project.path = newPath; projects[newPath] = project; delete s.projects[oldPath]; let selectedProject = s.selectedProject; if (selectedProject === oldPath) { selectedProject = newPath; } const newSettings = { ...s, selectedProject, projects, }; return newSettings; }); currentProjectPath.update((p) => { if (p === oldPath) { return newPath; } return p; }); projectMetadata.update((m) => { const project = m[oldPath]; m[newPath] = project; delete m[oldPath]; return m; }); return; } const status = this.anyMembership(abstractFile, oldPath); if (status === DraftsMembership.None) { return; } // If the current draft was renamed, update that store first. if ( status === DraftsMembership.Draft && oldPath.endsWith(get(currentDraftPath)) ) { currentDraftPath.set(abstractFile.name); } // We could do this more intelligently by making minimal edits to the store, // but for now let's just recalculate it. It's not clear to me yet how expensive // recursing children is. this.loadProjects({ newFile: abstractFile, oldPath }); } private anyMembership( abstractFile: TAbstractFile, oldPath?: string ): DraftsMembership { for (const { draftsPath } of this.watchedDraftFolders) { if (oldPath && oldPath.startsWith(draftsPath)) { return oldPath.endsWith(".md") ? DraftsMembership.Scene : DraftsMembership.Draft; } const status = membership(abstractFile, draftsPath); if (status !== DraftsMembership.None) { return status; } } return DraftsMembership.None; } }
the_stack
import { JSONSerializable } from '../../util/json'; import { Dec, Int } from '../numeric'; import { ValAddress } from '../bech32'; import { ValConsPublicKey } from '../PublicKey'; import { Validator as Validator_pb, Description as Description_pb, Commission as Commission_pb, CommissionRates as CommissionRates_pb, BondStatus, } from '@terra-money/terra.proto/cosmos/staking/v1beta1/staking'; import * as Long from 'long'; import { Any } from '@terra-money/terra.proto/google/protobuf/any'; /** * Stores information fetched from the blockchain about the current status of a validator. * As an end user, you will not have to create an instance of this class, one will be * generated for you to store information about a validator polled from the API functions * in [[StakingAPI]]. */ export class Validator extends JSONSerializable< Validator.Amino, Validator.Data, Validator.Proto > { /** * * @param operator_address validator's operator address * @param consensus_pubkey validator's consensus public key * @param jailed whether the current validator is jailed * @param status unbonded `0`, unbonding `1`, bonded `2` * @param tokens total Luna from all delegations (including self) * @param delegator_shares total shares of all delegators * @param description validator's delegate description * @param unbonding_height if unbonding, height at which this validator began unbonding * @param unbonding_time if unbonding, min time for the validator to complete unbonding * @param commission validator commission * @param min_self_delegation minimum self delegation */ constructor( public operator_address: ValAddress, public consensus_pubkey: ValConsPublicKey, public jailed: boolean, public status: BondStatus, public tokens: Int, public delegator_shares: Dec, public description: Validator.Description, public unbonding_height: number, public unbonding_time: Date, public commission: Validator.Commission, public min_self_delegation: Int ) { super(); } public toAmino(): Validator.Amino { return { operator_address: this.operator_address, consensus_pubkey: this.consensus_pubkey.toAmino(), jailed: this.jailed, status: this.status, tokens: this.tokens.toString(), delegator_shares: this.delegator_shares.toString(), description: this.description, unbonding_height: this.unbonding_height.toFixed(), unbonding_time: this.unbonding_time.toISOString(), commission: this.commission.toAmino(), min_self_delegation: this.min_self_delegation.toString(), }; } public static fromAmino(data: Validator.Amino): Validator { return new Validator( data.operator_address, ValConsPublicKey.fromAmino(data.consensus_pubkey), data.jailed || false, data.status || 0, new Int(data.tokens), new Dec(data.delegator_shares), Validator.Description.fromAmino(data.description), Number.parseInt(data.unbonding_height), new Date(data.unbonding_time), Validator.Commission.fromAmino(data.commission), new Int(data.min_self_delegation) ); } public toData(): Validator.Data { return { operator_address: this.operator_address, consensus_pubkey: this.consensus_pubkey.toData(), jailed: this.jailed, status: this.status, tokens: this.tokens.toString(), delegator_shares: this.delegator_shares.toString(), description: this.description, unbonding_height: this.unbonding_height.toFixed(), unbonding_time: this.unbonding_time.toISOString(), commission: this.commission.toData(), min_self_delegation: this.min_self_delegation.toString(), }; } public static fromData(data: Validator.Data): Validator { return new Validator( data.operator_address, ValConsPublicKey.fromData(data.consensus_pubkey), data.jailed || false, data.status || 0, new Int(data.tokens), new Dec(data.delegator_shares), Validator.Description.fromData(data.description), Number.parseInt(data.unbonding_height), new Date(data.unbonding_time), Validator.Commission.fromData(data.commission), new Int(data.min_self_delegation) ); } public toProto(): Validator.Proto { const { operator_address, consensus_pubkey, jailed, status, tokens, delegator_shares, description, unbonding_height, unbonding_time, commission, min_self_delegation, } = this; return Validator_pb.fromPartial({ commission: commission.toProto(), consensusPubkey: consensus_pubkey.packAny(), delegatorShares: delegator_shares.toString(), description: description.toProto(), jailed, minSelfDelegation: min_self_delegation.toString(), operatorAddress: operator_address, status, tokens: tokens.toString(), unbondingHeight: Long.fromNumber(unbonding_height), unbondingTime: unbonding_time, }); } public static fromProto(data: Validator.Proto): Validator { return new Validator( data.operatorAddress, ValConsPublicKey.unpackAny(data.consensusPubkey as Any), data.jailed, data.status, new Int(data.tokens), new Dec(data.delegatorShares), Validator.Description.fromProto( data.description as Validator.Description.Proto ), data.unbondingHeight.toNumber(), data.unbondingTime as Date, Validator.Commission.fromProto( data.commission as Validator.Commission.Proto ), new Int(data.minSelfDelegation) ); } } export namespace Validator { export const Status = BondStatus; export type Status = BondStatus; export interface Amino { operator_address: ValAddress; consensus_pubkey: ValConsPublicKey.Amino; jailed: boolean; status: BondStatus; tokens: string; delegator_shares: string; description: Description.Amino; unbonding_height: string; unbonding_time: string; commission: Commission.Amino; min_self_delegation: string; } export interface Data { operator_address: ValAddress; consensus_pubkey: ValConsPublicKey.Data; jailed: boolean; status: BondStatus; tokens: string; delegator_shares: string; description: Description.Data; unbonding_height: string; unbonding_time: string; commission: Commission.Data; min_self_delegation: string; } export type Proto = Validator_pb; export class Description extends JSONSerializable< Description.Amino, Description.Data, Description.Proto > { /** * @param moniker Identifying name, e.g. "Hashed" * @param identity time at which commission was last updated * @param website validator's website * @param details long description * @param security_contact validator's contact */ constructor( public moniker: string, public identity: string, public website: string, public details: string, public security_contact: string ) { super(); } public toAmino(): Description.Amino { return { moniker: this.moniker, identity: this.identity, website: this.website, details: this.details, security_contact: this.security_contact, }; } public static fromAmino(data: Description.Amino): Description { return new Description( data.moniker, data.identity || '', data.website || '', data.details || '', data.security_contact || '' ); } public toData(): Description.Data { return { moniker: this.moniker, identity: this.identity, website: this.website, details: this.details, security_contact: this.security_contact, }; } public static fromData(data: Description.Data): Description { return new Description( data.moniker, data.identity || '', data.website || '', data.details || '', data.security_contact || '' ); } public toProto(): Description.Proto { const { moniker, identity, website, details, security_contact } = this; return Description_pb.fromPartial({ details, identity, moniker, securityContact: security_contact, website, }); } public static fromProto(proto: Description.Proto): Description { return new Description( proto.moniker, proto.identity, proto.website, proto.details, proto.securityContact ); } } export namespace Description { export interface Amino { moniker: string; identity: string; website: string; details: string; security_contact: string; } export interface Data { moniker: string; identity: string; website: string; details: string; security_contact: string; } export type Proto = Description_pb; } export class CommissionRates extends JSONSerializable< CommissionRates.Amino, CommissionRates.Data, CommissionRates.Proto > { /** * @param rate current commission rate * @param max_rate max commission rate * @param max_change_rate max percentage commission can change in 24hrs */ constructor( public rate: Dec, public max_rate: Dec, public max_change_rate: Dec ) { super(); } public static fromAmino(data: CommissionRates.Amino): CommissionRates { const { rate, max_rate, max_change_rate } = data; return new CommissionRates( new Dec(rate), new Dec(max_rate), new Dec(max_change_rate) ); } public toAmino(): Validator.CommissionRates.Amino { const { rate, max_rate, max_change_rate } = this; return { rate: rate.toString(), max_rate: max_rate.toString(), max_change_rate: max_change_rate.toString(), }; } public static fromData(data: CommissionRates.Data): CommissionRates { const { rate, max_rate, max_change_rate } = data; return new CommissionRates( new Dec(rate), new Dec(max_rate), new Dec(max_change_rate) ); } public toData(): Validator.CommissionRates.Data { const { rate, max_rate, max_change_rate } = this; return { rate: rate.toString(), max_rate: max_rate.toString(), max_change_rate: max_change_rate.toString(), }; } public static fromProto(proto: CommissionRates.Proto): CommissionRates { return new CommissionRates( new Dec(proto.rate), new Dec(proto.maxRate), new Dec(proto.maxChangeRate) ); } public toProto(): Validator.CommissionRates.Proto { const { rate, max_rate, max_change_rate } = this; return CommissionRates_pb.fromPartial({ maxChangeRate: max_change_rate.toString(), maxRate: max_rate.toString(), rate: rate.toString(), }); } } export namespace CommissionRates { export interface Amino { rate: string; max_rate: string; max_change_rate: string; } export interface Data { rate: string; max_rate: string; max_change_rate: string; } export type Proto = CommissionRates_pb; } export class Commission extends JSONSerializable< Commission.Amino, Commission.Data, Commission.Proto > { /** * @param commission_rates commission rates * @param update_time time at which commission was last updated */ constructor( public commission_rates: CommissionRates, public update_time: Date ) { super(); } public toAmino(): Commission.Amino { return { commission_rates: this.commission_rates.toAmino(), update_time: this.update_time.toISOString(), }; } public static fromAmino(data: Commission.Amino): Commission { return new Commission( CommissionRates.fromAmino(data.commission_rates), new Date(data.update_time) ); } public toData(): Commission.Data { return { commission_rates: this.commission_rates.toData(), update_time: this.update_time.toISOString(), }; } public static fromData(data: Commission.Data): Commission { return new Commission( CommissionRates.fromData(data.commission_rates), new Date(data.update_time) ); } public toProto(): Commission.Proto { const { commission_rates, update_time } = this; return Commission_pb.fromPartial({ commissionRates: commission_rates.toProto(), updateTime: update_time, }); } public static fromProto(proto: Commission.Proto): Commission { return new Commission( CommissionRates.fromProto( proto.commissionRates as CommissionRates.Proto ), proto.updateTime as Date ); } } export namespace Commission { export interface Amino { commission_rates: CommissionRates.Amino; update_time: string; } export interface Data { commission_rates: CommissionRates.Data; update_time: string; } export type Proto = Commission_pb; } }
the_stack
/* Copyright 2017-2020 Dicky Suryadi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { createEventEmitter } from "../libs/utils"; import * as jQueryShim from "../libs/jquery-shim"; import * as signalRNetCore from "@microsoft/signalr"; import { IDotnetifyHub } from "../_typings"; let $ = jQueryShim; const _window = window || global || <any>{}; export class dotnetifyHubFactory { static create(): IDotnetifyHub { let dotnetifyHub: any = { version: "2.0.0", type: null, reconnectDelay: [2, 5, 10], reconnectRetry: null, _startInfo: null, _init: false, // Hub server methods. requestVM: (iVMId, iOptions) => dotnetifyHub.server.request_VM(iVMId, iOptions), updateVM: (iVMId, iValue) => dotnetifyHub.server.update_VM(iVMId, iValue), disposeVM: iVMId => dotnetifyHub.server.dispose_VM(iVMId), // Connection events. responseEvent: createEventEmitter(), reconnectedEvent: createEventEmitter(), connectedEvent: createEventEmitter(), connectionFailedEvent: createEventEmitter(), get isHubStarted(): boolean { return !!this._startInfo; }, // Starts connection with SignalR hub server. startHub(hubOptions, doneHandler, failHandler, forceRestart) { const _doneHandler = () => { if (typeof doneHandler == "function") doneHandler(); this.connectedEvent.emit(); }; const _failHandler = ex => { if (typeof failHandler == "function") failHandler(); this.connectionFailedEvent.emit(); throw ex; }; if (this._startInfo === null || forceRestart) { try { this._startInfo = this.start(hubOptions).done(_doneHandler).fail(_failHandler); } catch (err) { this._startInfo = null; } } else { try { this._startInfo.done(_doneHandler); } catch (err) { this._startInfo = null; return this.startHub(hubOptions, doneHandler, failHandler, forceRestart); } } } }; // Configures connection to SignalR hub server. dotnetifyHub.init = function (iHubPath, iServerUrl, signalR) { if (dotnetifyHub._init) return; dotnetifyHub._init = true; signalR = signalR || _window.signalR || signalRNetCore; // SignalR .NET Core. if (signalR && signalR.HubConnection) { dotnetifyHub.type = "netcore"; Object.defineProperty(dotnetifyHub, "isConnected", { get: function () { return dotnetifyHub._connection && dotnetifyHub._connection.connection.connectionState === signalR.HubConnectionState.Connected; } }); dotnetifyHub = $.extend(dotnetifyHub, { hubPath: iHubPath || "/dotnetify", url: iServerUrl, // Internal variables. Do not modify! _connection: null, _reconnectCount: 0, _startDoneHandler: null, _startFailHandler: null, _disconnectedHandler: function () {}, _stateChangedHandler: function (iNewState) {}, _onDisconnected: function () { dotnetifyHub._changeState(4); dotnetifyHub._disconnectedHandler(); }, _changeState: function (iNewState) { if (iNewState == 1) dotnetifyHub._reconnectCount = 0; let stateText = { 0: "connecting", 1: "connected", 2: "reconnecting", 4: "disconnected", 99: "terminated" }; dotnetifyHub._stateChangedHandler(stateText[iNewState]); }, _startConnection: function (iHubOptions, iTransportArray) { let url = dotnetifyHub.url ? dotnetifyHub.url + dotnetifyHub.hubPath : dotnetifyHub.hubPath; let hubOptions: any = {}; Object.keys(iHubOptions).forEach(function (key) { hubOptions[key] = iHubOptions[key]; }); hubOptions.transport = iTransportArray.shift(); let hubConnectionBuilder = new signalR.HubConnectionBuilder().withUrl(url, hubOptions); if (typeof hubOptions.connectionBuilder == "function") hubConnectionBuilder = hubOptions.connectionBuilder(hubConnectionBuilder); dotnetifyHub._connection = hubConnectionBuilder.build(); dotnetifyHub._connection.on("response_vm", dotnetifyHub.client.response_VM); dotnetifyHub._connection.onclose(dotnetifyHub._onDisconnected); let promise = dotnetifyHub._connection .start() .then(function () { dotnetifyHub._changeState(1); }) .catch(function () { // If failed to start, fallback to the next transport. if (iTransportArray.length > 0) dotnetifyHub._startConnection(iHubOptions, iTransportArray); else dotnetifyHub._onDisconnected(); }); if (typeof dotnetifyHub._startDoneHandler === "function") promise.then(dotnetifyHub._startDoneHandler).catch(dotnetifyHub._startFailHandler || function () {}); return promise; }, start: function (iHubOptions) { dotnetifyHub._startDoneHandler = null; dotnetifyHub._startFailHandler = null; // Map the transport option. let transport = [0]; let transportOptions = { webSockets: 0, serverSentEvents: 1, longPolling: 2 }; if (iHubOptions && Array.isArray(iHubOptions.transport)) transport = iHubOptions.transport.map(function (arg) { return transportOptions[arg]; }); let promise = dotnetifyHub._startConnection(iHubOptions, transport); return { done: function (iHandler) { dotnetifyHub._startDoneHandler = iHandler; promise.then(iHandler).catch(function (error) { throw error; }); return this; }, fail: function (iHandler) { dotnetifyHub._startFailHandler = iHandler; promise.catch(iHandler); return this; } }; }, disconnected: function (iHandler) { if (typeof iHandler === "function") dotnetifyHub._disconnectedHandler = iHandler; }, stateChanged: function (iHandler) { if (typeof iHandler === "function") dotnetifyHub._stateChangedHandler = iHandler; }, reconnect: function (iStartHubFunc) { if (typeof iStartHubFunc === "function") { // Only attempt reconnect if the specified retry hasn't been exceeded. if (!dotnetifyHub.reconnectRetry || dotnetifyHub._reconnectCount < dotnetifyHub.reconnectRetry) { // Determine reconnect delay from the specified configuration array. let delay = dotnetifyHub._reconnectCount < dotnetifyHub.reconnectDelay.length ? dotnetifyHub.reconnectDelay[dotnetifyHub._reconnectCount] : dotnetifyHub.reconnectDelay[dotnetifyHub.reconnectDelay.length - 1]; dotnetifyHub._reconnectCount++; setTimeout(function () { dotnetifyHub._changeState(2); iStartHubFunc(); }, delay * 1000); } else dotnetifyHub._changeState(99); } }, client: {}, server: { dispose_VM: function (iVMId) { dotnetifyHub._connection.invoke("Dispose_VM", iVMId); }, update_VM: function (iVMId, iValue) { dotnetifyHub._connection.invoke("Update_VM", iVMId, iValue); }, request_VM: function (iVMId, iArgs) { dotnetifyHub._connection.invoke("Request_VM", iVMId, iArgs); } } }); } else { // SignalR .NET FX. dotnetifyHub.type = "netfx"; if (_window.jQuery) $ = _window.jQuery; // SignalR hub auto-generated from /signalr/hubs. /// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" /> /// <reference path="jquery.signalR.js" /> (function ($) { /// <param name="$" type="jQuery" /> "use strict"; if (typeof $.signalR !== "function") { throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js."); } var signalR = $.signalR; function makeProxyCallback(hub, callback) { return function () { // Call the client hub method callback.apply(hub, $.makeArray(arguments)); }; } function registerHubProxies(instance, shouldSubscribe) { var key, hub, memberKey, memberValue, subscriptionMethod; for (key in instance) { if (instance.hasOwnProperty(key)) { hub = instance[key]; if (!hub.hubName) { // Not a client hub continue; } if (shouldSubscribe) { // We want to subscribe to the hub events subscriptionMethod = hub.on; } else { // We want to unsubscribe from the hub events subscriptionMethod = hub.off; } // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe for (memberKey in hub.client) { if (hub.client.hasOwnProperty(memberKey)) { memberValue = hub.client[memberKey]; if (!$.isFunction(memberValue)) { // Not a client hub function continue; } subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue)); } } } } } $.hubConnection.prototype.createHubProxies = function () { var proxies = {}; this.starting(function () { // Register the hub proxies as subscribed // (instance, shouldSubscribe) registerHubProxies(proxies, true); this._registerSubscribedHubs(); }).disconnected(function () { // Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs. // (instance, shouldSubscribe) registerHubProxies(proxies, false); }); proxies["dotNetifyHub"] = this.createHubProxy("dotNetifyHub"); proxies["dotNetifyHub"].client = {}; proxies["dotNetifyHub"].server = { dispose_VM: function (vmId) { return proxies["dotNetifyHub"].invoke.apply(proxies["dotNetifyHub"], $.merge(["Dispose_VM"], $.makeArray(arguments))); }, request_VM: function (vmId, vmArg) { return proxies["dotNetifyHub"].invoke.apply(proxies["dotNetifyHub"], $.merge(["Request_VM"], $.makeArray(arguments))); }, update_VM: function (vmId, vmData) { return proxies["dotNetifyHub"].invoke.apply(proxies["dotNetifyHub"], $.merge(["Update_VM"], $.makeArray(arguments))); } }; return proxies; }; signalR.hub = $.hubConnection(dotnetifyHub.hubPath, { useDefaultPath: false }); $.extend(signalR, signalR.hub.createHubProxies()); })($); Object.defineProperty(dotnetifyHub, "state", { get: function () { return $.connection.hub.state; }, set: function (val) { $.connection.hub.state = val; } }); Object.defineProperty(dotnetifyHub, "client", { get: function () { return $.connection.dotNetifyHub.client; } }); Object.defineProperty(dotnetifyHub, "server", { get: function () { return $.connection.dotNetifyHub.server; } }); Object.defineProperty(dotnetifyHub, "isConnected", { get: function () { return $.connection.hub.state == $.signalR.connectionState.connected; } }); dotnetifyHub = $.extend(dotnetifyHub, { hubPath: iHubPath || "/signalr", url: iServerUrl, _reconnectCount: 0, _stateChangedHandler: function (iNewState) {}, start: function (iHubOptions) { if (dotnetifyHub.url) $.connection.hub.url = dotnetifyHub.url; let deferred; if (iHubOptions) deferred = $.connection.hub.start(iHubOptions); else deferred = $.connection.hub.start(); deferred.fail(function (error) { if (error.source && error.source.message === "Error parsing negotiate response.") console.warn("This client may be attempting to connect to an incompatible SignalR .NET Core server."); }); return deferred; }, disconnected: function (iHandler) { return $.connection.hub.disconnected(iHandler); }, stateChanged: function (iHandler) { dotnetifyHub._stateChangedHandler = iHandler; return $.connection.hub.stateChanged(function (state) { if (state == 1) dotnetifyHub._reconnectCount = 0; let stateText = { 0: "connecting", 1: "connected", 2: "reconnecting", 4: "disconnected" }; iHandler(stateText[state.newState]); }); }, reconnect: function (iStartHubFunc) { if (typeof iStartHubFunc === "function") { // Only attempt reconnect if the specified retry hasn't been exceeded. if (!dotnetifyHub.reconnectRetry || dotnetifyHub._reconnectCount < dotnetifyHub.reconnectRetry) { // Determine reconnect delay from the specified configuration array. let delay = dotnetifyHub._reconnectCount < dotnetifyHub.reconnectDelay.length ? dotnetifyHub.reconnectDelay[dotnetifyHub._reconnectCount] : dotnetifyHub.reconnectDelay[dotnetifyHub.reconnectDelay.length - 1]; dotnetifyHub._reconnectCount++; setTimeout(function () { dotnetifyHub._stateChangedHandler("reconnecting"); iStartHubFunc(); }, delay * 1000); } else dotnetifyHub._stateChangedHandler("terminated"); } } }); } // Setup SignalR server method handler. dotnetifyHub.client.response_VM = function (iVMId, iVMData) { // SignalR .NET Core is sending an array of arguments. if (Array.isArray(iVMId)) { iVMData = iVMId[1]; iVMId = iVMId[0]; } let handled = dotnetifyHub.responseEvent.emit(iVMId, iVMData); // If we get to this point, that means the server holds a view model instance // whose view no longer existed. So, tell the server to dispose the view model. if (!handled) dotnetifyHub.server.dispose_VM(iVMId); }; // On disconnected, keep attempting to start the connection. dotnetifyHub.disconnected(function () { dotnetifyHub._startInfo = null; dotnetifyHub.reconnect(function () { dotnetifyHub.reconnectedEvent.emit(); }); }); }; return dotnetifyHub; } } export default dotnetifyHubFactory.create();
the_stack
import { Component, ContentChild, ContentChildren, Input, Optional, QueryList } from '@angular/core'; import { AbstractControl, ControlContainer, FormArray, FormGroupDirective, NgForm } from '@angular/forms'; import { DisplayMode, ValdemortConfig } from './valdemort-config.service'; import { DefaultValidationErrors } from './default-validation-errors.service'; import { ValidationErrorDirective } from './validation-error.directive'; import { ValidationFallbackDirective } from './validation-fallback.directive'; interface FallbackError { type: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any value: any; } interface ErrorsToDisplay { // The validation error directives to display errors: Array<ValidationErrorDirective>; // The fallback directive to use to display the fallback errors fallback: ValidationFallbackDirective | undefined; // the fallback errors to display (empty if there is no fallback directive) fallbackErrors: Array<FallbackError>; } /** * Component allowing to display validation error messages associated to a given form control, form group or form array. * The control is provided using the `control` input of the component. If it's used inside an enclosing form group or * form array, it can instead be provided using the `controlName` input of the component. * * Example usage where the control itself is being passed as input: * ``` * <val-errors [control]="form.get('birthDate')"> * <ng-template valError="required">The birth date is mandatory</ng-template> * <ng-template valError="max" let-error="error">The max value for the birth date is {{ error.max | number }}</ng-template> * </val-errors> * ``` * * Example usage where the control name is being passed as input: * ``` * <val-errors controlName="birthDate"> * <ng-template valError="required">The birth date is mandatory</ng-template> * <ng-template valError="max" let-error="error">The max value for the birth date is {{ error.max | number }}</ng-template> * </val-errors> * ``` * * This component, if the control is invalid, displays its validation errors using the provided templates. * The templates, as shown in the above example, have access to the validation error itself. * * The label of the control can also be provided as input, and then used in the templates: * ``` * <val-errors controlName="birthDate" label="the birth date"> * <ng-template valError="required" let-label>{{ label }} is mandatory</ng-template> * <ng-template valError="max" let-error="error" let-label>The max value for {{ label }} is {{ error.max | number }}</ng-template> * </val-errors> * ``` * * The component‘s behavior is configured globally by the Config service (see its documentation for more details). It can * - display the first error, or all the errors * - add CSS classes to its host `<val-errors>` element * - add CSS classes to each error message element being displayed * - choose when to display the errors (dirty, touched, touched and submitted, etc.) * * Global, default templates can be defined (and used by this component) using the default validation errors directive * (see its documentation for details). So, if the default error messages are defined and sufficient for a given control, all you * need is * * ``` * <val-errors controlName="birthDate"></val-errors> * ``` * * or, if the default templates expect a label: * * ``` * <val-errors controlName="birthDate" label="the birth date"></val-errors> * ``` * * If, however, you want to override one or several error messages by custom ones, you can do so by simply defining them inside the * component: * * ``` * <val-errors controlName="birthDate" label="the birth date"> * <ng-template valError="max">You're too young, sorry</ng-template> * </val-errors> * ``` * * A fallback template can also be provided. This fallback template is used for all the errors that exist on the form control * but are not handled by any of the specific error templates: * ``` * <val-errors controlName="birthDate" label="the birth date"> * <ng-template valError="max">You're too young, sorry</ng-template> * <ng-template valFallback let-label let-type="type" let-error="error">{{ label }} has an unhandled error of type {{ type }}: {{ error | json }}</ng-template> * </val-errors> * ``` * Note that, the fallback template can also be defined in the default validation errors directive (see its documentation for details). * If a fallback template is defined inside `val-errors`, it overrides the default fallback. * * If an error is present on the control, but doesn't have any template, default template or fallback template defined for its type, * then it's not displayed. If the control is valid, or if none of the errors of the component has a matching template or default template, * then this component itself is hidden. */ @Component({ selector: 'val-errors', templateUrl: './validation-errors.component.html', host: { '[class]': 'errorsClasses', '[style.display]': `shouldDisplayErrors ? '' : 'none'` } }) export class ValidationErrorsComponent { /** * The FormControl, FormGroup or FormArray containing the validation errors. * If set, the controlName input is ignored */ @Input() control: AbstractControl | null = null; /** * The name (or the index, in case it's contained in a FormArray) of the FormControl, FormGroup or FormArray containing the validation * errors. * Ignored if the control input is set, and only usable if the control to validate is part of a control container */ @Input() controlName: string | number | null = null; /** * The label of the field, exposed to templates so they can use it in the error message. */ @Input() label: string | null = null; /** * The list of validation error directives (i.e. <ng-template valError="...">) contained inside the component element. */ @ContentChildren(ValidationErrorDirective) errorDirectives!: QueryList<ValidationErrorDirective>; /** * The validation fallback directive (i.e. <ng-template valFallback>) contained inside the component element. */ @ContentChild(ValidationFallbackDirective) fallbackDirective: ValidationFallbackDirective | undefined; /** * @param config the Config service instance, defining the behavior of this component * @param defaultValidationErrors the service holding the default error templates, optionally * defined by using the default validation errors directive * @param controlContainer one of the 4 form group or form array directives that can "wrap" the control. * It's injected so that we can know if it exists and, if it does, if its form directive has been submitted or not: * the config service shouldDisplayErrors function can choose (and does by default) to use that information. */ constructor( private config: ValdemortConfig, private defaultValidationErrors: DefaultValidationErrors, @Optional() private controlContainer: ControlContainer ) {} get shouldDisplayErrors(): boolean { const ctrl = this.actualControl; if (!ctrl || !ctrl.invalid || !this.hasDisplayableError(ctrl)) { return false; } const form = this.controlContainer && (this.controlContainer.formDirective as NgForm | FormGroupDirective); return this.config.shouldDisplayErrors(ctrl, form); } get errorsClasses(): string { return this.config.errorsClasses || ''; } get errorClasses(): string { return this.config.errorClasses || ''; } get errorsToDisplay(): ErrorsToDisplay { const mergedDirectives: Array<ValidationErrorDirective> = []; const fallbackErrors: Array<FallbackError> = []; const alreadyMetTypes = new Set<string>(); const shouldContinue = () => this.config.displayMode === DisplayMode.ALL || (mergedDirectives.length === 0 && fallbackErrors.length === 0); const ctrl = this.actualControl!; for (let i = 0; i < this.defaultValidationErrors.directives.length && shouldContinue(); i++) { const defaultDirective = this.defaultValidationErrors.directives[i]; if (ctrl.hasError(defaultDirective.type)) { const customDirectiveOfSameType = this.errorDirectives.find(dir => dir.type === defaultDirective.type); mergedDirectives.push(customDirectiveOfSameType || defaultDirective); } alreadyMetTypes.add(defaultDirective.type); } if (shouldContinue()) { const customDirectives = this.errorDirectives.toArray(); for (let i = 0; i < customDirectives.length && shouldContinue(); i++) { const customDirective = customDirectives[i]; if (ctrl.hasError(customDirective.type) && !alreadyMetTypes.has(customDirective.type)) { mergedDirectives.push(customDirective); } alreadyMetTypes.add(customDirective.type); } } if (shouldContinue() && (this.fallbackDirective || this.defaultValidationErrors.fallback)) { const allErrors = Object.entries(ctrl.errors ?? []); for (let i = 0; i < allErrors.length && shouldContinue(); i++) { const [type, value] = allErrors[i]; if (!alreadyMetTypes.has(type)) { fallbackErrors.push({ type, value }); } } } return { errors: mergedDirectives, fallback: this.fallbackDirective ?? this.defaultValidationErrors.fallback, fallbackErrors }; } get actualControl(): AbstractControl | null { if (this.control) { return this.control; } else if ((this.controlName || (this.controlName as number) === 0) && (this.controlContainer.control as FormArray)?.controls) { const control = (this.controlContainer.control as FormArray).controls[this.controlName as number]; if (this.config.shouldThrowOnMissingControl()) { // if the control is null, then there are two cases: // - we are in a template driven form, and the controls might not be initialized yet // - there was an error in the control name. If so, let's throw an error to help developers // to avoid false positive in template driven forms, we check if the controls are initialized // by checking if the `controls` object or array has any element if (!control && Object.keys((this.controlContainer.control as FormArray)?.controls).length > 0) { throw new Error(`ngx-valdemort: no control found for controlName: '${this.controlName}'.`); } } return control; } return null; } private hasDisplayableError(ctrl: AbstractControl) { return ( ctrl.errors && (this.fallbackDirective || this.defaultValidationErrors.fallback || Object.keys(ctrl.errors).some( type => this.defaultValidationErrors.directives.some(dir => dir.type === type) || this.errorDirectives.some(dir => dir.type === type) )) ); } }
the_stack
import {Component, NgZone, AfterViewChecked, EventEmitter, Output, ViewChild} from '@angular/core'; import {ModalComponent} from 'ng2-bs3-modal/ng2-bs3-modal'; import * as $ from "jquery" import {downgradeComponent} from '@angular/upgrade/static'; import {TeleporterService} from '../../core/services'; import {NotificationService} from "../../core/services/notification.service"; declare var angular:any @Component({ selector: 'teleporter', templateUrl: "./teleporter.component.html", styleUrls: [] }) class TeleporterComponent implements AfterViewChecked { private popoversEnabled:boolean; private protocols; private strategies; private nameResolvers; private logLevels; private dbConnection; private jurlPattern; private jurlSplit; private defaultConfig; private config; private step; private driversInfo; private driverNames; private job; private jobRunning; private hints; // dual list box private keepSorted; private key; private fieldToDisplay; private sourceDBTables = []; private includedTables = []; // JSON configuration for modelling private modellingConfig; private selectedElement; private configFetched:boolean; // Event Emitter @Output() onMigrationConfigFetched = new EventEmitter(); @ViewChild('detailPanel') detailPanel; @ViewChild('graphPanel') graphPanel; // Modals' variables @ViewChild('acceptOracleLicenseModal') acceptOracleLicenseModal: ModalComponent; private licensePermission = false; constructor(private teleporterService: TeleporterService, private notification: NotificationService, private zone: NgZone) { this.init(); } init() { this.popoversEnabled = false; this.protocols = ["plocal", "memory"]; this.strategies = ["naive", "naive-aggregate"]; this.nameResolvers = ["original", "java"]; this.logLevels = ["NO","DEBUG","INFO","WARNING","ERROR"]; this.dbConnection = { "host": "", "port": "", "dbName": "", "sid": "" } this.jurlSplit = []; this.defaultConfig = { "driver": "PostgreSQL", "jurl": "", "username": "", "password": "", "protocol": "plocal", "outDBName": "", "outDbUrl": "", "strategy": "naive", "mapper": "basicDBMapper", "xmlPath": "", "nameResolver": "original", "level": "2", "includedTables": [] } this.config = angular.copy(this.defaultConfig); this.step = '1'; // fetching driver name and jurl pattern this.drivers().then((data) => { this.driversInfo = data; this.driverNames = Object.keys(this.driversInfo); this.jurlPattern = this.driversInfo[this.config.driver].format[0]; this.updateJurlSplit(); this.updateJurl(); }); // initialising job info this.initJobInfo(); this.jobRunning = false; this.hints = { driver: "Driver name of the DBMS from which you want to execute the migration.", host: "Address of the host where the DBMS is available.", port: "The port where your DBMS is listening for new connections.", dbName: "The source database name.", sid: "SID is a unique name for an Oracle database instance.", username: "The username to access the source database.", password: "The password to access the source database.", protocol: "The protocol to use during the migration in order to connect to OrientDB:<br>" + "<li><b>plocal</b>: the dabase will run locally in the same JVM of your application.</li>" + "<li><b>remote</b>: the database will be accessed via TCP/IP connection.</li>", outDBName: "The name for the destination OrientDB graph database.", strategy: "Strategy adopted during the importing phase.<br> " + "<li><b>naive</b>: performs a 'naive' import of the data source. The data source schema is translated semi-directly in a correspondent and coherent graph model.</li> " + "<li><b>naive-aggregate</b>: performs a 'naive' import of the data source. The data source schema is translated semi-directly in a correspondent and coherent graph model " + "using an aggregation policy on the junction tables of dimension equals to 2.</li><br>" + "<a href='http://orientdb.com/docs/last/Teleporter-Execution-Strategies.html'>More info</a>", nameResolver: "Name of the resolver which transforms the names of all the elements of the source database according to a specific convention.<br>" + "<li><b>original</b>: maintains the original name convention.</li>" + "<li><b>java</b>: transforms all the elements' names according to the Java convention.</li>", tableList: "Select the source database tables you want to import in OrientDB.", XMLPath: "Executes the migration taking advantage of OrientDB's polymorphism according to the configuration in the specified XML file.<br><br>" + "<a href='http://orientdb.com/docs/last/Teleporter-Inheritance.html'>More info</a>", logLevel: "Level of verbosity printed to the output during the execution." } // dual list box this.keepSorted = true; this.key = "id"; this.fieldToDisplay = "tableName"; // this.buildConfigJSON(); this.selectedElement = undefined; this.configFetched = false; } ngAfterViewChecked() { if(!this.popoversEnabled) { this.enablePopovers(); this.popoversEnabled = true; } } enablePopovers() { (<any>$('[data-toggle="popover"]')).popover({ title: '', placement: 'right', trigger: 'focus' }); } initJobInfo() { this.job = {cfg: undefined, status: undefined, log: ""}; } getStep() { return this.step; } switchConfigStep(step) { if(step === '3') { // fetching tables' names this.getTablesNames().then((data) => { this.sourceDBTables = data["tables"]; }) } else if(step === '4') { // fetching migration config this.getMigrationConfig(); } this.step = step; // popovers need being enabled this.popoversEnabled = false; } changeSelectedElement(e) { this.selectedElement = e; this.detailPanel.changeSelectedElement(e); } drivers() { return this.teleporterService.drivers(); } getTablesNames() { return this.teleporterService.getTablesNames(this.config); } getMigrationConfig() { this.teleporterService.getMigrationConfig(this.config).then((data) => { this.modellingConfig = data; this.onMigrationConfigFetched.emit(); }).catch((error) => { this.notification.push({content: error.json(), error: true, autoHide: true}); }); } updateIncludedTables(includedTables) { var includedTablesRaw = []; for(var i=0; i<includedTables.length; i++) { includedTablesRaw[i] = includedTables[i].tableName; } this.config.includedTables = includedTablesRaw; } changeJurlAccordingToDriver() { this.jurlPattern = this.driversInfo[this.config.driver].format[0]; this.updateJurlSplit(); this.updateJurl(); } updateJurlSplit() { var regExp = new RegExp(/(<HOST>|<PORT>|<DB>|<SID>)/); this.jurlSplit = this.jurlPattern.split(regExp, 6); } updateJurl() { this.jurlSplit[1] = this.dbConnection.host; this.jurlSplit[3] = this.dbConnection.port; if(this.config.driver == "Oracle") { this.jurlSplit[5] = this.dbConnection.sid; } else { this.jurlSplit[5] = this.dbConnection.dbName; } this.config.jurl = this.jurlSplit.join(""); } testConnection() { this.teleporterService.testConnection(this.config).then(() => { this.notification.push({content: "Connection is alive", autoHide: true}); }).catch((error) => { this.notification.push({content: error.json(), error: true, autoHide: true}); }); } saveConfiguration() { var migrationConfigString; // fetching modelling config if it's not undefined and preparation if(this.modellingConfig) { // copying the configuration object var configCopy = JSON.parse(JSON.stringify(this.modellingConfig)); this.prepareModellingConfig(configCopy); migrationConfigString = JSON.stringify(configCopy); } var params = { migrationConfig: migrationConfigString, outDBName: this.config.outDBName }; this.teleporterService.saveConfiguration(params).then(() => { this.notification.push({content: "Configuration correctly saved.", autoHide: true}); }).catch((error) => { this.notification.push({content: error.json(), error: true, autoHide: true}); }); } launch() { if(this.config.driver === 'Oracle' && this.licensePermission === false) { this.prepareAndOpenAcceptOracleLicenseModal(); } else { // fetching modelling config if it's not undefined and preparation if (this.modellingConfig) { // copying the configuration object var configCopy = JSON.parse(JSON.stringify(this.modellingConfig)); this.prepareModellingConfig(configCopy); this.config.migrationConfig = JSON.stringify(configCopy); } this.config.outDbUrl = this.config.protocol + ":" + this.config.outDBName; // transforming includedTables if set if (this.includedTables.length > 0) { for (var i = 0; i < this.includedTables.length; i++) { this.config.includedTables.push(this.includedTables[i].tableName); } } // invalidate the old migration config this.modellingConfig = undefined; this.selectedElement = undefined; if (this.graphPanel !== undefined) { this.graphPanel.invalidateMigrationConfig(); } this.initJobInfo(); this.step = "running"; this.jobRunning = true; this.teleporterService.launch(this.config).then(() => { this.status(); }).catch(function (error) { alert("Error during migration!") }); } } prepareModellingConfig(configCopy) { // deleting source and target for each edge definition for (var edge of configCopy.edges) { delete edge.source; delete edge.target; } this.aggregateEdgesByNameInConfig(configCopy); } aggregateEdgesByNameInConfig(configCopy) { // aggregating edges with the same name (that is all the edges representing the same edge class) for (var i = 0; i < configCopy.edges.length; i++) { var elementToAggregate = configCopy.edges[i]; var elementToAggregateName = this.getEdgeClassName(elementToAggregate); for (var j = i + 1; j < configCopy.edges.length; j++) { var currEdge = configCopy.edges[j]; var currEdgeName = this.getEdgeClassName(currEdge); if (elementToAggregateName === currEdgeName) { // aggregate mapping information elementToAggregate[elementToAggregateName].mapping.push(currEdge[currEdgeName].mapping[0]); // delete the duplicate edges configCopy.edges.splice(j, 1); // decreasing j as the array shifted after the delete j--; } } } } getEdgeClassName(link) { var edgeClassName = undefined; var keys = Object.keys(link); for(var key of keys) { if(key !== 'source' && key !== 'target') { edgeClassName = key; break; } } return edgeClassName; } status() { if(this.jobRunning) { this.teleporterService.status().then((data) => { if(data.jobs.length > 0) { var currentJobInfo = data.jobs[0]; this.job.cfg = currentJobInfo.cfg; this.job.status = currentJobInfo.status; this.job.log += currentJobInfo.log; this.scrollLogAreaDown(); } else { if(this.job) { this.job.finished = true; this.jobRunning = false; this.scrollLogAreaDown(); } } // start status again after 3 secs setTimeout(() => { this.zone.run(() => { this.status(); }) }, 3000); }); } } scrollLogAreaDown() { var logArea = $("#logArea"); logArea.scrollTop(9999999); } /** * * @param $event */ renameElementInGraph(event) { this.graphPanel.renameElementInGraph(event); } /** * * @param $event */ removeElementInGraph(event) { this.graphPanel.removeElementInGraph(event); } /** * ---------------------------------------------------------- * * Modals' methods * * ---------------------------------------------------------- */ /** * It prepares and opens an "accept oracle license" modal. */ prepareAndOpenAcceptOracleLicenseModal() { // opening the modal this.acceptOracleLicenseModal.open(); } /** * It's called when an "accept oracle license" modal closing or dismissing occurs. */ dismissOrCloseAcceptOracleLicenseModal(action) { if(action === 'accept') { // setting acceptOracleLicense true this.licensePermission = true; this.launch(); // closing the modal this.acceptOracleLicenseModal.close(); } else if(action === 'reject') { // setting permission to false this.licensePermission = false; // closing the modal this.acceptOracleLicenseModal.close(); } else if(action === 'dismiss') { // setting permission to false this.licensePermission = false; // dismissing the modal this.acceptOracleLicenseModal.dismiss(); } } } angular.module('teleporter.components', []).directive( `teleporter`, downgradeComponent({component: TeleporterComponent})); export {TeleporterComponent};
the_stack
declare namespace jsb { type AccelerationXYZ = number; type AccelerationIncludingGravityXYZ = number; type RotationRateAlpha = number; type RotationRateBeta = number; type RotationRateGamma = number; type DeviceMotionValue = [AccelerationXYZ, AccelerationXYZ, AccelerationXYZ, AccelerationIncludingGravityXYZ, AccelerationIncludingGravityXYZ, AccelerationIncludingGravityXYZ, RotationRateAlpha, RotationRateBeta, RotationRateGamma]; export namespace device { export function getBatteryLevel(): number; export function getDevicePixelRatio(): number; export function getDeviceOrientation(): number; export function getNetworkType(): number; // TODO: enum type export function getSafeAreaEdge(): NativeSafeAreaEdge; export function setAccelerometerEnabled(isEnabled: boolean); export function setAccelerometerInterval(intervalInSeconds: number); export function getDeviceMotionValue(): DeviceMotionValue; } export interface NativeSafeAreaEdge { /** * top */ x: number; /** * left */ y: number; /** * bottom */ z: number; /** * right */ w: number; } export interface MouseEvent { x: number, y: number, button: number, } type MouseEventCallback = (mouseEvent: MouseEvent) => void; export interface MouseWheelEvent extends MouseEvent { wheelDeltaX: number, wheelDeltaY: number, } type MouseWheelEventCallback = (mouseEvent: MouseWheelEvent) => void; export let onMouseDown: MouseEventCallback | undefined; export let onMouseMove: MouseEventCallback | undefined; export let onMouseUp: MouseEventCallback | undefined; export let onMouseWheel: MouseWheelEventCallback | undefined; type TouchEventCallback = (touchList: TouchList) => void; export let onTouchStart: TouchEventCallback | undefined; export let onTouchMove: TouchEventCallback | undefined; export let onTouchEnd: TouchEventCallback | undefined; export let onTouchCancel: TouchEventCallback | undefined; export interface KeyboardEvent { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; repeat: boolean; keyCode: number; } type KeyboardEventCallback = (keyboardEvent: KeyboardEvent) => void; export let onKeyDown: KeyboardEventCallback | undefined; export let onKeyUp: KeyboardEventCallback| undefined; export let onResize: (size: {width: number, height: number}) => void | undefined; export let onOrientationChanged: (event: {orientation: number}) => void | undefined; // TODO: enum orientation type export let onResume: () => void | undefined; export let onPause: () => void | undefined; export let onClose: () => void | undefined; export function openURL(url: string): void; export function garbageCollect(): void; export namespace AudioEngine { export function preload (url: string, cb: (isSuccess: boolean) => void); export function play2d (url: string, loop: boolean, volume: number): number; export function pause (id: number); export function pauseAll (); export function resume (id: number); export function resumeAll (); export function stop (id: number); export function stopAll (); export function getPlayingAudioCount (): number; export function getMaxAudioInstance (): number; export function getState (id: number): any; export function getDuration (id: number): number; export function getVolume (id: number): number; export function isLoop (id: number): boolean; export function getCurrentTime (id: number): number; export function setVolume (id: number, val: number); export function setLoop (id: number, val: boolean); export function setCurrentTime (id: number, val: number); export function uncache (url: string); export function uncacheAll (); export function setErrorCallback (id: number, cb: (err: any) => void); export function setFinishCallback (id: number, cb: () => void); } export namespace reflection{ /** * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html * call OBJC/Java static methods * * @param className * @param methodName * @param methodSignature * @param parameters */ export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; } export namespace bridge{ /** * send to native with at least one argument. */ export function sendToNative(arg0: string, arg1?: string): void; /** * save your own callback controller with a js function, * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} * @param args : received from native */ export function onNative(arg0: string, arg1?: string|null): void; } /** * 下载任务对象 */ export type DownloaderTask = { requestURL: string, storagePath: string, identifier: string }; /** * Http file downloader for jsb! */ export class Downloader { /** * create a download task * @param requestURL * @param storagePath * @param identifier */ createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; setOnTaskProgress (onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void): void; setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; } export interface ManifestAsset { md5: string; path: string; compressed: boolean; size: number; downloadState: number; } export class Manifest { constructor (manifestUrl: string); constructor (content: string, manifestRoot: string); parseFile (manifestUrl: string): void; parseJSONString (content: string, manifestRoot: string): void; getManifestRoot (): string; getManifestFileUrl (): string; getVersionFileUrl (): string; getSearchPaths (): [string]; getVersion (): string; getPackageUrl (): boolean; setUpdating (isUpdating: boolean): void; isUpdating (): boolean; isVersionLoaded (): boolean; isLoaded (): boolean; } export class EventAssetsManager { // EventCode static ERROR_NO_LOCAL_MANIFEST: number; static ERROR_DOWNLOAD_MANIFEST: number; static ERROR_PARSE_MANIFEST: number; static NEW_VERSION_FOUND: number; static ALREADY_UP_TO_DATE: number; static UPDATE_PROGRESSION: number; static ASSET_UPDATED: number; static ERROR_UPDATING: number; static UPDATE_FINISHED: number; static UPDATE_FAILED: number; static ERROR_DECOMPRESS: number; constructor (eventName: string, manager: AssetsManager, eventCode: number, assetId?: string, message?: string, curleCode?: number, curlmCode?: number); getAssetsManagerEx (): AssetsManager; isResuming (): boolean; getDownloadedFiles (): number; getDownloadedBytes (): number; getTotalFiles (): number; getTotalBytes (): number; getPercent (): number; getPercentByFile (): number; getEventCode (): number; getMessage (): string; getAssetId (): string; getCURLECode (): number; getCURLMCode (): number; } export namespace AssetsManager { export enum State { UNINITED, UNCHECKED, PREDOWNLOAD_VERSION, DOWNLOADING_VERSION, VERSION_LOADED, PREDOWNLOAD_MANIFEST, DOWNLOADING_MANIFEST, MANIFEST_LOADED, NEED_UPDATE, READY_TO_UPDATE, UPDATING, UNZIPPING, UP_TO_DATE, FAIL_TO_UPDATE, } } export class AssetsManager { constructor (manifestUrl: string, storagePath: string, versionCompareHandle?: (versionA: string, versionB: string) => number); static create (manifestUrl: string, storagePath: string): AssetsManager; getState (): AssetsManager.State; getStoragePath (): string getMaxConcurrentTask (): number; // setMaxConcurrentTask (max: number): void; // actually not supported checkUpdate (): void; prepareUpdate (): void; update (): void; isResuming (): boolean; getDownloadedFiles (): number; getDownloadedBytes (): number; getTotalFiles (): number; getTotalBytes (): number; downloadFailedAssets (): void; getLocalManifest (): Manifest; loadLocalManifest (manifestUrl: string): boolean; loadLocalManifest (localManifest: Manifest, storagePath: string): boolean; getRemoteManifest (): Manifest; loadRemoteManifest (remoteManifest: Manifest): boolean; /** * Setup your own version compare handler, versionA and B is versions in string. * if the return value greater than 0, versionA is greater than B, * if the return value equals 0, versionA equals to B, * if the return value smaller than 0, versionA is smaller than B. */ setVersionCompareHandle (versionCompareHandle?: (versionA: string, versionB: string) => number): void; /** * Setup the verification callback, Return true if the verification passed, otherwise return false */ setVerifyCallback (verifyCallback: (path: string, asset: ManifestAsset) => boolean): void; setEventCallback (eventCallback: (event: EventAssetsManager) => void): void; } /** * FileUtils Helper class to handle file operations. */ export namespace fileUtils{ /** * Checks whether the path is an absolute path. * * @note On Android, if the parameter passed in is relative to "@assets/", this method will treat it as an absolute path. * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path. * * @param path The path that needs to be checked. * @return True if it's an absolute path, false if not. */ export function isAbsolutePath (path:string):boolean; /** Returns the fullpath for a given filename. First it will try to get a new filename from the "filenameLookup" dictionary. If a new filename can't be found on the dictionary, it will use the original filename. Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths. The file search is based on the array element order of search paths and resolution directories. For instance: We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths, and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd") to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/". If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains `key: sprite.png -> value: sprite.pvr.gz`. Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows: /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next) /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next) /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next) /mnt/sdcard/sprite.pvr.gz (if not found, search next) internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next) internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next) internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next) internal_dir/sprite.pvr.gz (if not found, return "sprite.png") If the filename contains relative path like "gamescene/uilayer/sprite.png", and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`. The file search order will be: /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next) internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png") If the new file can't be found on the file system, it will return the parameter filename directly. This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, you might need to load different resources for a given file in the different platforms. @since v2.1 */ export function fullPathForFilename (filename:string):string; /** * Gets string from a file. */ export function getStringFromFile (filename:string):string; /** * Removes a file. * * @param filepath The full path of the file, it must be an absolute path. * @return True if the file have been removed successfully, false if not. */ export function removeFile (filepath:string):boolean; /** * Checks whether the path is a directory. * * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return True if the directory exists, false if not. */ export function isDirectoryExist (dirPath:string):boolean; /** * Normalize: remove . and .. * @param filepath */ export function normalizePath (filepath:string):string; /** * Get default resource root path. */ export function getDefaultResourceRootPath ():string; /** * Loads the filenameLookup dictionary from the contents of a filename. * * @note The plist file name should follow the format below: * * @code * <?xml version="1.0" encoding="UTF-8"?> * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> * <plist version="1.0"> * <dict> * <key>filenames</key> * <dict> * <key>sounds/click.wav</key> * <string>sounds/click.caf</string> * <key>sounds/endgame.wav</key> * <string>sounds/endgame.caf</string> * <key>sounds/gem-0.wav</key> * <string>sounds/gem-0.caf</string> * </dict> * <key>metadata</key> * <dict> * <key>version</key> * <integer>1</integer> * </dict> * </dict> * </plist> * @endcode * @param filename The plist file name. * @since v2.1 * @js loadFilenameLookup * @lua loadFilenameLookup */ export function loadFilenameLookup (filepath:string):void; /** Checks whether to pop up a message box when failed to load an image. * @return True if pop up a message box when failed to load an image, false if not. */ export function isPopupNotify ():boolean; /** * Sets whether to pop-up a message box when failed to load an image. */ export function setPopupNotify (notify:boolean):void; // Converts the contents of a file to a ValueVector. // This method is used internally. export function getValueVectorFromFile (filepath:string):Array<any>; /** * Gets the array of search paths. * * @return The array of search paths which may contain the prefix of default resource root path. * @note In best practise, getter function should return the value of setter function passes in. * But since we should not break the compatibility, we keep using the old logic. * Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead. * @see fullPathForFilename(const char*). * @lua NA */ export function getSearchPaths ():Array<string>; /** * * @param filepath */ export function getFileDir (filepath:string):string; /** * write a ValueMap into a plist file * *@param dict the ValueMap want to save (key,value) *@param fullPath The full path to the file you want to save a string *@return bool */ export function writeToFile (valueMap:any):boolean; /** * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'. * @return The array of the original search paths */ export function getOriginalSearchPaths ():Array<string>; /** * List all files in a directory. * * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ export function listFiles (filepath:string):Array<string>; /** * Converts the contents of a file to a ValueMap. * @param filename The filename of the file to gets content. * @return ValueMap of the file contents. * @note This method is used internally. */ export function getValueMapFromFile (filepath:string):any; /** * Retrieve the file size. * * @note If a relative path was passed in, it will be inserted a default root path at the beginning. * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ export function getFileSize (filepath:string):number; /** Converts the contents of a file to a ValueMap. * This method is used internally. */ export function getValueMapFromData (filedata:string, filesize:number):any; /** * Removes a directory. * * @param dirPath The full path of the directory, it must be an absolute path. * @return True if the directory have been removed successfully, false if not. */ export function removeDirectory (dirPath:string):boolean; /** * Sets the array of search paths. * * You can use this array to modify the search path of the resources. * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array. * * @note This method could access relative path and absolute path. * If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path. * For instance: * On Android, the default resource root path is "@assets/". * If "/mnt/sdcard/" and "resources-large" were set to the search paths vector, * "resources-large" will be converted to "@assets/resources-large" since it was a relative path. * * @param searchPaths The array contains search paths. * @see fullPathForFilename(const char*) * @since v2.1 * In js:var setSearchPaths(var jsval); * @lua NA */ export function setSearchPaths (searchPath:Array<string>):void; /** * write a string into a file * * @param dataStr the string want to save * @param fullPath The full path to the file you want to save a string * @return bool True if write success */ export function writeStringToFile (dataStr:string, fullPath:string):boolean; /** * Sets the array that contains the search order of the resources. * * @param searchResolutionsOrder The source array that contains the search order of the resources. * @see getSearchResolutionsOrder(), fullPathForFilename(const char*). * @since v2.1 * In js:var setSearchResolutionsOrder(var jsval) * @lua NA */ export function setSearchResolutionsOrder (searchResolutionsOrder:Array<string>):void; /** * Append search order of the resources. * * @see setSearchResolutionsOrder(), fullPathForFilename(). * @since v2.1 */ export function addSearchResolutionsOrder (order:string, front:boolean):void; /** * Add search path. * * @since v2.1 */ export function addSearchPath (path:string, front:boolean):void; /** * write ValueVector into a plist file * *@param vecData the ValueVector want to save *@param fullPath The full path to the file you want to save a string *@return bool */ export function writeValueVectorToFile (vecData:Array<any>, fullPath:string):boolean; /** * Checks whether a file exists. * * @note If a relative path was passed in, it will be inserted a default root path at the beginning. * @param filename The path of the file, it could be a relative or absolute path. * @return True if the file exists, false if not. */ export function isFileExist (filename:string):boolean; /** * Purges full path caches. */ export function purgeCachedEntries ():void; /** * Gets full path from a file name and the path of the relative file. * @param filename The file name. * @param relativeFile The path of the relative file. * @return The full path. * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) * */ export function fullPathFromRelativeFile (filename:string, relativeFile:string):string; /** * Windows fopen can't support UTF-8 filename * Need convert all parameters fopen and other 3rd-party libs * * @param filenameUtf8 std::string name file for conversion from utf-8 * @return std::string ansi filename in current locale */ export function getSuitableFOpen (filenameUtf8:string):string; /** * write ValueMap into a plist file * *@param dict the ValueMap want to save *@param fullPath The full path to the file you want to save a string *@return bool */ export function writeValueMapToFile (dict:any, fullPath:string):string; /** * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt. * @param filePath The path of the file, it could be a relative or absolute path. * @return suffix for filename in lower case or empty if a dot not found. */ export function getFileExtension (filePath:string):string; /** * Sets writable path. */ export function setWritablePath (writablePath:string):void; /** * Set default resource root path. */ export function setDefaultResourceRootPath (filepath:string):void; /** * Gets the array that contains the search order of the resources. * * @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*). * @since v2.1 * @lua NA */ export function getSearchResolutionsOrder ():Array<string>; /** * Creates a directory. * * @param dirPath The path of the directory, it must be an absolute path. * @return True if the directory have been created successfully, false if not. */ export function createDirectory (dirPath:string):string; /** * List all files recursively in a directory. * * @param dirPath The path of the directory, it could be a relative or an absolute path. * @return File paths in a string vector */ export function listFilesRecursively (dirPath:string, files:Array<string>):void; /** * Gets the writable path. * @return The path that can be write/read a file in */ export function getWritablePath ():string; } }
the_stack
import { Node } from './node' describe('Root Node', () => { const node = new Node() node.insert('get', '/', 'get root') it('get /', () => { const res = node.search('get', '/') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['get root']) expect(node.search('get', '/hello')).toBeNull() }) }) describe('Root Node is not defined', () => { const node = new Node() node.insert('get', '/hello', 'get hello') it('get /', () => { expect(node.search('get', '/')).toBeNull() }) }) describe('Get with *', () => { const node = new Node() node.insert('get', '*', 'get all') it('get /', () => { expect(node.search('get', '/')).not.toBeNull() expect(node.search('get', '/hello')).not.toBeNull() }) }) describe('Basic Usage', () => { const node = new Node() node.insert('get', '/hello', 'get hello') node.insert('post', '/hello', 'post hello') node.insert('get', '/hello/foo', 'get hello foo') it('get, post /hello', () => { expect(node.search('get', '/')).toBeNull() expect(node.search('post', '/')).toBeNull() expect(node.search('get', '/hello')?.handlers).toEqual(['get hello']) expect(node.search('post', '/hello')?.handlers).toEqual(['post hello']) expect(node.search('put', '/hello')).toBeNull() }) it('get /nothing', () => { expect(node.search('get', '/nothing')).toBeNull() }) it('/hello/foo, /hello/bar', () => { expect(node.search('get', '/hello/foo')?.handlers).toEqual(['get hello foo']) expect(node.search('post', '/hello/foo')).toBeNull() expect(node.search('get', '/hello/bar')).toBeNull() }) it('/hello/foo/bar', () => { expect(node.search('get', '/hello/foo/bar')).toBeNull() }) }) describe('Name path', () => { const node = new Node() node.insert('get', '/entry/:id', 'get entry') node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') node.insert('get', '/map/:location/events', 'get events') it('get /entry/123', () => { const res = node.search('get', '/entry/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['get entry']) expect(res?.params).not.toBeNull() expect(res?.params['id']).toBe('123') expect(res?.params['id']).not.toBe('1234') }) it('get /entry/456/comment', () => { const res = node.search('get', '/entry/456/comment') expect(res).toBeNull() }) it('get /entry/789/comment/123', () => { const res = node.search('get', '/entry/789/comment/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['get comment']) expect(res?.params['id']).toBe('789') expect(res?.params['comment_id']).toBe('123') }) it('get /map/:location/events', () => { const res = node.search('get', '/map/yokohama/events') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['get events']) expect(res?.params['location']).toBe('yokohama') }) }) describe('Name path - Multiple route', () => { const node = new Node() node.insert('get', '/:type/:id', 'common') node.insert('get', '/posts/:id', 'specialized') it('get /posts/123', () => { const res = node.search('get', '/posts/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['common', 'specialized']) expect(res?.params['id']).toBe('123') }) }) describe('Wildcard', () => { const node = new Node() node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard') it('/wildcard-abc/xxxxxx/wildcard-efg', () => { const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['wildcard']) }) node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard') it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => { const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['wildcard']) }) }) describe('Regexp', () => { const node = new Node() node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp') it('/regexp-abc/123/comment/abc', () => { const res = node.search('get', '/regex-abc/123/comment/abc') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['regexp']) expect(res?.params['id']).toBe('123') expect(res?.params['comment_id']).toBe('abc') }) it('/regexp-abc/abc', () => { const res = node.search('get', '/regex-abc/abc') expect(res).toBeNull() }) it('/regexp-abc/123/comment/123', () => { const res = node.search('get', '/regex-abc/123/comment/123') expect(res).toBeNull() }) }) describe('All', () => { const node = new Node() node.insert('ALL', '/all-methods', 'all methods') // ALL it('/all-methods', () => { let res = node.search('get', '/all-methods') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['all methods']) res = node.search('put', '/all-methods') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['all methods']) }) }) describe('Special Wildcard', () => { const node = new Node() node.insert('ALL', '*', 'match all') it('/foo', () => { const res = node.search('get', '/foo') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['match all']) }) it('/hello', () => { const res = node.search('get', '/hello') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['match all']) }) it('/hello/foo', () => { const res = node.search('get', '/hello/foo') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['match all']) }) }) describe('Special Wildcard deeply', () => { const node = new Node() node.insert('ALL', '/hello/*', 'match hello') it('/hello', () => { const res = node.search('get', '/hello') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['match hello']) }) it('/hello/foo', () => { const res = node.search('get', '/hello/foo') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['match hello']) }) }) describe('Default with wildcard', () => { const node = new Node() node.insert('ALL', '/api/*', 'fallback') node.insert('ALL', '/api/abc', 'match api') it('/api/abc', () => { const res = node.search('get', '/api/abc') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['fallback', 'match api']) }) it('/api/def', () => { const res = node.search('get', '/api/def') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['fallback']) }) }) describe('Multi match', () => { describe('Basic', () => { const node = new Node() node.insert('get', '*', 'GET *') node.insert('get', '/abc/*', 'GET /abc/*') node.insert('get', '/abc/*/edf', 'GET /abc/*/edf') node.insert('get', '/abc/edf', 'GET /abc/edf') node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') it('get /abc/edf', () => { const res = node.search('get', '/abc/edf') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf']) }) it('get /abc/xxx/edf', () => { const res = node.search('get', '/abc/xxx/edf') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/*/edf']) }) it('get /', () => { const res = node.search('get', '/') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['GET *']) }) it('post /', () => { const res = node.search('post', '/') expect(res).toBeNull() }) it('get /abc/edf/ghi', () => { const res = node.search('get', '/abc/edf/ghi') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['GET *', 'GET /abc/*']) }) }) describe('Blog', () => { const node = new Node() node.insert('get', '*', 'middleware a') // 0.1 node.insert('ALL', '*', 'middleware b') // 0.2 <=== node.insert('get', '/entry', 'get entries') // 1.3 node.insert('post', '/entry/*', 'middleware c') // 1.4 <=== node.insert('post', '/entry', 'post entry') // 1.5 <=== node.insert('get', '/entry/:id', 'get entry') // 2.6 node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') // 4.7 it('get /entry/123', async () => { const res = node.search('get', '/entry/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry']) expect(res?.params['id']).toBe('123') }) it('get /entry/123/comment/456', async () => { const res = node.search('get', '/entry/123/comment/456') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment']) expect(res?.params['id']).toBe('123') expect(res?.params['comment_id']).toBe('456') }) it('post /entry', async () => { const res = node.search('post', '/entry') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware b', 'middleware c', 'post entry']) }) it('delete /entry', async () => { const res = node.search('delete', '/entry') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware b']) }) }) describe('ALL', () => { const node = new Node() node.insert('ALL', '*', 'ALL *') node.insert('ALL', '/abc/*', 'ALL /abc/*') node.insert('ALL', '/abc/*/def', 'ALL /abc/*/def') it('get /', () => { const res = node.search('get', '/') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['ALL *']) }) it('post /abc', () => { const res = node.search('post', '/abc') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*']) }) it('delete /abc/xxx/def', () => { const res = node.search('post', '/abc/xxx/def') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*', 'ALL /abc/*/def']) }) }) describe('Regexp', () => { const node = new Node() node.insert('get', '/regex-abc/:id{[0-9]+}/*', 'middleware a') node.insert('get', '/regex-abc/:id{[0-9]+}/def', 'regexp') it('/regexp-abc/123/def', () => { const res = node.search('get', '/regex-abc/123/def') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware a', 'regexp']) expect(res?.params['id']).toBe('123') }) it('/regexp-abc/123', () => { const res = node.search('get', '/regex-abc/123/ghi') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['middleware a']) }) }) describe('Trailing slash', () => { const node = new Node() node.insert('get', '/book', 'GET /book') node.insert('get', '/book/:id', 'GET /book/:id') it('get /book', () => { const res = node.search('get', '/book') expect(res).not.toBeNull() }) it('get /book/', () => { const res = node.search('get', '/book/') expect(res).toBeNull() }) }) describe('Same path', () => { const node = new Node() node.insert('get', '/hey', 'Middleware A') node.insert('get', '/hey', 'Middleware B') it('get /hey', () => { const res = node.search('get', '/hey') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['Middleware A', 'Middleware B']) }) }) }) describe('Duplicate param name', () => { it('self', () => { const node = new Node() expect(() => { node.insert('get', '/:id/:id', 'foo') }).toThrowError(/Duplicate param name/) }) it('parent', () => { const node = new Node() node.insert('get', '/:id/:action', 'foo') expect(() => { node.insert('get', '/posts/:id', 'bar') }).toThrowError(/Duplicate param name/) }) it('child', () => { const node = new Node() node.insert('get', '/posts/:id', 'foo') expect(() => { node.insert('get', '/:id/:action', 'bar') }).toThrowError(/Duplicate param name/) }) it('hierarchy', () => { const node = new Node() node.insert('get', '/posts/:id/comments/:comment_id', 'foo') expect(() => { node.insert('get', '/posts/:id', 'bar') }).not.toThrowError() }) it('regular expression', () => { const node = new Node() node.insert('get', '/:id/:action{create|update}', 'foo') expect(() => { node.insert('get', '/:id/:action{delete}', 'bar') }).not.toThrowError() }) }) describe('Sort Order', () => { describe('Basic', () => { const node = new Node() node.insert('get', '*', 'a') node.insert('get', '/page', '/page') node.insert('get', '/:slug', '/:slug') it('get /page', () => { const res = node.search('get', '/page') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['a', '/page', '/:slug']) }) }) describe('With Named path', () => { const node = new Node() node.insert('get', '*', 'a') node.insert('get', '/posts/:id', '/posts/:id') node.insert('get', '/:type/:id', '/:type/:id') it('get /posts/123', () => { const res = node.search('get', '/posts/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['a', '/posts/:id', '/:type/:id']) }) }) describe('With Wildcards', () => { const node = new Node() node.insert('get', '/api/*', '1st') node.insert('get', '/api/*', '2nd') node.insert('get', '/api/posts/:id', '3rd') node.insert('get', '/api/*', '4th') it('get /api/posts/123', () => { const res = node.search('get', '/api/posts/123') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['1st', '2nd', '4th', '3rd']) }) }) describe('With special Wildcard', () => { const node = new Node() node.insert('get', '/posts', '/posts') // 1.1 node.insert('get', '/posts/*', '/posts/*') // 1.2 node.insert('get', '/posts/:id', '/posts/:id') // 2.3 it('get /posts', () => { const res = node.search('get', '/posts') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['/posts', '/posts/*']) }) }) describe('Complex', () => { const node = new Node() node.insert('get', '/api', 'x') // score 1.1 node.insert('get', '/api/*', 'c') // score 2.2 node.insert('get', '/api/:type', 'y') // score 2.3 node.insert('get', '/api/:type/:id', 'd') // score 3.4 node.insert('get', '/api/posts/:id', 'e') // score 3.5 node.insert('get', '/api/posts/123', 'f') // score 3.6 node.insert('get', '/*/*/:id', 'g') // score 3.7 node.insert('get', '/api/posts/*/comment', 'z') // score 4.8 - not match node.insert('get', '*', 'a') // score 1.9 node.insert('get', '*', 'b') // score 1.10 it('get /api/posts/123', () => { const res = node.search('get', '/api/posts/123') // ---> will match => c, d, e, e, f, g, a, b // ---> sort by score => a, b, c, d, e, f, g expect(res?.handlers).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g']) }) }) describe('Multi match', () => { const node = new Node() node.insert('get', '*', 'GET *') // 0.1 node.insert('get', '/abc/*', 'GET /abc/*') // 1.2 node.insert('get', '/abc/edf', 'GET /abc/edf') // 2.3 node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4 it('get /abc/edf', () => { const res = node.search('get', '/abc/edf') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf']) }) }) describe('Multi match', () => { const node = new Node() node.insert('get', '/api/*', 'a') // 2.1 for /api/entry node.insert('get', '/api/entry', 'entry') // 2.2 node.insert('ALL', '/api/*', 'b') // 2.3 for /api/entry it('get /api/entry', async () => { const res = node.search('get', '/api/entry') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['a', 'entry', 'b']) }) }) describe('fallback', () => { describe('Blog - failed', () => { const node = new Node() node.insert('post', '/entry', 'post entry') // 1.1 node.insert('post', '/entry/*', 'fallback') // 1.2 node.insert('get', '/entry/:id', 'get entry') // 2.3 it('post /entry', async () => { const res = node.search('post', '/entry') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['post entry', 'fallback']) }) }) }) describe('page', () => { const node = new Node() node.insert('get', '/page', 'page') // 1.1 node.insert('ALL', '/*', 'fallback') // 1.2 it('get /page', async () => { const res = node.search('get', '/page') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['page', 'fallback']) }) }) }) describe('star', () => { const node = new Node() node.insert('get', '/', '/') node.insert('get', '/*', '/*') node.insert('get', '*', '*') node.insert('get', '/x', '/x') node.insert('get', '/x/*', '/x/*') it('top', async () => { const res = node.search('get', '/') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/'] }) it('Under a certain path', async () => { const res = node.search('get', '/x') expect(res).not.toBeNull() expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*']) }) })
the_stack
import * as debugGenerator from "debug"; import { postcss } from "opticss"; import { Block } from "../BlockTree"; import { Options, ResolvedConfiguration, resolveConfiguration } from "../configuration"; import { CssBlockError } from "../errors"; import { FileIdentifier } from "../importing"; import { builders } from "./ast"; import { addPresetSelectors } from "./features/add-preset-selectors"; import { assertForeignGlobalAttribute } from "./features/assert-foreign-global-attribute"; import { composeBlock } from "./features/composes-block"; import { constructBlock } from "./features/construct-block"; import { disallowDefinitionRules } from "./features/disallow-dfn-rules"; import { disallowImportant } from "./features/disallow-important"; import { discoverGuid } from "./features/discover-guid"; import { discoverName } from "./features/discover-name"; import { exportBlocks, exportBlocksSync } from "./features/export-blocks"; import { extendBlock } from "./features/extend-block"; import { globalAttributes } from "./features/global-attributes"; import { implementBlock } from "./features/implement-block"; import { importBlocks, importBlocksSync } from "./features/import-blocks"; import { processDebugStatements } from "./features/process-debug-statements"; import { BlockFactory } from "./index"; import { BlockFactorySync } from "./index"; import { Syntax } from "./preprocessing"; import { gen_guid } from "./utils/genGuid"; const debug = debugGenerator("css-blocks:BlockParser"); export interface ParsedSource { identifier: FileIdentifier; defaultName: string; originalSource: string; originalSyntax: Syntax; parseResult: postcss.Root; dependencies: string[]; } /** * Parser that, given a PostCSS AST will return a `Block` object. Main public * interface is `BlockParser.parse`. */ export class BlockParser { private config: ResolvedConfiguration; private factory: BlockFactory | BlockFactorySync; constructor(opts: Options, factory: BlockFactory | BlockFactorySync) { this.config = resolveConfiguration(opts); this.factory = factory; } public async parseSource(source: ParsedSource): Promise<Block> { let root = source.parseResult; let block = await this.parse(root, source.identifier, source.defaultName); for (let dependency of source.dependencies) { block.addDependency(dependency); } return block; } public parseSourceSync(source: ParsedSource): Block { let root = source.parseResult; let block = this.parseSync(root, source.identifier, source.defaultName); for (let dependency of source.dependencies) { block.addDependency(dependency); } return block; } public async parseDefinitionSource(root: postcss.Root, identifier: string, expectedId: string, defaultName: string): Promise<Block> { return await this.parse(root, identifier, defaultName, true, expectedId); } public parseDefinitionSourceSync(root: postcss.Root, identifier: string, expectedId: string, defaultName: string): Block { return this.parseSync(root, identifier, defaultName, true, expectedId); } /** * Main public interface of `BlockParser`. Given a PostCSS AST, returns a promise * for the new `Block` object. * @param root - PostCSS AST * @param sourceFile - Source file name * @param name - Name of block * @param isDfnFile - Whether the block being parsed is a definition file. Definition files are incomplete blocks * that will need to merge in rules from its Compiled CSS later. They are also expected to declare * additional properties that regular Blocks don't, such as `block-id`. * @param expectedGuid - If a GUID is defined in the file, it's expected to match this value. This argument is only * relevant to definition files, where the definition file is linked to Compiled CSS and * both files may declare a GUID. */ public async parse(root: postcss.Root, identifier: string, name: string, isDfnFile = false, expectedGuid?: string): Promise<Block> { let importer = this.config.importer; let debugIdent = importer.debugIdentifier(identifier, this.config); let sourceFile = importer.filesystemPath(identifier, this.config) || debugIdent; let configuration = this.factory.configuration; debug(`Begin parse: "${debugIdent}" which ${isDfnFile ? "is" : "is not"} a definition file.`); // Discover the block's preferred name. let nameDiscoveryError: CssBlockError | undefined; try { name = discoverName(configuration, root, sourceFile, isDfnFile, name); } catch (e) { nameDiscoveryError = e; } // Discover, or generate, the block's GUID. let guid: string; let guidDiscoveryError: CssBlockError | undefined; try { guid = discoverGuid(configuration, root, sourceFile, isDfnFile, expectedGuid) || gen_guid(identifier, configuration.guidAutogenCharacters); } catch (e) { guidDiscoveryError = e; guid = gen_guid(identifier, configuration.guidAutogenCharacters); } // Create our new Block object and save reference to the raw AST. let block = new Block(name, identifier, guid, root); block.blockAST = builders.root(); // Add any errors that surfaced during name and GUID discovery. if (nameDiscoveryError) { block.addError(nameDiscoveryError); } if (guidDiscoveryError) { block.addError(guidDiscoveryError); } if (!isDfnFile) { // If not a definition file, it shouldn't have rules that can // only be in definition files. debug(" - Disallow Definition-Only Declarations"); disallowDefinitionRules(block, configuration, root, sourceFile); } // Throw if we encounter any `!important` decls. disallowImportant(configuration, root, block, sourceFile); // Discover and parse all block references included by this block. await importBlocks(block, this.factory, sourceFile); // Export all exported block references from this block. await exportBlocks(block, this.factory, sourceFile); // Handle any global attributes defined by this block. globalAttributes(configuration, root, block, sourceFile); // Parse all block styles and build block tree. constructBlock(configuration, root, block, debugIdent); // Verify that external blocks referenced have been imported, have defined the attribute being selected, and have marked it as a global state. assertForeignGlobalAttribute(configuration, root, block, debugIdent); // Construct block extensions and validate. extendBlock(configuration, root, block, debugIdent); // Validate that all required Styles are implemented. implementBlock(configuration, root, block, debugIdent); // Register all block compositions. composeBlock(configuration, root, block, debugIdent); // Log any debug statements discovered. processDebugStatements(root, block, debugIdent, this.config); // These rules are only relevant to definition files. We run these after we're // basically done reconstituting the block. if (isDfnFile) { // Find any block-class rules and override the class name of the block with its value. debug(" - Process Preset Block Classes"); addPresetSelectors(configuration, root, block, debugIdent); // TODO: Process inherited-styles? } // Return our fully constructed block. debug(` - Complete`); return block; } /** * Main public interface of `BlockParser`. Given a PostCSS AST, returns a * new `Block` object if the block hasn't yet been parsed, or the existing block if it has. * * @param root - PostCSS AST * @param sourceFile - Source file name * @param name - Name of block * @param isDfnFile - Whether the block being parsed is a definition file. Definition files are incomplete blocks * that will need to merge in rules from its Compiled CSS later. They are also expected to declare * additional properties that regular Blocks don't, such as `block-id`. * @param expectedGuid - If a GUID is defined in the file, it's expected to match this value. This argument is only * relevant to definition files, where the definition file is linked to Compiled CSS and * both files may declare a GUID. */ public parseSync(root: postcss.Root, identifier: string, name: string, isDfnFile = false, expectedGuid?: string): Block { let importer = this.config.importer; let debugIdent = importer.debugIdentifier(identifier, this.config); let sourceFile = importer.filesystemPath(identifier, this.config) || debugIdent; let configuration = this.factory.configuration; if (!this.factory.isSync) { throw new CssBlockError("Configuration Error: an async factory was provided for a synchronous method call."); } debug(`Begin parse: "${debugIdent}" which ${isDfnFile ? "is" : "is not"} a definition file.`); // Discover the block's preferred name. let nameDiscoveryError: CssBlockError | undefined; try { name = discoverName(configuration, root, sourceFile, isDfnFile, name); } catch (e) { nameDiscoveryError = e; } // Discover, or generate, the block's GUID. let guid: string; let guidDiscoveryError: CssBlockError | undefined; try { guid = discoverGuid(configuration, root, sourceFile, isDfnFile, expectedGuid) || gen_guid(identifier, configuration.guidAutogenCharacters); } catch (e) { guidDiscoveryError = e; guid = gen_guid(identifier, configuration.guidAutogenCharacters); } // Create our new Block object and save reference to the raw AST. let block = new Block(name, identifier, guid, root); block.blockAST = builders.root(); // Add any errors that surfaced during name and GUID discovery. if (nameDiscoveryError) { block.addError(nameDiscoveryError); } if (guidDiscoveryError) { block.addError(guidDiscoveryError); } if (!isDfnFile) { // If not a definition file, it shouldn't have rules that can // only be in definition files. disallowDefinitionRules(block, configuration, root, sourceFile); } // Throw if we encounter any `!important` decls. disallowImportant(configuration, root, block, sourceFile); // Discover and parse all block references included by this block. importBlocksSync(block, this.factory, sourceFile); // Export all exported block references from this block. exportBlocksSync(block, this.factory, sourceFile); // Handle any global attributes defined by this block. globalAttributes(configuration, root, block, sourceFile); // Parse all block styles and build block tree. constructBlock(configuration, root, block, debugIdent); // Verify that external blocks referenced have been imported, have defined the attribute being selected, and have marked it as a global state. assertForeignGlobalAttribute(configuration, root, block, debugIdent); // Construct block extensions and validate. extendBlock(configuration, root, block, debugIdent); // Validate that all required Styles are implemented. implementBlock(configuration, root, block, debugIdent); // Register all block compositions. composeBlock(configuration, root, block, debugIdent); // Log any debug statements discovered. processDebugStatements(root, block, debugIdent, this.config); // These rules are only relevant to definition files. We run these after we're // basically done reconstituting the block. if (isDfnFile) { // Find any block-class rules and override the class name of the block with its value. addPresetSelectors(configuration, root, block, debugIdent); // TODO: Process inherited-styles? } return block; } }
the_stack
import { ActionTypes } from 'app/containers/Projects/constants' import actions from 'app/containers/Projects/actions' import { mockStore } from './fixtures' describe('Projects Actions', () => { const { project, projectId, projects, resolve, orgId, isFavorite, adminIds, relationId } = mockStore describe('clearCurrentProject', () => { it('clearCurrentProject should return the correct type', () => { const expectedResult = { type: ActionTypes.CLEAR_CURRENT_PROJECT } expect(actions.clearCurrentProject()).toEqual(expectedResult) }) }) describe('loadProjects', () => { it('loadProjects should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECTS } expect(actions.loadProjects()).toEqual(expectedResult) }) }) describe('projectsLoaded', () => { it('projectsLoaded should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECTS_SUCCESS, payload: { projects } } expect(actions.projectsLoaded(projects)).toEqual(expectedResult) }) }) describe('loadProjectsFail', () => { it('loadProjectsFail should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECTS_FAILURE } expect(actions.loadProjectsFail()).toEqual(expectedResult) }) }) describe('addProject', () => { it('addProject should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT, payload: { project, resolve } } expect(actions.addProject(project, resolve)).toEqual(expectedResult) }) }) describe('projectAdded', () => { it('projectAdded should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_SUCCESS, payload: { result: project } } expect(actions.projectAdded(project)).toEqual(expectedResult) }) }) describe('addProjectFail', () => { it('addProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_FAILURE } expect(actions.addProjectFail()).toEqual(expectedResult) }) }) describe('editProject', () => { it('editProject should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_PROJECT, payload: { project, resolve } } expect(actions.editProject(project, resolve)).toEqual(expectedResult) }) }) describe('projectEdited', () => { it('projectEdited should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_PROJECT_SUCCESS, payload: { result: project } } expect(actions.projectEdited(project)).toEqual(expectedResult) }) }) describe('editProjectFail', () => { it('editProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.EDIT_PROJECT_FAILURE } expect(actions.editProjectFail()).toEqual(expectedResult) }) }) describe('transferProject', () => { it('transferProject should return the correct type', () => { const expectedResult = { type: ActionTypes.TRANSFER_PROJECT, payload: { id: projectId, orgId, resolve } } expect(actions.transferProject(projectId, orgId, resolve)).toEqual( expectedResult ) }) }) describe('projectTransfered', () => { it('projectTransfered should return the correct type', () => { const expectedResult = { type: ActionTypes.TRANSFER_PROJECT_SUCCESS, payload: { result: project } } expect(actions.projectTransfered(project)).toEqual(expectedResult) }) }) describe('transferProjectFail', () => { it('transferProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.TRANSFER_PROJECT_FAILURE } expect(actions.transferProjectFail()).toEqual(expectedResult) }) }) describe('deleteProject', () => { it('deleteProject should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT, payload: { id: projectId, resolve } } expect(actions.deleteProject(projectId, resolve)).toEqual(expectedResult) }) }) describe('projectDeleted', () => { it('projectDeleted should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_SUCCESS, payload: { id: projectId } } expect(actions.projectDeleted(projectId)).toEqual(expectedResult) }) }) describe('deleteProjectFail', () => { it('deleteProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_FAILURE } expect(actions.deleteProjectFail()).toEqual(expectedResult) }) }) describe('loadProjectDetail', () => { it('loadProjectDetail should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECT_DETAIL, payload: { id: projectId } } expect(actions.loadProjectDetail(projectId)).toEqual(expectedResult) }) }) describe('projectDetailLoaded', () => { it('projectDetailLoaded should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECT_DETAIL_SUCCESS, payload: { project } } expect(actions.projectDetailLoaded(project)).toEqual(expectedResult) }) }) describe('loadProjectDetailFail', () => { it('loadProjectDetailFail should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_PROJECT_DETAIL_FAILURE } expect(actions.loadProjectDetailFail()).toEqual(expectedResult) }) }) describe('searchProject', () => { it('searchProject should return the correct type', () => { const expectedResult = { type: ActionTypes.SEARCH_PROJECT, payload: { param: 'projectName' } } expect(actions.searchProject('projectName')).toEqual(expectedResult) }) }) describe('projectSearched', () => { it('projectSearched should return the correct type', () => { const expectedResult = { type: ActionTypes.SEARCH_PROJECT_SUCCESS, payload: { result: project } } expect(actions.projectSearched(project)).toEqual(expectedResult) }) }) describe('searchProjectFail', () => { it('searchProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.SEARCH_PROJECT_FAILURE } expect(actions.searchProjectFail()).toEqual(expectedResult) }) }) describe('getProjectStarUser', () => { it('getProjectStarUser should return the correct type', () => { const expectedResult = { type: ActionTypes.GET_PROJECT_STAR_USER, payload: { id: projectId } } expect(actions.getProjectStarUser(projectId)).toEqual(expectedResult) }) }) describe('getProjectStarUserSuccess', () => { it('getProjectStarUserSuccess should return the correct type', () => { const expectedResult = { type: ActionTypes.GET_PROJECT_STAR_USER_SUCCESS, payload: { result: project } } expect(actions.getProjectStarUserSuccess(project)).toEqual(expectedResult) }) }) describe('getProjectStarUserFail', () => { it('getProjectStarUserFail should return the correct type', () => { const expectedResult = { type: ActionTypes.GET_PROJECT_STAR_USER_FAILURE } expect(actions.getProjectStarUserFail()).toEqual(expectedResult) }) }) describe('unStarProject', () => { it('unStarProject should return the correct type', () => { const expectedResult = { type: ActionTypes.PROJECT_UNSTAR, payload: { id: projectId, resolve } } expect(actions.unStarProject(projectId, resolve)).toEqual(expectedResult) }) }) describe('unStarProjectSuccess', () => { it('unStarProjectSuccess should return the correct type', () => { const expectedResult = { type: ActionTypes.PROJECT_UNSTAR_SUCCESS, payload: { result: project } } expect(actions.unStarProjectSuccess(project)).toEqual(expectedResult) }) }) describe('unStarProjectFail', () => { it('unStarProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.PROJECT_UNSTAR_FAILURE } expect(actions.unStarProjectFail()).toEqual(expectedResult) }) }) describe('loadCollectProjects', () => { it('loadCollectProjects should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_COLLECT_PROJECTS } expect(actions.loadCollectProjects()).toEqual(expectedResult) }) }) describe('collectProjectLoaded', () => { it('collectProjectLoaded should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_COLLECT_PROJECTS_SUCCESS, payload: { result: project } } expect(actions.collectProjectLoaded(project)).toEqual(expectedResult) }) }) describe('collectProjectFail', () => { it('collectProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_COLLECT_PROJECTS_FAILURE } expect(actions.collectProjectFail()).toEqual(expectedResult) }) }) describe('clickCollectProjects', () => { it('clickCollectProjects should return the correct type', () => { const expectedResult = { type: ActionTypes.CLICK_COLLECT_PROJECT, payload: { isFavorite, proId: projectId, resolve } } expect( actions.clickCollectProjects(isFavorite, projectId, resolve) ).toEqual(expectedResult) }) }) describe('collectProjectClicked', () => { it('collectProjectClicked should return the correct type', () => { const expectedResult = { type: ActionTypes.CLICK_COLLECT_PROJECT_SUCCESS, payload: { result: project } } expect(actions.collectProjectClicked(project)).toEqual(expectedResult) }) }) describe('clickCollectProjectFail', () => { it('clickCollectProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.CLICK_COLLECT_PROJECT_FAILURE } expect(actions.clickCollectProjectFail()).toEqual(expectedResult) }) }) describe('addProjectAdmin', () => { it('addProjectAdmin should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ADMIN, payload: { id: projectId, adminIds, resolve } } expect(actions.addProjectAdmin(projectId, adminIds, resolve)).toEqual( expectedResult ) }) }) describe('projectAdminAdded', () => { it('projectAdminAdded should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ADMIN_SUCCESS, payload: { result: project } } expect(actions.projectAdminAdded(project)).toEqual(expectedResult) }) }) describe('addProjectAdminFail', () => { it('addProjectAdminFail should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ADMIN_FAIL } expect(actions.addProjectAdminFail()).toEqual(expectedResult) }) }) describe('deleteProjectAdmin', () => { it('deleteProjectAdmin should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ADMIN, payload: { id: projectId, relationId, resolve } } expect( actions.deleteProjectAdmin(projectId, relationId, resolve) ).toEqual(expectedResult) }) }) describe('projectAdminDeleted', () => { it('projectAdminDeleted should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ADMIN_SUCCESS, payload: { result: project } } expect(actions.projectAdminDeleted(project)).toEqual(expectedResult) }) }) describe('deleteProjectAdminFail', () => { it('deleteProjectAdminFail should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ADMIN_FAIL } expect(actions.deleteProjectAdminFail()).toEqual(expectedResult) }) }) describe('addProjectRole', () => { it('addProjectRole should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ROLE, payload: { projectId, roleIds: adminIds, resolve } } expect(actions.addProjectRole(projectId, adminIds, resolve)).toEqual( expectedResult ) }) }) describe('projectRoleAdded', () => { it('projectRoleAdded should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ROLE_SUCCESS, payload: { result: project } } expect(actions.projectRoleAdded(project)).toEqual(expectedResult) }) }) describe('addProjectRoleFail', () => { it('addProjectRoleFail should return the correct type', () => { const expectedResult = { type: ActionTypes.ADD_PROJECT_ROLE_FAIL } expect(actions.addProjectRoleFail()).toEqual(expectedResult) }) }) describe('deleteProjectRole', () => { it('deleteProjectRole should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ROLE, payload: { id: projectId, relationId, resolve } } expect(actions.deleteProjectRole(projectId, relationId, resolve)).toEqual( expectedResult ) }) }) describe('projectRoleDeleted', () => { it('projectRoleDeleted should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ROLE_SUCCESS, payload: { result: project } } expect(actions.projectRoleDeleted(project)).toEqual(expectedResult) }) }) describe('deleteProjectRoleFail', () => { it('deleteProjectRoleFail should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_PROJECT_ROLE_FAIL } expect(actions.deleteProjectRoleFail()).toEqual(expectedResult) }) }) describe('updateRelRoleProject', () => { it('updateRelRoleProject should return the correct type', () => { const expectedResult = { type: ActionTypes.UPDATE_RELATION_ROLE_PROJECT, payload: { roleId: relationId, projectId, projectRole: adminIds } } expect( actions.updateRelRoleProject(relationId, projectId, adminIds) ).toEqual(expectedResult) }) }) describe('relRoleProjectUpdated', () => { it('relRoleProjectUpdated should return the correct type', () => { const expectedResult = { type: ActionTypes.UPDATE_RELATION_ROLE_PROJECT_SUCCESS, payload: { result: project } } expect(actions.relRoleProjectUpdated(project)).toEqual(expectedResult) }) }) describe('updateRelRoleProjectFail', () => { it('updateRelRoleProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.UPDATE_RELATION_ROLE_PROJECT_FAIL } expect(actions.updateRelRoleProjectFail()).toEqual(expectedResult) }) }) describe('deleteRelRoleProject', () => { it('deleteRelRoleProject should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_RELATION_ROLE_PROJECT, payload: { roleId: relationId, projectId, resolve } } expect( actions.deleteRelRoleProject(relationId, projectId, resolve) ).toEqual(expectedResult) }) }) describe('relRoleProjectDeleted', () => { it('relRoleProjectDeleted should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_RELATION_ROLE_PROJECT_SUCCESS, payload: { result: project } } expect(actions.relRoleProjectDeleted(project)).toEqual(expectedResult) }) }) describe('deleteRelRoleProjectFail', () => { it('deleteRelRoleProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.DELETE_RELATION_ROLE_PROJECT_FAIL } expect(actions.deleteRelRoleProjectFail()).toEqual(expectedResult) }) }) describe('loadRelRoleProject', () => { it('loadRelRoleProject should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_RELATION_ROLE_PROJECT, payload: { id: projectId, roleId: relationId } } expect(actions.loadRelRoleProject(projectId, relationId)).toEqual( expectedResult ) }) }) describe('relRoleProjectLoaded', () => { it('relRoleProjectLoaded should return the correct type', () => { const expectedResult = { type: ActionTypes.RELATION_ROLE_PROJECT_LOADED, payload: { result: project } } expect(actions.relRoleProjectLoaded(project)).toEqual(expectedResult) }) }) describe('loadRelRoleProjectFail', () => { it('loadRelRoleProjectFail should return the correct type', () => { const expectedResult = { type: ActionTypes.LOAD_RELATION_ROLE_PROJECT_FAIL } expect(actions.loadRelRoleProjectFail()).toEqual(expectedResult) }) }) describe('excludeRoles', () => { it('excludeRoles should return the correct type', () => { const expectedResult = { type: ActionTypes.EXCLUDE_ROLES, payload: { type: 'roleType', id: relationId, resolve } } expect(actions.excludeRoles('roleType', relationId, resolve)).toEqual( expectedResult ) }) }) describe('rolesExcluded', () => { it('rolesExcluded should return the correct type', () => { const expectedResult = { type: ActionTypes.EXCLUDE_ROLES_SUCCESS, payload: { result: project } } expect(actions.rolesExcluded(project)).toEqual(expectedResult) }) }) describe('excludeRolesFail', () => { it('excludeRolesFail should return the correct type', () => { const expectedResult = { type: ActionTypes.EXCLUDE_ROLES_FAIL, payload: { err: 'err' } } expect(actions.excludeRolesFail('err')).toEqual(expectedResult) }) }) })
the_stack
module es { /** * 创建这个字典的原因只有一个: * 我需要一个能让我直接以数组的形式对值进行迭代的字典,而不需要生成一个数组或使用迭代器。 * 对于这个目标是比标准字典快N倍。 * Faster dictionary在大部分操作上也比标准字典快,但差别可以忽略不计。 * 唯一较慢的操作是在添加时调整内存大小,因为与标准数组相比,这个实现需要使用两个单独的数组。 */ export class FasterDictionary<TKey, TValue> { public _values: TValue[]; public _valuesInfo: FastNode[]; public _buckets: number[]; public _freeValueCellIndex: number = 0; public _collisions: number = 0; constructor(size: number = 1) { this._valuesInfo = new Array(size); this._values = new Array(size); this._buckets = new Array(HashHelpers.getPrime(size)); } public getValuesArray(count: {value: number}): TValue[] { count.value = this._freeValueCellIndex; return this._values; } public get valuesArray(): TValue[] { return this._values; } public get count(): number { return this._freeValueCellIndex; } public add(key: TKey, value: TValue) { if (!this.addValue(key, value, {value: 0})) throw new Error("key 已经存在") } public addValue(key: TKey, value: TValue, indexSet: {value: number}) { let hash = HashHelpers.getHashCode(key); let bucketIndex = FasterDictionary.reduce(hash, this._buckets.length); if (this._freeValueCellIndex == this._values.length) { let expandPrime = HashHelpers.expandPrime(this._freeValueCellIndex); this._values.length = expandPrime; this._valuesInfo.length = expandPrime; } // buckets值-1表示它是空的 let valueIndex = NumberExtension.toNumber(this._buckets[bucketIndex]) - 1; if (valueIndex == -1) { // 在最后一个位置创建信息节点,并填入相关信息 this._valuesInfo[this._freeValueCellIndex] = new FastNode(key, hash); } else { { let currentValueIndex = valueIndex; do { // 必须检查键是否已经存在于字典中 if (this._valuesInfo[currentValueIndex].hashcode == hash && this._valuesInfo[currentValueIndex].key == key) { // 键已经存在,只需将其值替换掉即可 this._values[currentValueIndex] = value; indexSet.value = currentValueIndex; return false; } currentValueIndex = this._valuesInfo[currentValueIndex].previous; } while (currentValueIndex != -1); // -1表示没有更多的值与相同的哈希值的键 } this._collisions++; // 创建一个新的节点,该节点之前的索引指向当前指向桶的节点 this._valuesInfo[this._freeValueCellIndex] = new FastNode(key, hash, valueIndex); // 更新现有单元格的下一个单元格指向新的单元格,旧的单元格 -> 新的单元格 -> 旧的单元格 <- 下一个单元格 this._valuesInfo[valueIndex].next = this._freeValueCellIndex; } // 重要的是:新的节点总是被桶单元格指向的那个节点,所以我可以假设被桶指向的那个节点总是最后添加的值(next = -1) // item与这个bucketIndex将指向最后创建的值 // TODO: 如果相反,我假设原来的那个是bucket中的那个,我就不需要在这里更新bucket了 this._buckets[bucketIndex] = (this._freeValueCellIndex + 1); this._values[this._freeValueCellIndex] = value; indexSet.value = this._freeValueCellIndex; this._freeValueCellIndex++; if (this._collisions > this._buckets.length) { // 我们需要更多的空间和更少的碰撞 this._buckets = new Array(HashHelpers.expandPrime(this._collisions)); this._collisions = 0; // 我们需要得到目前存储的所有值的哈希码,并将它们分布在新的桶长上 for (let newValueIndex = 0; newValueIndex < this._freeValueCellIndex; newValueIndex++) { // 获取原始哈希码,并根据新的长度找到新的bucketIndex bucketIndex = FasterDictionary.reduce(this._valuesInfo[newValueIndex].hashcode, this._buckets.length); // bucketsIndex可以是-1或下一个值。 // 如果是-1意味着没有碰撞。 // 如果有碰撞,我们创建一个新节点,它的上一个指向旧节点。 // 旧节点指向新节点,新节点指向旧节点,旧节点指向新节点,现在bucket指向新节点,这样我们就可以重建linkedlist. // 获取当前值Index,如果没有碰撞,则为-1。 let existingValueIndex = NumberExtension.toNumber(this._buckets[bucketIndex]) - 1; // 将bucket索引更新为共享bucketIndex的当前项目的索引(最后找到的总是bucket中的那个) this._buckets[bucketIndex] = newValueIndex + 1; if (existingValueIndex != -1) { // 这个单元格已经指向了新的bucket list中的一个值,这意味着有一个碰撞,出了问题 this._collisions++; // bucket将指向这个值,所以新的值将使用以前的索引 this._valuesInfo[newValueIndex].previous = existingValueIndex; this._valuesInfo[newValueIndex].next = -1; // 并将之前的下一个索引更新为新的索引 this._valuesInfo[existingValueIndex].next = newValueIndex; } else { // 什么都没有被索引,桶是空的。我们需要更新之前的 next 和 previous 的值。 this._valuesInfo[newValueIndex].next = -1; this._valuesInfo[newValueIndex].previous = -1; } } } return true; } public remove(key: TKey): boolean { let hash = FasterDictionary.hash(key); let bucketIndex = FasterDictionary.reduce(hash, this._buckets.length); // 找桶 let indexToValueToRemove = NumberExtension.toNumber(this._buckets[bucketIndex]) - 1; // 第一部分:在bucket list中寻找实际的键,如果找到了,我就更新bucket list,使它不再指向要删除的单元格。 while (indexToValueToRemove != -1) { if (this._valuesInfo[indexToValueToRemove].hashcode == hash && this._valuesInfo[indexToValueToRemove].key == key) { // 如果找到了密钥,并且桶直接指向了要删除的节点 if (this._buckets[bucketIndex] - 1 == indexToValueToRemove){ if (this._valuesInfo[indexToValueToRemove].next != -1) throw new Error("如果 bucket 指向单元格,那么 next 必须不存在。"); // 如果前一个单元格存在,它的下一个指针必须被更新! //<---迭代顺序 // B(ucket总是指向最后一个) // ------- ------- ------- // 1 | | | | 2 | | | 3 | //bucket不能有下一个,只能有上一个。 // ------- ------- ------- //--> 插入 let value = this._valuesInfo[indexToValueToRemove].previous; this._buckets[bucketIndex] = value + 1; }else{ if (this._valuesInfo[indexToValueToRemove].next == -1) throw new Error("如果 bucket 指向另一个单元格,则 NEXT 必须存在"); } FasterDictionary.updateLinkedList(indexToValueToRemove, this._valuesInfo); break; } indexToValueToRemove = this._valuesInfo[indexToValueToRemove].previous; } if (indexToValueToRemove == -1) return false; // 未找到 this._freeValueCellIndex --; // 少了一个需要反复计算的值 // 第二部分 // 这时节点指针和水桶会被更新,但_values数组会被更新仍然有要删除的值 // 这个字典的目标是能够做到像数组一样对数值进行迭代,所以数值数组必须始终是最新的 // 如果要删除的单元格是列表中的最后一个,我们可以执行较少的操作(不需要交换),否则我们要将最后一个值的单元格移到要删除的值上。 if (indexToValueToRemove != this._freeValueCellIndex){ // 我们可以将两个数组的最后一个值移到要删除的数组中。 // 为了做到这一点,我们需要确保 bucket 指针已经更新了 // 首先我们在桶列表中找到指向要移动的单元格的指针的索引 let movingBucketIndex = FasterDictionary.reduce(this._valuesInfo[this._freeValueCellIndex].hashcode, this._buckets.length); // 如果找到了键,并且桶直接指向要删除的节点,现在必须指向要移动的单元格。 if (this._buckets[movingBucketIndex] - 1 == this._freeValueCellIndex) this._buckets[movingBucketIndex] = (indexToValueToRemove + 1); // 否则意味着有多个键具有相同的哈希值(碰撞),所以我们需要更新链接列表和它的指针 let next = this._valuesInfo[this._freeValueCellIndex].next; let previous = this._valuesInfo[this._freeValueCellIndex].previous; // 现在它们指向最后一个值被移入的单元格 if (next != -1) this._valuesInfo[next].previous = indexToValueToRemove; if (previous != -1) this._valuesInfo[previous].next = indexToValueToRemove; // 最后,实际上是移动值 this._valuesInfo[indexToValueToRemove] = this._valuesInfo[this._freeValueCellIndex]; this._values[indexToValueToRemove] = this._values[this._freeValueCellIndex]; } return true; } public trim(){ let expandPrime = HashHelpers.expandPrime(this._freeValueCellIndex); if (expandPrime < this._valuesInfo.length){ this._values.length = expandPrime; this._valuesInfo.length = expandPrime; } } public clear(){ if (this._freeValueCellIndex == 0) return; this._freeValueCellIndex = 0; this._buckets.length = 0; this._values.length = 0; this._valuesInfo.length = 0; } public fastClear(){ if (this._freeValueCellIndex == 0) return; this._freeValueCellIndex = 0; this._buckets.length = 0; this._valuesInfo.length = 0; } public containsKey(key: TKey){ if (this.tryFindIndex(key, {value: 0})){ return true; } return false; } public tryGetValue(key: TKey): TValue { let findIndex = {value: 0}; if (this.tryFindIndex(key, findIndex)){ return this._values[findIndex.value]; } return null; } public tryFindIndex(key: TKey, findIndex: {value: number}){ // 我把所有的索引都用偏移量+1来存储,这样在bucket list中0就意味着实际上不存在 // 当读取时,偏移量必须再偏移-1才是真实的 // 这样我就避免了将数组初始化为-1 let hash = FasterDictionary.hash(key); let bucketIndex = FasterDictionary.reduce(hash, this._buckets.length); let valueIndex = NumberExtension.toNumber(this._buckets[bucketIndex]) - 1; // 即使我们找到了一个现有的值,我们也需要确定它是我们所要求的值 while (valueIndex != -1){ if (this._valuesInfo[valueIndex].hashcode == hash && this._valuesInfo[valueIndex].key == key){ findIndex.value = valueIndex; return true; } valueIndex = this._valuesInfo[valueIndex].previous; } findIndex.value = 0; return false; } public getDirectValue(index: number): TValue { return this._values[index]; } public getIndex(key: TKey): number { let findIndex = {value: 0}; if (this.tryFindIndex(key, findIndex)) return findIndex.value; throw new Error("未找到key"); } public static updateLinkedList(index: number, valuesInfo: FastNode[]){ let next = valuesInfo[index].next; let previous = valuesInfo[index].previous; if (next != -1) valuesInfo[next].previous = previous; if (previous != -1) valuesInfo[previous].next = next; } public static hash(key) { return HashHelpers.getHashCode(key); } public static reduce(x: number, n: number) { if (x >= n) return x % n; return x; } } export class FastNode { readonly key; readonly hashcode: number; previous: number; next: number; constructor(key, hash: number, previousNode: number = -1) { this.key = key; this.hashcode = hash; this.previous = previousNode; this.next = -1; } } }
the_stack
import * as angular from 'angular'; import { PersonaSize } from './sizeEnum'; import { PlaceholderEnum } from './placeholderEnum'; import { PersonaStyleEnum } from '../../core/personaStyleEnum'; import { PresenceEnum } from '../../core/personaPresenceEnum'; /** * @ngdoc directive * @name uifPersonaCard * @module officeuifabric.components.personacard * * @restrict E * * @description * `<uif-persona-card>` is the personacard directive. * * @see {link http://dev.office.com/fabric/components/personacard} * * @usage * * <uif-persona-card uif-style="square" uif-size="small" uif-presence="dnd"> * <uif-persona-card-primary-text>Alton Lafferty</uif-persona-card-primary-text> * <uif-persona-card-secondary-text>Interior Designer, Contoso</uif-persona-card-secondary-text> * <uif-persona-card-tertiary-text>Office: 7/1234</uif-persona-card-tertiary-text> * <uif-persona-card-optional-text>Available - Video capable</uif-persona-card-optional-text> * <uif-persona-card-action uif-icon="video" uif-placeholder="regular"> * <uif-persona-card-detail-line> * <uif-persona-card-detail-label>Personal:</uif-persona-card-detail-label> 555.206.2443 * </uif-persona-card-detail-line> * <uif-persona-card-detail-line> * <uif-persona-card-detail-label>Work:</uif-persona-card-detail-label> 555.929.8240 * </uif-persona-card-detail-line> * </uif-persona-card-action> * <uif-persona-card-action uif-icon="org" uif-placeholder="overflow">View profile</uif-persona-card-action> * </uif-persona-card> * */ export class PersonaCardDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public require: string[] = ['uifPersonaCard']; public controller: any = PersonaCardController; public scope: {} = { 'uifImageUrl': '@', 'uifPresence': '@', 'uifSize': '@' }; public template: string = '<div class="ms-PersonaCard" ng-class="getPersonaCardClasses()">' + '<div class="ms-PersonaCard-persona">' + '<div class="ms-Persona" ng-class="getPersonaClasses()">' + '<div class="ms-Persona-imageArea">' + '<uif-icon uif-type="person"></uif-icon>' + '<img class="ms-Persona-image" ng-src="{{uifImageUrl}}" ng-if="uifImageUrl">' + '</div>' + '<div class="ms-Persona-presence"></div>' + '<div class="ms-Persona-details"></div>' + '</div>' + '</div>' + '<ul class="ms-PersonaCard-actions">' + '<li ng-repeat="action in personaCardActions" ng-class="getActionClasses(action)" ng-click="selectAction($event, action)">' + '<uif-icon uif-type={{action.icon}} ng-if="action.placeholder != \'overflow\'"></uif-icon>' + '</li>' + '</ul>' + '<div class="ms-PersonaCard-actionDetailBox">' + '<ul ng-class="detailClass"></ul>' + '</div>' + '</div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PersonaCardDirective(); return directive; } public link: angular.IDirectiveLinkFn = ( scope: IPersonaCardScope, element: angular.IAugmentedJQuery, attrs: IPersonaCardAttributes, controllers: any, transclude: angular.ITranscludeFunction): void => { let personaCardController: PersonaCardController = controllers[0]; // add class to icon in image area let icon: angular.IAugmentedJQuery = element.find('uif-icon'); icon.addClass('ms-Persona-placeholder'); // validate attributes if (angular.isDefined(attrs.uifSize) && angular.isUndefined(PersonaSize[attrs.uifSize])) { personaCardController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "' + attrs.uifSize + '" is not a valid value for uifSize. It should be xsmall, small, medium, large, xlarge.'); return; } if (angular.isDefined(attrs.uifStyle) && angular.isUndefined(PersonaStyleEnum[attrs.uifStyle])) { personaCardController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "' + attrs.uifStyle + '" is not a valid value for uifStyle. It should be round or square.'); return; } if (angular.isDefined(attrs.uifPresence) && angular.isUndefined(PresenceEnum[attrs.uifPresence])) { personaCardController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "' + attrs.uifPresence + '" is not a valid value for uifPresence. It should be available, away, blocked, busy, dnd or offline.'); return; } // determine CSS for action elements scope.getActionClasses = (action: PersonaCardAction) => { let actionClasses: string[] = []; let placeholder: number = PlaceholderEnum[action.placeholder]; switch (placeholder) { case PlaceholderEnum.topright: actionClasses.push('ms-PersonaCard-action'); actionClasses.push('ms-PersonaCard-orgChart'); break; case PlaceholderEnum.regular: actionClasses.push('ms-PersonaCard-action'); break; default: break; } if (action.isActive) { actionClasses.push('is-active'); } return actionClasses.join(' '); }; // determines CSS for main persona component scope.getPersonaClasses = () => { let personaClasses: string[] = []; if (PersonaStyleEnum[attrs.uifStyle] === PersonaStyleEnum.square) { personaClasses.push('ms-Persona--square'); } // size CSS switch (PersonaSize[attrs.uifSize]) { case PersonaSize.xsmall: personaClasses.push('ms-Persona--xs'); break; case PersonaSize.small: personaClasses.push('ms-Persona--sm'); break; case PersonaSize.large: personaClasses.push('ms-Persona--lg'); break; case PersonaSize.xlarge: personaClasses.push('ms-Persona--xl'); break; default: // no css needed for medium break; } // presence CSS switch (PresenceEnum[attrs.uifPresence]) { case PresenceEnum.available: personaClasses.push('ms-Persona--available'); break; case PresenceEnum.away: personaClasses.push('ms-Persona--away'); break; case PresenceEnum.blocked: personaClasses.push('ms-Persona--blocked'); break; case PresenceEnum.busy: personaClasses.push('ms-Persona--busy'); break; case PresenceEnum.dnd: personaClasses.push('ms-Persona--dnd'); break; default: personaClasses.push('ms-Persona--offline'); break; } return personaClasses.join(' '); }; // get CSS for persona card component scope.getPersonaCardClasses = () => { return PersonaStyleEnum[attrs.uifStyle] === PersonaStyleEnum.square ? 'ms-PersonaCard--square' : ''; }; // move transcluded elements around transclude((clone: angular.IAugmentedJQuery) => { let detailsWrapper: angular.IAugmentedJQuery = angular.element(element[0].getElementsByClassName('ms-Persona-details')); let actionDetailsBoxList: JQuery = angular.element(element[0].getElementsByClassName('ms-PersonaCard-actionDetailBox')) .find('ul').eq(0); let actionsList: JQuery = angular.element(element[0].getElementsByClassName('ms-PersonaCard-actions')); for (let i: number = 0; i < clone.length; i++) { let tagName: string = clone[i].tagName; switch (tagName) { // text directives go to persona details case 'UIF-PERSONA-CARD-PRIMARY-TEXT': case 'UIF-PERSONA-CARD-SECONDARY-TEXT': case 'UIF-PERSONA-CARD-TERTIARY-TEXT': case 'UIF-PERSONA-CARD-OPTIONAL-TEXT': detailsWrapper.append(clone[i]); break; // actions go to action lists, depending on the placeholder case 'UIF-PERSONA-CARD-ACTION': let wrappedAction: angular.IAugmentedJQuery = angular.element(clone[i]); let placeholder: string = wrappedAction.attr('uif-placeholder'); // overflow goes to ms-PersonaCard-actions if (PlaceholderEnum[placeholder] === PlaceholderEnum.overflow) { actionsList.append(wrappedAction); } else { actionDetailsBoxList.append(this.processAction(wrappedAction, scope, personaCardController)); } break; default: break; } } }); } /** * Ensures that proper CSS is attached to the action node and registers action in the controller for renderiangular. */ private processAction( clone: angular.IAugmentedJQuery, scope: IPersonaCardScope, personaCardController: PersonaCardController): angular.IAugmentedJQuery { let classToAdd: string = ''; let placeholder: string = clone.attr('uif-placeholder'); let icon: string = clone.attr('uif-icon'); let actionToAdd: PersonaCardAction = new PersonaCardAction(icon, placeholder); switch (placeholder) { case PlaceholderEnum[PlaceholderEnum.regular]: classToAdd = 'detail-' + (++scope.regularActionsCount); break; case PlaceholderEnum[PlaceholderEnum.topright]: classToAdd = 'detail-5'; break; default: break; } // applying classes directly to the list element clone.find('li').eq(0).addClass(classToAdd); actionToAdd.detailClass = classToAdd; personaCardController.addAction(actionToAdd); return clone; } } /** * @ngdoc controller * @name PersonaCardController * @module officeuifabric.components.personacard * * @description * Controller used for the `<uif-persona-card>` directive. * Main focus is around handling click events on the directive actions. */ export class PersonaCardController { public static $inject: string[] = ['$log', '$scope']; private detailCss: { [index: number]: string } = { 1: 'Chat', 2: 'Phone', 3: 'Video', 4: 'Mail', 5: 'Org' }; constructor(public $log: angular.ILogService, public $scope: IPersonaCardScope) { $scope.personaCardActions = new Array<PersonaCardAction>(); $scope.regularActionsCount = 0; $scope.detailClass = 'ms-PersonaCard-detailChat'; // handle click on the action $scope.selectAction = ($event: MouseEvent, action: PersonaCardAction): void => { $scope.personaCardActions.forEach((value: PersonaCardAction) => { value.isActive = false; }); action.isActive = true; let detailNumber: number = +(action.detailClass.charAt(action.detailClass.length - 1)); $scope.detailClass = 'ms-PersonaCard-detail' + this.detailCss[detailNumber]; }; } /** * Registers the actionin the controller for renderiangular. * Makes sure that first added action is active. */ public addAction(actionToAdd: PersonaCardAction): void { // make first action active if (this.$scope.personaCardActions.length === 0) { actionToAdd.isActive = true; } this.$scope.personaCardActions.push(actionToAdd); } } /** * @ngdoc interface * @name IPersonaCardAttributes * @module officeuifabric.components.personacard * * @description * Attributes used by the directive * * @property {string} uifSize Determines the size of the component * @property {string} uifStyle Determines round or square size of the component * @property {string} uifPresence Indicates presence of the associated user */ export interface IPersonaCardAttributes extends angular.IAttributes { uifSize: string; uifStyle: string; uifPresence: string; } /** * @ngdoc interface * @name IPersonaCardScope * @module officeuifabric.components.personacard * * @description * Scope used by the persona card directive. * * @property {string} uifPresence Indicates presence of the associated user * @property {string} uifSize Size of the persona card component * @property {string} uifImageUrl User image URL * @property {number} regularActionsCount Number of regular actions on the persona card for generating proper CSS * @property {function} getPersonaCardClasses Gets CSS classes for persona card based on type * @property {function} getPersonaClasses Gets CSS classes for persona component based on type, size and presence * @property {function} getActionClasses Gets CSS classes for action elements rendered on the persona card * @property {string} detailClass CSS class name indicating current action being selected * @property {function} selectAction Select proper action when action element is clicked * @property {collection} personaCardActions Actions rendered for regular and topright placeholder */ export interface IPersonaCardScope extends angular.IScope { uifPresence: string; uifSize: string; uifImageUrl: string; regularActionsCount: number; getPersonaCardClasses: () => string; getPersonaClasses: () => string; getActionClasses: (action: PersonaCardAction) => string; detailClass: string; selectAction: ($event: MouseEvent, selectedAction: PersonaCardAction) => void; personaCardActions: PersonaCardAction[]; } /** * @ngdoc object * @name PersonaCardAction * @module officeuifabric.components.personacard * * @description * Helper class used for rendering action buttons for regular and topright placeholder. * * @property {string} icon Icon used by particular action * @property {string} placeholder Placeholder where action belongs to * @property {boolean} isActive True if the action was clicked and is considered current * @property {string} detailClass Name of the CSS class that should be applied to list element */ class PersonaCardAction { public isActive: boolean; public detailClass: string; constructor( public icon: string, public placeholder: string) { } } /** * @ngdoc directive * @name uifPersonaCardText * @module officeuifabric.components.personacard * @restrict E * * @description * `<uif-persona-card-text>` directive is used to render information about associated user. * This directive class is used to provide functionality for multiple text directives: * - uif-persona-card-text-primary * - uif-persona-card-text-secondary * - uif-persona-card-text-tertiary * - uif-persona-card-text-optional * Type of directive is determined by the parameter injected into the factory method: * * <pre> * .directive('uifPersonaCardTertiaryText', PersonaCardTextDirective.factory('tertiary')) * .directive('uifPersonaCardOptionalText', PersonaCardTextDirective.factory('')); * </pre> */ export class PersonaCardTextDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public scope: boolean = false; private availableClasses: { [directiveType: string]: string } = { 'optional': 'ms-Persona-optionalText', 'primary': 'ms-Persona-primaryText', 'secondary': 'ms-Persona-secondaryText', 'tertiary': 'ms-Persona-tertiaryText' }; public static factory(type: string): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PersonaCardTextDirective(type); return directive; } // template based on the passed type public template: any = ($element: angular.IAugmentedJQuery, $attrs: any) => { let directiveTemplate: string = '<div class="' + this.availableClasses[this.directiveType] + '" ng-transclude></div>'; return directiveTemplate; } public constructor(private directiveType: string) { if (angular.isUndefined(this.availableClasses[this.directiveType])) { this.directiveType = 'optional'; } } } /** * @ngdoc directive * @name uifPersonaCardAction * @module officeuifabric.components.personacard * @restrict E * * @description * `<uif-persona-card-action>` is used to render the actions for the persona card. * Action can define icon that is used to render and placehodler where it should be placed: * - in the top-right corner of persona (topright) * - in the action bar below persona with icon (regular) * - in the right of the action bar below persona (overflow) * * @usage * * <uif-persona-card uif-style="square" uif-size="small" uif-presence="dnd"> * <uif-persona-card-action uif-icon="video" uif-placeholder="regular">Video capable</uif-persona-card-action> * <uif-persona-card-action uif-icon="org" uif-placeholder="topright">Org chart</uif-persona-card-action> * <uif-persona-card-action uif-placeholder="overflow">View profile</uif-persona-card-action> * </uif-persona-card> */ export class PersonaCardActionDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = false; public require: string = '^?uifPersonaCard'; public scope: boolean = false; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new PersonaCardActionDirective($log); directive.$inject = ['$log']; return directive; } constructor(private $log: angular.ILogService) { } public template: any = (instanceElement: angular.IAugmentedJQuery, actionAttrs: IPersonaCardActionAttributes) => { if (angular.isDefined(actionAttrs.uifPlaceholder) && angular.isUndefined(PlaceholderEnum[actionAttrs.uifPlaceholder])) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - ' + '"' + actionAttrs.uifPlaceholder + '" is not a valid value for uifPlaceholder. It should be regular, topright or overflow.'); return ''; } if (PlaceholderEnum[actionAttrs.uifPlaceholder] === PlaceholderEnum.overflow) { return '<li class="ms-PersonaCard-overflow" ng-transclude></li>'; } return '<li class="ms-PersonaCard-actionDetails" ng-transclude></li>'; } } /** * @ngdoc interface * @name IPersonaCardActionAttributes * @module officeuifabric.components.personacard * * @description * Attributes used by `<uif-persona-card-action>`. * * @property {string} uifIcon Icon to be used for associated action * @property {string} uifPlaceholder Indicated where the action should be rendered */ export interface IPersonaCardActionAttributes extends angular.IAttributes { uifIcon: string; uifPlaceholder: string; } /** * @ngdoc directive * @name uifPersonaCardDetailLabel * @module officeuifabric.components.personacard * @restrict E * * @description * `<uif-persona-card-detail-label>` is intended to render labels within action details * * @usage * * <uif-persona-card uif-style="round" uif-size="xlarge" uif-presence="away"> * <uif-persona-card-action uif-icon="chat" uif-placeholder="regular"> * <uif-persona-card-detail-line> * <uif-persona-card-detail-label>Lync:</uif-persona-card-detail-label> <uif-link ng-href="#">Start Lync call</uif-link> * </uif-persona-card-detail-line> * </uif-persona-card-action> * </uif-persona-card> */ export class PersonaCardDetailLabelDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public scope: boolean = false; public template: string = '<span class="ms-PersonaCard-detailLabel" ng-transclude></span>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PersonaCardDetailLabelDirective(); return directive; } } /** * @ngdoc directive * @name uifPersonaCardDetailLine * @module officeuifabric.components.personacard * @restrict E * * @description * `<uif-persona-card-detail-line>` is rendering details of the action within the action container * * @usage * * <uif-persona-card uif-style="round" uif-size="xlarge" uif-presence="away"> * <uif-persona-card-action uif-icon="chat" uif-placeholder="regular"> * <uif-persona-card-detail-line> * <uif-link ng-href="#">Start Lync call</uif-link> * </uif-persona-card-detail-line> * </uif-persona-card-action> * </uif-persona-card> */ export class PersonaCardDetailLineDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public scope: boolean = false; public template: string = '<div class="ms-PersonaCard-detailLine" ng-transclude></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PersonaCardDetailLineDirective(); return directive; } } /** * @ngdoc module * @name officeuifabric.components.personacard * * @description * PersonaCard */ export let module: angular.IModule = angular.module('officeuifabric.components.personacard', ['officeuifabric.components']) .directive('uifPersonaCard', PersonaCardDirective.factory()) .directive('uifPersonaCardAction', PersonaCardActionDirective.factory()) .directive('uifPersonaCardDetailLabel', PersonaCardDetailLabelDirective.factory()) .directive('uifPersonaCardDetailLine', PersonaCardDetailLineDirective.factory()) .directive('uifPersonaCardPrimaryText', PersonaCardTextDirective.factory('primary')) .directive('uifPersonaCardSecondaryText', PersonaCardTextDirective.factory('secondary')) .directive('uifPersonaCardTertiaryText', PersonaCardTextDirective.factory('tertiary')) .directive('uifPersonaCardOptionalText', PersonaCardTextDirective.factory(''));
the_stack
* @group integration/deposit */ import { createLightDidFromSeed, createOnChainDidFromSeed, DemoKeystore, DidChain, FullDidDetails, SigningAlgorithms, } from '@kiltprotocol/did' import { IRequestForAttestation, KeyRelationship, KeyringPair, KeystoreSigner, SubmittableExtrinsic, } from '@kiltprotocol/types' import { DecoderUtils, Keyring } from '@kiltprotocol/utils' import { BlockchainUtils } from '@kiltprotocol/chain-helpers' import { mnemonicGenerate, randomAsHex } from '@polkadot/util-crypto' import { BN } from '@polkadot/util' import { createMinimalFullDidFromLightDid, WS_ADDRESS, devFaucet, DriversLicense, endowAccounts, CtypeOnChain, } from './utils' import { Balance } from '../balance' import { Attestation } from '../attestation/Attestation' import { Claim } from '../claim/Claim' import { RequestForAttestation } from '../requestforattestation/RequestForAttestation' import { disconnect, init } from '../kilt' import { queryRaw } from '../attestation/Attestation.chain' let tx: SubmittableExtrinsic let authorizedTx: SubmittableExtrinsic let attestation: Attestation let storedEndpointsCount: number async function checkDeleteFullDid( identity: KeyringPair, fullDid: FullDidDetails, keystore: DemoKeystore ): Promise<boolean> { storedEndpointsCount = await DidChain.queryEndpointsCounts(fullDid.did) const deleteDid = await DidChain.getDeleteDidExtrinsic(storedEndpointsCount) const refreshedTxIndex = await fullDid.refreshTxIndex() tx = await DidChain.generateDidAuthenticatedTx({ didIdentifier: identity.address, txCounter: refreshedTxIndex.getNextTxIndex(), call: deleteDid, signer: keystore as KeystoreSigner<string>, signingPublicKey: fullDid.getKeys(KeyRelationship.authentication)[0] .publicKeyHex, alg: fullDid.getKeys(KeyRelationship.authentication)[0].type, submitter: identity.address, }) const balanceBeforeDeleting = await Balance.getBalances(identity.address) const didResult = await DidChain.queryDidEncoded(identity.address) DecoderUtils.assertCodecIsType(didResult, ['Option<DidDidDetails>']) const didDeposit = didResult.isSome ? didResult.unwrap().deposit.amount.toBn() : new BN(0) await BlockchainUtils.signAndSubmitTx(tx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const balanceAfterDeleting = await Balance.getBalances(identity.address) return balanceBeforeDeleting.reserved .sub(didDeposit) .eq(balanceAfterDeleting.reserved) } async function checkReclaimFullDid( identity: KeyringPair, fullDid: FullDidDetails ): Promise<boolean> { storedEndpointsCount = await DidChain.queryEndpointsCounts(fullDid.did) tx = await DidChain.getReclaimDepositExtrinsic( identity.address, storedEndpointsCount ) const balanceBeforeRevoking = await Balance.getBalances(identity.address) const didResult = await DidChain.queryDidEncoded(identity.address) DecoderUtils.assertCodecIsType(didResult, ['Option<DidDidDetails>']) const didDeposit = didResult.isSome ? didResult.unwrap().deposit.amount.toBn() : new BN(0) await BlockchainUtils.signAndSubmitTx(tx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const balanceAfterRevoking = await Balance.getBalances(identity.address) return balanceBeforeRevoking.reserved .sub(didDeposit) .eq(balanceAfterRevoking.reserved) } async function checkRemoveFullDidAttestation( identity: KeyringPair, fullDid: FullDidDetails, keystore: DemoKeystore, requestForAttestation: IRequestForAttestation ): Promise<boolean> { attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) tx = await attestation.store() authorizedTx = await fullDid.authorizeExtrinsic( tx, keystore, identity.address ) await BlockchainUtils.signAndSubmitTx(authorizedTx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const attestationResult = await queryRaw(attestation.claimHash) DecoderUtils.assertCodecIsType(attestationResult, [ 'Option<AttestationAttestationsAttestationDetails>', ]) const attestationDeposit = attestationResult.isSome ? attestationResult.unwrap().deposit.amount.toBn() : new BN(0) const balanceBeforeRemoving = await Balance.getBalances(identity.address) attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) tx = await attestation.remove(0) authorizedTx = await fullDid.authorizeExtrinsic( tx, keystore, identity.address ) await BlockchainUtils.signAndSubmitTx(authorizedTx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const balanceAfterRemoving = await Balance.getBalances(identity.address) return balanceBeforeRemoving.reserved .sub(attestationDeposit) .eq(balanceAfterRemoving.reserved) } async function checkReclaimFullDidAttestation( identity: KeyringPair, fullDid: FullDidDetails, keystore: DemoKeystore, requestForAttestation: IRequestForAttestation ): Promise<boolean> { attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) tx = await attestation.store() authorizedTx = await fullDid.authorizeExtrinsic( tx, keystore, identity.address ) await BlockchainUtils.signAndSubmitTx(authorizedTx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const balanceBeforeReclaiming = await Balance.getBalances(identity.address) attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) tx = await attestation.reclaimDeposit() const attestationResult = await queryRaw(attestation.claimHash) DecoderUtils.assertCodecIsType(attestationResult, [ 'Option<AttestationAttestationsAttestationDetails>', ]) const attestationDeposit = attestationResult.isSome ? attestationResult.unwrap().deposit.amount.toBn() : new BN(0) await BlockchainUtils.signAndSubmitTx(tx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) const balanceAfterDeleting = await Balance.getBalances(identity.address) return balanceBeforeReclaiming.reserved .sub(attestationDeposit) .eq(balanceAfterDeleting.reserved) } async function checkDeletedDidReclaimAttestation( identity: KeyringPair, fullDid: FullDidDetails, keystore: DemoKeystore, requestForAttestation: IRequestForAttestation ): Promise<void> { attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) tx = await attestation.store() authorizedTx = await fullDid.authorizeExtrinsic( tx, keystore, identity.address ) await BlockchainUtils.signAndSubmitTx(authorizedTx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) storedEndpointsCount = await DidChain.queryEndpointsCounts(fullDid.did) attestation = Attestation.fromRequestAndDid( requestForAttestation, fullDid.did ) const deleteDid = await DidChain.getDeleteDidExtrinsic(storedEndpointsCount) const refreshedTxIndex = await fullDid.refreshTxIndex() tx = await DidChain.generateDidAuthenticatedTx({ didIdentifier: identity.address, txCounter: refreshedTxIndex.getNextTxIndex(), call: deleteDid, signer: keystore as KeystoreSigner<string>, signingPublicKey: fullDid.getKeys(KeyRelationship.authentication)[0] .publicKeyHex, alg: fullDid.getKeys(KeyRelationship.authentication)[0].type, submitter: identity.address, }) await BlockchainUtils.signAndSubmitTx(tx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) tx = await attestation.reclaimDeposit() await BlockchainUtils.signAndSubmitTx(tx, identity, { resolveOn: BlockchainUtils.IS_FINALIZED, }) } const testIdentities: KeyringPair[] = [] const testMnemonics: string[] = [] const keystore = new DemoKeystore() let requestForAttestation: RequestForAttestation beforeAll(async () => { /* Initialize KILT SDK and set up node endpoint */ await init({ address: WS_ADDRESS }) const keyring: Keyring = new Keyring({ ss58Format: 38, type: 'sr25519' }) for (let i = 0; i < 9; i += 1) { testMnemonics.push(mnemonicGenerate()) } /* Generating all the identities from the keyring */ testMnemonics.forEach((val) => testIdentities.push(keyring.addFromMnemonic(val, undefined, 'sr25519')) ) // Sending tokens to all accounts const testAddresses = testIdentities.map((val) => val.address) await endowAccounts(devFaucet, testAddresses) // Create the group of mnemonics for the script const claimerMnemonic = mnemonicGenerate() /* Generating the claimerLightDid and testOneLightDid from the demo keystore with the generated seed both with sr25519 */ const claimerLightDid = await createLightDidFromSeed( keystore, claimerMnemonic ) const attester = await createOnChainDidFromSeed( devFaucet, keystore, randomAsHex() ) const ctypeExists = await CtypeOnChain(DriversLicense) if (!ctypeExists) { await attester .authorizeExtrinsic( await DriversLicense.store(), keystore, devFaucet.address ) .then((val) => BlockchainUtils.signAndSubmitTx(val, devFaucet, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) } const rawClaim = { name: 'claimer', age: 69, } const claim = Claim.fromCTypeAndClaimContents( DriversLicense, rawClaim, claimerLightDid.did ) requestForAttestation = RequestForAttestation.fromClaim(claim) await requestForAttestation.signWithDid(keystore, claimerLightDid) }, 120_000) describe('Different deposits scenarios', () => { let testFullDidOne: FullDidDetails let testFullDidTwo: FullDidDetails let testFullDidThree: FullDidDetails let testFullDidFour: FullDidDetails let testFullDidFive: FullDidDetails let testFullDidSix: FullDidDetails let testFullDidSeven: FullDidDetails let testFullDidEight: FullDidDetails let testFullDidNine: FullDidDetails beforeAll(async () => { const [testDidFive, testDidSix, testDidSeven, testDidEight, testDidNine] = await Promise.all([ createLightDidFromSeed( keystore, testMnemonics[4], SigningAlgorithms.Sr25519 ), createLightDidFromSeed( keystore, testMnemonics[5], SigningAlgorithms.Sr25519 ), createLightDidFromSeed( keystore, testMnemonics[6], SigningAlgorithms.Sr25519 ), createLightDidFromSeed( keystore, testMnemonics[7], SigningAlgorithms.Sr25519 ), createLightDidFromSeed( keystore, testMnemonics[8], SigningAlgorithms.Sr25519 ), ]) ;[ testFullDidOne, testFullDidTwo, testFullDidThree, testFullDidFour, testFullDidFive, testFullDidSix, testFullDidSeven, testFullDidEight, testFullDidNine, ] = await Promise.all([ createOnChainDidFromSeed( testIdentities[0], keystore, testMnemonics[0], SigningAlgorithms.Sr25519 ), createOnChainDidFromSeed( testIdentities[1], keystore, testMnemonics[1], SigningAlgorithms.Sr25519 ), createOnChainDidFromSeed( testIdentities[2], keystore, testMnemonics[2], SigningAlgorithms.Sr25519 ), createOnChainDidFromSeed( testIdentities[3], keystore, testMnemonics[3], SigningAlgorithms.Sr25519 ), createMinimalFullDidFromLightDid( testIdentities[4], testDidFive, keystore ), createMinimalFullDidFromLightDid(testIdentities[5], testDidSix, keystore), createMinimalFullDidFromLightDid( testIdentities[6], testDidSeven, keystore ), createMinimalFullDidFromLightDid( testIdentities[7], testDidEight, keystore ), createMinimalFullDidFromLightDid( testIdentities[8], testDidNine, keystore ), ]) }, 240_000) it('Check if deleting full DID returns deposit', async () => { await expect( checkDeleteFullDid(testIdentities[0], testFullDidOne, keystore) ).resolves.toBe(true) }, 45_000) it('Check if reclaiming full DID returns deposit', async () => { await expect( checkReclaimFullDid(testIdentities[1], testFullDidTwo) ).resolves.toBe(true) }, 45_000) it('Check if removing an attestation from a full DID returns deposit', async () => { await expect( checkRemoveFullDidAttestation( testIdentities[2], testFullDidThree, keystore, requestForAttestation ) ).resolves.toBe(true) }, 90_000) it('Check if reclaiming an attestation from a full DID returns the deposit', async () => { await expect( checkReclaimFullDidAttestation( testIdentities[3], testFullDidFour, keystore, requestForAttestation ) ).resolves.toBe(true) }, 90_000) it('Check if deleting from a migrated light DID to a full DID returns deposit', async () => { await expect( checkDeleteFullDid(testIdentities[4], testFullDidFive, keystore) ).resolves.toBe(true) }, 90_000) it('Check if reclaiming from a migrated light DID to a full DID returns deposit', async () => { await expect( checkReclaimFullDid(testIdentities[5], testFullDidSix) ).resolves.toBe(true) }, 90_000) it('Check if removing an attestation from a migrated light DID to a full DID returns the deposit', async () => { await expect( checkRemoveFullDidAttestation( testIdentities[6], testFullDidSeven, keystore, requestForAttestation ) ).resolves.toBe(true) }, 90_000) it('Check if reclaiming an attestation from a migrated light DID to a full DID returns the deposit', async () => { await expect( checkReclaimFullDidAttestation( testIdentities[7], testFullDidEight, keystore, requestForAttestation ) ).resolves.toBe(true) }, 90_000) it('Check if deleting a full DID and reclaiming an attestation returns the deposit', async () => { await expect( checkDeletedDidReclaimAttestation( testIdentities[8], testFullDidNine, keystore, requestForAttestation ) ).resolves.not.toThrow() }, 120_000) }) afterAll(() => { disconnect() })
the_stack
declare module "notifme-sdk" { export type ChannelType = "email" | "sms" | "push" | "webpush" | "slack"; export type ProviderStrategyType = "fallback" | "roundrobin" | "no-fallback"; export default class NotifMeSdk { constructor(options: Options); send(notification: Notification): Promise<NotificationStatus>; } export type Options = { channels: { email?: Channel<EmailProvider>; sms?: Channel<SmsProvider>; push?: any; // TODO webpush?: any; // TODO slack?: Channel<SlackProvider>; }; useNotificationCatcher?: boolean; }; export type Notification = { metadata?: { id?: string; userId?: string; }; email?: EmailRequest; push?: PushRequest; sms?: SmsRequest; webpush?: WebpushRequest; slack?: SlackRequest; }; export type NotificationStatus = { status: "success" | "error"; channels?: { [channel in ChannelType]: { id: string; providerId?: string; }; }; errors?: { [channel in ChannelType]: Error }; info?: Object; }; export type Channel<T> = { multiProviderStrategy?: MultiProviderStrategy | ProviderStrategyType; providers: T[]; }; export type MultiProviderStrategy = (providers: Provider[]) => any; //region PROVIDERS export type EmailProvider = | { type: "logger"; } | { type: "custom"; id: string; send: (request: EmailRequest) => Promise<string>; } | { // Doc: https://nodemailer.com/transports/sendmail/ type: "sendmail"; sendmail: true; path: string; // Defaults to 'sendmail' newline: "windows" | "unix"; // Defaults to 'unix' args?: string[]; attachDataUrls?: boolean; disableFileAccess?: boolean; disableUrlAccess?: boolean; } | { // General options (Doc: https://nodemailer.com/smtp/) type: "smtp"; port?: 25 | 465 | 587; // Defaults to 587 host?: string; // Defaults to 'localhost' auth: | { type?: "login"; user: string; pass: string; } | { type: "oauth2"; // Doc: https://nodemailer.com/smtp/oauth2/#oauth-3lo user: string; clientId?: string; clientSecret?: string; refreshToken?: string; accessToken?: string; expires?: string; accessUrl?: string; } | { type: "oauth2"; // Doc: https://nodemailer.com/smtp/oauth2/#oauth-2lo user: string; serviceClient: string; privateKey?: string; }; authMethod?: string; // Defaults to 'PLAIN' // TLS options (Doc: https://nodemailer.com/smtp/#tls-options) secure?: boolean; tls?: Object; // Doc: https://nodejs.org/api/tls.html#tls_class_tls_tlssocket ignoreTLS?: boolean; requireTLS?: boolean; // Connection options (Doc: https://nodemailer.com/smtp/#connection-options) name?: string; localAddress?: string; connectionTimeout?: number; greetingTimeout?: number; socketTimeout?: number; // Debug options (Doc: https://nodemailer.com/smtp/#debug-options) logger?: boolean; debug?: boolean; // Security options (Doc: https://nodemailer.com/smtp/#security-options) disableFileAccess?: boolean; disableUrlAccess?: boolean; // Pooling options (Doc: https://nodemailer.com/smtp/pooled/) pool?: boolean; maxConnections?: number; maxMessages?: number; rateDelta?: number; rateLimit?: number; // Proxy options (Doc: https://nodemailer.com/smtp/proxies/) proxy?: string; } | { type: "mailgun"; apiKey: string; domainName: string; } | { type: "sendgrid"; apiKey: string; } | { type: "ses"; region: string; accessKeyId: string; secretAccessKey: string; sessionToken?: string; } | { type: "sparkpost"; apiKey: string; }; export type SmsProvider = | { type: "logger"; } | { type: "custom"; id: string; send: (request: SmsRequest) => Promise<string>; } | { type: "46elks"; apiUsername: string; apiPassword: string; } | { type: "callr"; login: string; password: string; } | { type: "clickatell"; apiKey: string; // One-way integration API key } | { type: "infobip"; username: string; password: string; } | { type: "nexmo"; apiKey: string; apiSecret: string; } | { type: "ovh"; appKey: string; appSecret: string; consumerKey: string; account: string; host: string; // https://github.com/ovh/node-ovh/blob/master/lib/endpoints.js } | { type: "plivo"; authId: string; authToken: string; } | { type: "twilio"; accountSid: string; authToken: string; }; export type PushProvider = | { type: "logger"; } | { type: "custom"; id: string; send: (request: PushRequest) => Promise<string>; } | { // Doc: https://github.com/node-apn/node-apn/blob/master/doc/provider.markdown type: "apn"; // Apple Push Notification token?: { key: string; keyId: string; teamId: string; }; cert?: string; key?: string; ca?: string[]; pfx?: string; passphrase?: string; production?: boolean; rejectUnauthorized?: boolean; connectionRetryLimit?: number; } | { // Doc: https://github.com/ToothlessGear/node-gcm type: "fcm"; // Firebase Cloud Messaging (previously called GCM, Google Cloud Messaging) id: string; phonegap?: boolean; } | { // Doc: https://github.com/tjanczuk/wns type: "wns"; // Windows Push Notification clientId: string; clientSecret: string; notificationMethod: string; // sendTileSquareBlock, sendTileSquareImage... } | { // Doc: https://github.com/umano/node-adm type: "adm"; // Amazon Device Messaging clientId: string; clientSecret: string; }; // TODO?: onesignal, urbanairship, goroost, sendpulse, wonderpush, appboy... export type WebpushProvider = | { type: "logger"; } | { type: "custom"; id: string; send: (request: WebpushRequest) => Promise<string>; } | { type: "gcm"; gcmAPIKey?: string; vapidDetails?: { subject: string; publicKey: string; privateKey: string; }; ttl?: number; headers?: { [key: string]: string | number | boolean }; }; export type SlackProvider = | { type: "logger"; } | { type: "custom"; id: string; send: (request: SlackRequest) => Promise<string>; } | { type: "webhook"; webhookUrl: string; }; export type Provider = | EmailProvider | SmsProvider | PushProvider | WebpushProvider | SlackProvider; //endregion PROVIDERS //region REQUEST TYPES: type RequestMetadata = { id?: string; userId?: string; }; export type EmailRequest = RequestMetadata & { from: string; to: string; subject: string; cc?: string[]; bcc?: string[]; replyTo?: string; text?: string; html?: string; attachments?: { contentType: string; // text/plain... filename: string; content: string | Buffer; // path?: string, // href?: string, // contentDisposition?: string, // contentTransferEncoding?: string, // cid?: string, // raw?: string, // encoding?: string, // headers?: {[string]: string | number | boolean} }[]; headers?: { [key: string]: string | number | boolean }; }; export type PushRequest = RequestMetadata & { registrationToken: string; title: string; body: string; custom?: Object; priority?: "high" | "normal"; // gcm, apn. Will be translated to 10 and 5 for apn. Defaults to 'high' collapseKey?: string; // gcm for android, used as collapseId in apn contentAvailable?: boolean; // gcm for android delayWhileIdle?: boolean; // gcm for android restrictedPackageName?: string; // gcm for android dryRun?: boolean; // gcm for android icon?: string; // gcm for android tag?: string; // gcm for android color?: string; // gcm for android clickAction?: string; // gcm for android. In ios, category will be used if not supplied locKey?: string; // gcm, apn bodyLocArgs?: string; // gcm, apn titleLocKey?: string; // gcm, apn titleLocArgs?: string; // gcm, apn retries?: number; // gcm, apn encoding?: string; // apn badge?: number; // gcm for ios, apn sound?: string; // gcm, apn alert?: string | Object; // apn, will take precedence over title and body launchImage?: string; // apn and gcm for ios action?: string; // apn and gcm for ios topic?: string; // apn and gcm for ios category?: string; // apn and gcm for ios mdm?: string; // apn and gcm for ios urlArgs?: string; // apn and gcm for ios truncateAtWordEnd?: boolean; // apn and gcm for ios mutableContent?: number; // apn expiry?: number; // seconds timeToLive?: number; // if both expiry and timeToLive are given, expiry will take precedency headers?: { [key: string]: string | number | boolean }; // wns launch?: string; // wns duration?: string; // wns consolidationKey?: string; // ADM }; export type SmsRequest = RequestMetadata & { from: string; to: string; text: string; type?: "text" | "unicode"; // Defaults to 'text' nature?: "marketing" | "transactional"; ttl?: number; messageClass?: 0 | 1 | 2 | 3; // 0 for Flash SMS, 1 - ME-specific, 2 - SIM / USIM specific, 3 - TE-specific // } & ( // {type?: 'text', text: string} // | {type: 'unicode', text: string} // | {type: 'binary', body: string, udh: string, protocolId: string} // | {type: 'wappush', title: string, url: string, validity?: number} // | {type: 'vcal', vcal: string} // | {type: 'vcard', vcard: string} // ) }; export type WebpushRequest = RequestMetadata & { subscription: { endpoint: string; keys: { auth: string; p256dh: string; }; }; title: string; // C22 F22 S6 body: string; // C22 F22 S6 actions?: { action: string; title: string; icon?: string; }[]; // C53 badge?: string; // C53 dir?: "auto" | "rtl" | "ltr"; // C22 F22 S6 icon?: string; // C22 F22 image?: string; // C55 F22 redirects?: { [key: string]: string }; // added for local tests requireInteraction?: boolean; // C22 F52 }; export type SlackRequest = RequestMetadata & { text: string; }; export type Request = EmailRequest | PushRequest | SmsRequest | WebpushRequest | SlackRequest; }
the_stack
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Add, ExpandMore, Replay, Shuffle, Update } from '@mui/icons-material'; import { Alert, Box, Button, ButtonGroup, CardContent, CardHeader, Collapse, Grid, MenuItem, Skeleton, Typography } from '@mui/material'; import React, { lazy, Suspense, useCallback, useContext, useEffect, useMemo, useReducer, useState } from 'react'; import { Trans, useTranslation } from 'react-i18next'; import ArtifactRarityDropdown from '../Components/Artifact/ArtifactRarityDropdown'; import ArtifactSetDropdown from '../Components/Artifact/ArtifactSetDropdown'; import ArtifactSlotDropdown from '../Components/Artifact/ArtifactSlotDropdown'; import BootstrapTooltip from '../Components/BootstrapTooltip'; import CardDark from '../Components/Card/CardDark'; import CardLight from '../Components/Card/CardLight'; import CustomNumberInput, { CustomNumberInputButtonGroupWrapper } from '../Components/CustomNumberInput'; import CustomNumberTextField from '../Components/CustomNumberTextField'; import DropdownButton from '../Components/DropdownMenu/DropdownButton'; import ExpandButton from '../Components/ExpandButton'; import ImgIcon from '../Components/Image/ImgIcon'; import SqBadge from '../Components/SqBadge'; import { DatabaseContext } from '../Database/Database'; import { parseArtifact, validateArtifact } from '../Database/validation'; import useForceUpdate from '../ReactHooks/useForceUpdate'; import usePromise from '../ReactHooks/usePromise'; import Stat from '../Stat'; import { allSubstats, IArtifact, ICachedArtifact, ISubstat, MainStatKey } from '../Types/artifact'; import { ArtifactRarity, ArtifactSetKey, SlotKey } from '../Types/consts'; import { randomizeArtifact } from '../Util/ArtifactUtil'; import { valueString } from '../Util/UIUtil'; import { clamp, deepClone } from '../Util/Util'; import Artifact from './Artifact'; import ArtifactCard from './ArtifactCard'; import { ArtifactSheet } from './ArtifactSheet'; import artifactSubstatRollCorrection from './artifact_sub_rolls_correction_gen.json'; import PercentBadge from './PercentBadge'; import TextButton from '../Components/TextButton'; const UploadDisplay = lazy(() => import('./UploadDisplay')) type ArtifactEditorArgument = { artifactIdToEdit: string, cancelEdit: () => void } const allSubstatFilter = new Set(allSubstats) let uploadDisplayReset: (() => void) | undefined export default function ArtifactEditor({ artifactIdToEdit, cancelEdit }: ArtifactEditorArgument) { const { t } = useTranslation("artifact") const artifactSheets = usePromise(ArtifactSheet.getAll(), []) const database = useContext(DatabaseContext) const [expanded, setExpanded] = useState(() => !database._getArts().length) const [dirtyDatabase, setDirtyDatabase] = useForceUpdate() useEffect(() => database.followAnyArt(setDirtyDatabase), [database, setDirtyDatabase]) const [editorArtifact, artifactDispatch] = useReducer(artifactReducer, undefined) const artifact = useMemo(() => editorArtifact && parseArtifact(editorArtifact), [editorArtifact]) const { old, oldType }: { old: ICachedArtifact | undefined, oldType: "edit" | "duplicate" | "upgrade" | "" } = useMemo(() => { const databaseArtifact = dirtyDatabase && database._getArt(artifactIdToEdit) if (databaseArtifact) return { old: databaseArtifact, oldType: "edit" } if (artifact === undefined) return { old: undefined, oldType: "" } const { duplicated, upgraded } = dirtyDatabase && database.findDuplicates(artifact) return { old: duplicated[0] ?? upgraded[0], oldType: duplicated.length !== 0 ? "duplicate" : "upgrade" } }, [artifact, artifactIdToEdit, database, dirtyDatabase]) const { artifact: cachedArtifact, errors } = useMemo(() => { if (!artifact) return { artifact: undefined, errors: [] as Displayable[] } const validated = validateArtifact(artifact, artifactIdToEdit) if (old) { validated.artifact.location = old.location validated.artifact.exclude = old.exclude } return validated }, [artifact, artifactIdToEdit, old]) // Overwriting using a different function from `databaseArtifact` because `useMemo` does not // guarantee to trigger *only when* dependencies change, which is necessary in this case. useEffect(() => { const databaseArtifact = dirtyDatabase && database._getArt(artifactIdToEdit) if (databaseArtifact) { setExpanded(true) artifactDispatch({ type: "overwrite", artifact: deepClone(databaseArtifact) }) } }, [artifactIdToEdit, database, dirtyDatabase]) const sheet = artifact ? artifactSheets?.[artifact.setKey] : undefined const getUpdloadDisplayReset = (reset: () => void) => uploadDisplayReset = reset const reset = useCallback(() => { cancelEdit?.(); uploadDisplayReset?.() artifactDispatch({ type: "reset" }) }, [cancelEdit, artifactDispatch]) const update = useCallback((newValue: Partial<IArtifact>) => { const newSheet = newValue.setKey ? artifactSheets![newValue.setKey] : sheet! function pick<T>(value: T | undefined, available: readonly T[], prefer?: T): T { return (value && available.includes(value)) ? value : (prefer ?? available[0]) } if (newValue.setKey) { newValue.rarity = pick(artifact?.rarity, newSheet.rarity, Math.max(...newSheet.rarity) as ArtifactRarity) newValue.slotKey = pick(artifact?.slotKey, newSheet.slots) } if (newValue.rarity) newValue.level = artifact?.level ?? 0 if (newValue.level) newValue.level = clamp(newValue.level, 0, 4 * (newValue.rarity ?? artifact!.rarity)) if (newValue.slotKey) newValue.mainStatKey = pick(artifact?.mainStatKey, Artifact.slotMainStats(newValue.slotKey)) if (newValue.mainStatKey) { newValue.substats = [0, 1, 2, 3].map(i => (artifact && artifact.substats[i].key !== newValue.mainStatKey) ? artifact!.substats[i] : { key: "", value: 0 }) } artifactDispatch({ type: "update", artifact: newValue }) }, [artifact, artifactSheets, sheet, artifactDispatch]) const setSubstat = useCallback((index: number, substat: ISubstat) => { artifactDispatch({ type: "substat", index, substat }) }, [artifactDispatch]) const isValid = !errors.length const canClearArtifact = (): boolean => window.confirm(t`editor.clearPrompt` as string) const { rarity = 5, level = 0, slotKey = "flower" } = artifact ?? {} const { currentEfficiency = 0, maxEfficiency = 0 } = cachedArtifact ? Artifact.getArtifactEfficiency(cachedArtifact, allSubstatFilter) : {} return <Suspense fallback={<Skeleton variant="rectangular" sx={{ width: "100%", height: expanded ? "100%" : 64 }} />}><CardDark > <CardHeader action={ <ExpandButton expand={expanded} onClick={() => setExpanded(!expanded)} aria-expanded={expanded} aria-label="show more" > <ExpandMore /> </ExpandButton> } title={<Trans t={t} i18nKey="editor.title" >Artifact Editor</Trans>} /> <Collapse in={expanded} timeout="auto" unmountOnExit><CardContent sx={{ pt: 0 }}> <Grid container spacing={1} sx={{ mb: 1 }}> {/* Left column */} <Grid item xs={12} md={6} lg={6} sx={{ // select all excluding last "> div:nth-last-of-type(n+2)": { mb: 1 } }}> {/* set & rarity */} <ButtonGroup sx={{ display: "flex", mb: 1 }}> {/* Artifact Set */} <ArtifactSetDropdown selectedSetKey={artifact?.setKey} onChange={setKey => update({ setKey: setKey as ArtifactSetKey })} sx={{ flexGrow: 1 }} /> {/* rarity dropdown */} <ArtifactRarityDropdown rarity={artifact ? rarity : undefined} onChange={r => update({ rarity: r })} filter={r => !!sheet?.rarity?.includes?.(r)} disabled={!sheet} /> </ButtonGroup> {/* level */} <Box component="div" display="flex"> <CustomNumberTextField id="filled-basic" label="Level" variant="filled" sx={{ flexShrink: 1, flexGrow: 1, mr: 1, my: 0 }} margin="dense" size="small" value={level} disabled={!sheet} placeholder={`0~${rarity * 4}`} onChange={l => update({ level: l })} /> <ButtonGroup > <Button onClick={() => update({ level: level - 1 })} disabled={!sheet || level === 0}>-</Button> {rarity ? [...Array(rarity + 1).keys()].map(i => 4 * i).map(i => <Button key={i} onClick={() => update({ level: i })} disabled={!sheet || level === i}>{i}</Button>) : null} <Button onClick={() => update({ level: level + 1 })} disabled={!sheet || level === (rarity * 4)}>+</Button> </ButtonGroup> </Box> {/* slot */} <Box component="div" display="flex"> <ArtifactSlotDropdown disabled={!sheet} slotKey={slotKey} onChange={slotKey => update({ slotKey })} /> <CardLight sx={{ p: 1, ml: 1, flexGrow: 1 }}> <Suspense fallback={<Skeleton width="60%" />}> <Typography color="text.secondary"> {sheet?.getSlotName(artifact!.slotKey) ? <span><ImgIcon src={sheet.slotIcons[artifact!.slotKey]} /> {sheet?.getSlotName(artifact!.slotKey)}</span> : t`editor.unknownPieceName`} </Typography> </Suspense> </CardLight> </Box> {/* main stat */} <Box component="div" display="flex"> <DropdownButton title={<b>{artifact ? Stat.getStatNameWithPercent(artifact.mainStatKey) : t`mainStat`}</b>} disabled={!sheet} color={artifact ? "success" : "primary"} > {Artifact.slotMainStats(slotKey).map(mainStatK => <MenuItem key={mainStatK} selected={artifact?.mainStatKey === mainStatK} disabled={artifact?.mainStatKey === mainStatK} onClick={() => update({ mainStatKey: mainStatK })} >{Stat.getStatNameWithPercent(mainStatK)}</MenuItem>)} </DropdownButton> <CardLight sx={{ p: 1, ml: 1, flexGrow: 1 }}> <Typography color="text.secondary"> {artifact ? `${valueString(Artifact.mainStatValue(artifact.mainStatKey, rarity, level), Stat.getStatUnit(artifact.mainStatKey))}${Stat.getStatUnit(artifact.mainStatKey)}` : t`mainStat`} </Typography> </CardLight> </Box> {/* Current/Max Substats Efficiency */} <SubstatEfficiencyDisplayCard valid={isValid} efficiency={currentEfficiency} t={t} /> {currentEfficiency !== maxEfficiency && <SubstatEfficiencyDisplayCard max valid={isValid} efficiency={maxEfficiency} t={t} />} </Grid> {/* Right column */} <Grid item xs={12} md={6} lg={6} sx={{ // select all excluding last "> div:nth-last-of-type(n+2)": { mb: 1 } }}> {/* substat selections */} {[0, 1, 2, 3].map((index) => <SubstatInput key={index} index={index} artifact={cachedArtifact} setSubstat={setSubstat} />)} </Grid> </Grid> {/* Duplicate/Updated/Edit UI */} {old && <Grid container sx={{ justifyContent: "space-around", my: 1 }} > <Grid item lg={4} md={6} > <Typography sx={{ textAlign: "center" }} variant="h6" color="text.secondary" >{t`editor.preview`}</Typography> <div><ArtifactCard artifactObj={cachedArtifact} /></div> </Grid> <Grid item lg={4} md={6} > <Typography sx={{ textAlign: "center" }} variant="h6" color="text.secondary" >{oldType !== "edit" ? (oldType === "duplicate" ? t`editor.dupArt` : t`editor.upArt`) : t`editor.beforeEdit`}</Typography> <div><ArtifactCard artifactObj={old} /></div> </Grid> </Grid>} {/* Image OCR */} <CardLight sx={{ mb: 1 }}> <CardContent> {/* TODO: artifactDispatch not overwrite */} <Suspense fallback={<Skeleton width="100%" height="100" />}> <UploadDisplay setState={state => artifactDispatch({ type: "overwrite", artifact: state })} setReset={getUpdloadDisplayReset} artifactInEditor={!!artifact} /> </Suspense> </CardContent> </CardLight> {/* Error alert */} {!isValid && <Alert variant="filled" severity="error" sx={{ mb: 1 }}>{errors.map((e, i) => <div key={i}>{e}</div>)}</Alert>} {/* Buttons */} <Grid container spacing={2}> <Grid item> {oldType === "edit" ? <Button startIcon={<Add />} onClick={() => { database.updateArt(editorArtifact!, old!.id); reset() }} disabled={!editorArtifact || !isValid} color="primary"> {t`editor.btnSave`} </Button> : <Button startIcon={<Add />} onClick={() => { database.createArt(artifact!); reset() }} disabled={!artifact || !isValid} color={oldType === "duplicate" ? "warning" : "primary"}> {t`editor.btnAdd`} </Button>} </Grid> <Grid item flexGrow={1}> <Button startIcon={<Replay />} disabled={!artifact} onClick={() => { canClearArtifact() && reset() }} color="error">{t`editor.btnClear`}</Button> </Grid> <Grid item> {process.env.NODE_ENV === "development" && <Button color="info" startIcon={<Shuffle />} onClick={async () => artifactDispatch({ type: "overwrite", artifact: await randomizeArtifact() })}>{t`editor.btnRandom`}</Button>} </Grid> {old && oldType !== "edit" && <Grid item> <Button startIcon={<Update />} onClick={() => { database.updateArt(editorArtifact!, old.id); reset() }} disabled={!editorArtifact || !isValid} color="success">{t`editor.btnUpdate`}</Button> </Grid>} </Grid> </CardContent></Collapse> </CardDark ></Suspense> } function SubstatEfficiencyDisplayCard({ efficiency, max = false, t, valid }) { const eff = max ? "maxSubEff" : "curSubEff" return <CardLight sx={{ py: 1, px: 2 }}> <Grid container spacing={1}> <Grid item>{t(`editor.${eff}`)}</Grid> <Grid item flexGrow={1}> <BootstrapTooltip placement="top" title={<span> <Typography variant="h6">{t(`editor.${eff}`)}</Typography> <Typography><Trans t={t} i18nKey={`editor.${eff}Desc`} /></Typography> </span>}> <span><Box component={FontAwesomeIcon} icon={faQuestionCircle} sx={{ cursor: "help" }} /></span> </BootstrapTooltip> </Grid> <Grid item xs="auto"> <PercentBadge valid={valid} value={valid ? efficiency : "ERR"} /> </Grid> </Grid> </CardLight> } function SubstatInput({ index, artifact, setSubstat }: { index: number, artifact: ICachedArtifact | undefined, setSubstat: (index: number, substat: ISubstat) => void, }) { const { t } = useTranslation("artifact") const { mainStatKey = "", rarity = 5 } = artifact ?? {} const { key = "", value = 0, rolls = [], efficiency = 0 } = artifact?.substats[index] ?? {} const accurateValue = rolls.reduce((a, b) => a + b, 0) const unit = Stat.getStatUnit(key), rollNum = rolls.length let error: string = "", rollData: readonly number[] = [], allowedRolls = 0 if (artifact) { // Account for the rolls it will need to fill all 4 substates, +1 for its base roll const rarity = artifact.rarity const { numUpgrades, high } = Artifact.rollInfo(rarity) const maxRollNum = numUpgrades + high - 3; allowedRolls = maxRollNum - rollNum rollData = key ? Artifact.getSubstatRollData(key, rarity) : [] } const rollOffset = 7 - rollData.length if (!rollNum && key && value) error = error || t`editor.substat.error.noCalc` if (allowedRolls < 0) error = error || t("editor.substat.error.noOverRoll", { value: allowedRolls + rollNum }) return <CardLight> <Box sx={{ display: "flex" }}> <ButtonGroup size="small" sx={{ width: "100%", display: "flex" }}> <DropdownButton title={key ? Stat.getStatNameWithPercent(key) : t('editor.substat.substatFormat', { value: index + 1 })} disabled={!artifact} color={key ? "success" : "primary"} sx={{ whiteSpace: "nowrap" }}> {key && <MenuItem onClick={() => setSubstat(index, { key: "", value: 0 })}>{t`editor.substat.noSubstat`}</MenuItem>} {allSubstats.filter(key => mainStatKey !== key) .map(k => <MenuItem key={k} selected={key === k} disabled={key === k} onClick={() => setSubstat(index, { key: k, value: 0 })} > {Stat.getStatNameWithPercent(k)} </MenuItem>)} </DropdownButton> <CustomNumberInputButtonGroupWrapper sx={{ flexBasis: 30, flexGrow: 1 }} > <CustomNumberInput float={unit === "%"} placeholder={t`editor.substat.selectSub`} value={key ? value : undefined} onChange={value => setSubstat(index, { key, value: value ?? 0 })} disabled={!key} error={!!error} sx={{ px: 1, }} inputProps={{ sx: { textAlign: "right" } }} /> </CustomNumberInputButtonGroupWrapper> {!!rollData.length && <TextButton>{t`editor.substat.nextRolls`}</TextButton>} {rollData.map((v, i) => { let newValue = valueString(accurateValue + v, unit) newValue = artifactSubstatRollCorrection[rarity]?.[key]?.[newValue] ?? newValue return <Button key={i} color={`roll${clamp(rollOffset + i, 1, 6)}` as any} disabled={(value && !rollNum) || allowedRolls <= 0} onClick={() => setSubstat(index, { key, value: parseFloat(newValue) })}>{newValue}</Button> })} </ButtonGroup> </Box> <Box sx={{ p: 1, }}> {error ? <SqBadge color="error">{t`ui:error`}</SqBadge> : <Grid container> <Grid item> <SqBadge color={rollNum === 0 ? "secondary" : `roll${clamp(rollNum, 1, 6)}`}> {rollNum ? t("editor.substat.RollCount", { count: rollNum }) : t`editor.substat.noRoll`} </SqBadge> </Grid> <Grid item flexGrow={1}> {!!rolls.length && [...rolls].sort().map((val, i) => <Typography component="span" key={i} color={`roll${clamp(rollOffset + rollData.indexOf(val), 1, 6)}.main`} sx={{ ml: 1 }} >{valueString(val, unit)}</Typography>)} </Grid> <Grid item xs="auto" flexShrink={1}> <Typography> <Trans t={t} i18nKey="editor.substat.eff" color="text.secondary"> Efficiency: <PercentBadge valid={true} value={efficiency ? efficiency : t`editor.substat.noStat` as string} /> </Trans> </Typography> </Grid> </Grid>} </Box> </CardLight > } type ResetMessage = { type: "reset" } type SubstatMessage = { type: "substat", index: number, substat: ISubstat } type OverwriteMessage = { type: "overwrite", artifact: IArtifact } type UpdateMessage = { type: "update", artifact: Partial<IArtifact> } type Message = ResetMessage | SubstatMessage | OverwriteMessage | UpdateMessage interface IEditorArtifact { setKey: ArtifactSetKey, slotKey: SlotKey, level: number, rarity: ArtifactRarity, mainStatKey: MainStatKey, substats: ISubstat[], } function artifactReducer(state: IEditorArtifact | undefined, action: Message): IEditorArtifact | undefined { switch (action.type) { case "reset": return case "substat": { const { index, substat } = action const oldIndex = substat.key ? state!.substats.findIndex(current => current.key === substat.key) : -1 if (oldIndex === -1 || oldIndex === index) state!.substats[index] = substat else // Already in used, swap the items instead [state!.substats[index], state!.substats[oldIndex]] = [state!.substats[oldIndex], state!.substats[index]] return { ...state! } } case "overwrite": return action.artifact case "update": return { ...state!, ...action.artifact } } }
the_stack
import { BinaryRelations } from './mathcollection/BinaryRelations'; import { NumberTheory } from './mathcollection/NumberTheory'; import { PrimesCache } from './mathcollection/PrimesCache'; import { ProbabilityDistributions } from './mathcollection/ProbabilityDistributions'; import { BinaryRelation } from './parsertokens/BinaryRelation'; import { BitwiseOperator } from './parsertokens/BitwiseOperator'; import { BooleanOperator } from './parsertokens/BooleanOperator'; import { CalculusOperator } from './parsertokens/CalculusOperator'; import { ConstantValue } from './parsertokens/ConstantValue'; import { Function1Arg } from './parsertokens/Function1Arg'; import { Function2Arg } from './parsertokens/Function2Arg'; import { Function3Arg } from './parsertokens/Function3Arg'; import { FunctionVariadic } from './parsertokens/FunctionVariadic'; import { KeyWord } from './parsertokens/KeyWord'; import { Operator } from './parsertokens/Operator'; import { ParserSymbol } from './parsertokens/ParserSymbol'; import { RandomVariable } from './parsertokens/RandomVariable'; import type { Token } from './parsertokens/Token'; import { Unit } from './parsertokens/Unit'; import { Expression } from './Expression'; import { Constant } from './Constant'; import { FunctionConstants } from './FunctionConstants'; import { RecursiveArgument } from './RecursiveArgument'; import type { Argument } from './Argument'; import { ArgumentConstants } from './ArgumentConstants'; import { mXparserConstants } from './mXparserConstants'; import { TokenModification } from './Miscellaneous'; import { java } from 'j4ts/j4ts'; import { javaemul } from 'j4ts/j4ts'; /** * mXparser class provides usefull methods when parsing, calculating or * parameters transforming. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * * @version 4.4.2 * * @see RecursiveArgument * @see Expression * @see Function * @see Constant * @class */ export class mXparser { /** * Empty expression for general help purposes. */ static mXparserExp: Expression; public static mXparserExp_$LI$(): Expression { if (mXparser.mXparserExp == null) { mXparser.mXparserExp = new Expression(); } return mXparser.mXparserExp; } /** * Prime numbers cache */ public static primesCache: PrimesCache = null; public static initPrimesCache$() { mXparser.primesCache = new PrimesCache(); } public static initPrimesCache$int(mximumNumberInCache: number) { mXparser.primesCache = new PrimesCache(mximumNumberInCache); } public static initPrimesCache$org_mariuszgromada_math_mxparser_mathcollection_PrimesCache(primesCache: PrimesCache) { mXparser.primesCache = primesCache; } /** * Initialization of prime numbers cache. * @param {PrimesCache} primesCache The primes cache object * @see PrimesCache */ public static initPrimesCache(primesCache?: any) { if (((primesCache != null && primesCache instanceof <any>PrimesCache) || primesCache === null)) { return <any>mXparser.initPrimesCache$org_mariuszgromada_math_mxparser_mathcollection_PrimesCache(primesCache); } else if (((typeof primesCache === 'number') || primesCache === null)) { return <any>mXparser.initPrimesCache$int(primesCache); } else if (primesCache === undefined) { return <any>mXparser.initPrimesCache$(); } else throw new Error('invalid overload'); } /** * Returns true in case when primes cache initialization was successful, * otherwise returns false. * * @return {boolean} Returns true in case when primes cache initialization was successful, * otherwise returns false. */ public static isInitPrimesCacheSuccessful(): boolean { if (mXparser.primesCache == null) return false; { return mXparser.primesCache.isInitSuccessful(); }; } /** * Sets {@link mXparser#primesCache} to null */ public static setNoPrimesCache() { mXparser.primesCache = null; } /** * Returns maximum integer number in primes cache * @return {number} If primes cache was initialized then maximum number in * primes cache, otherwise {@link mXparser#PRIMES_CACHE_NOT_INITIALIZED} */ public static getMaxNumInPrimesCache(): number { if (mXparser.primesCache != null) { { return mXparser.primesCache.getMaxNumInCache(); }; } else return mXparserConstants.PRIMES_CACHE_NOT_INITIALIZED; } /** * Gets maximum threads number * * @return {number} Threads number. */ public static getThreadsNumber(): number { return mXparserConstants.THREADS_NUMBER_$LI$(); } /** * Sets default threads number */ public static setDefaultThreadsNumber() { mXparserConstants.THREADS_NUMBER = 1; } /** * Sets threads number * * @param {number} threadsNumber Thread number. */ public static setThreadsNumber(threadsNumber: number) { if (threadsNumber > 0) mXparserConstants.THREADS_NUMBER = threadsNumber; } /** * Calculates function f(x0) (given as expression) assigning Argument x = x0; * * * @param {Expression} f the expression * @param {Argument} x the argument * @param {number} x0 the argument value * * @return {number} f.calculate() * * @see Expression */ public static getFunctionValue(f: Expression, x: Argument, x0: number): number { x.setArgumentValue(x0); return f.calculate(); } /** * Returns array of double values of the function f(i) * calculated on the range: i = from to i = to by step = delta * * @param {Expression} f Function expression * @param {Argument} index Index argument * @param {number} from 'from' value * @param {number} to 'to' value * @param {number} delta 'delta' step definition * @return {double[]} Array of function values */ public static getFunctionValues(f: Expression, index: Argument, from: number, to: number, delta: number): number[] { if ((/* isNaN */isNaN(delta)) || (/* isNaN */isNaN(from)) || (/* isNaN */isNaN(to)) || (delta === 0)) return null; let n: number = 0; let values: number[]; if ((to >= from) && (delta > 0)) { for (let i: number = from; i < to; i += delta) { n++; } n++; values = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(n); let j: number = 0; for (let i: number = from; i < to; i += delta) { { values[j] = mXparser.getFunctionValue(f, index, i); j++; }; } values[j] = mXparser.getFunctionValue(f, index, to); } else if ((to <= from) && (delta < 0)) { for (let i: number = from; i > to; i += delta) { n++; } n++; values = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(n); let j: number = 0; for (let i: number = from; i > to; i += delta) { { values[j] = mXparser.getFunctionValue(f, index, i); j++; }; } values[j] = mXparser.getFunctionValue(f, index, to); } else if (from === to) { n = 1; values = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(n); values[0] = mXparser.getFunctionValue(f, index, from); } else values = null; return values; } /** * Modifies random generator used by the ProbabilityDistributions class. * * @param {Random} randomGenerator Random generator. * @see ProbabilityDistributions * @see ProbabilityDistributions#randomGenerator */ public static setRandomGenerator(randomGenerator: java.util.Random) { if (randomGenerator != null) ProbabilityDistributions.randomGenerator = randomGenerator; } /** * Sets comparison mode to EXACT. * @see BinaryRelations */ public static setExactComparison() { BinaryRelations.setExactComparison(); } /** * Sets comparison mode to EPSILON. * @see BinaryRelations */ public static setEpsilonComparison() { BinaryRelations.setEpsilonComparison(); } /** * Sets epsilon value. * @param {number} epsilon Epsilon value (grater than 0). * * @see #setEpsilonComparison() * @see BinaryRelations */ public static setEpsilon(epsilon: number) { BinaryRelations.setEpsilon(epsilon); } /** * Sets default epsilon value. * * @see #setEpsilonComparison() * @see BinaryRelations#DEFAULT_COMPARISON_EPSILON * @see BinaryRelations */ public static setDefaultEpsilon() { BinaryRelations.setDefaultEpsilon(); } /** * Returns current epsilon value. * @return {number} Returns current epsilon value. * * @see #setEpsilonComparison() * @see BinaryRelations */ public static getEpsilon(): number { return BinaryRelations.getEpsilon(); } /** * Checks if epsilon comparison mode is active; * @return {boolean} True if epsilon mode is active, otherwise returns false. * @see #setEpsilonComparison() * @see #setExactComparison() * @see BinaryRelations */ public static checkIfEpsilonMode(): boolean { return BinaryRelations.checkIfEpsilonMode(); } /** * Checks if exact comparison mode is active; * @return {boolean} True if exact mode is active, otherwise returns false. * @see #setEpsilonComparison() * @see #setExactComparison() * @see BinaryRelations */ public static checkIfExactMode(): boolean { return BinaryRelations.checkIfExactMode(); } /** * Enables ULP rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent ULP rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Using this mode 0.1 + 0.1 + 0.1 = 0.3 */ public static enableUlpRounding() { mXparserConstants.ulpRounding = true; } /** * Disables ULP rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent ULP rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Disabling this mode 0.1 + 0.1 + 0.1 will be slightly different than 0.3. */ public static disableUlpRounding() { mXparserConstants.ulpRounding = false; } /** * Enables / disables ULP rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent ULP rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Disabling this mode 0.1 + 0.1 + 0.1 will be slightly different than 0.3. * * @param {boolean} ulpRoundingState True to enable, false to disable */ public static setUlpRounding(ulpRoundingState: boolean) { mXparserConstants.ulpRounding = ulpRoundingState; } /** * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent ULP rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Using this mode 0.1 + 0.1 + 0.1 = 0.3 * * @return {boolean} True if ULP rounding is enabled, otherwise false. */ public static checkIfUlpRounding(): boolean { return mXparserConstants.ulpRounding; } /** * Enables canonical rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent canonical rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Using this mode 2.5 - 2.2 = 0.3 */ public static enableCanonicalRounding() { mXparserConstants.canonicalRounding = true; } /** * Disables canonical rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent canonical rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Using this mode 2.5 - 2.2 = 0.3 */ public static disableCanonicalRounding() { mXparserConstants.canonicalRounding = false; } /** * Enables / disables canonical rounding. * Double floating-point precision arithmetic causes * rounding problems, i.e. 0.1 + 0.1 + 0.1 is slightly different than 0.3, * additionally doubles are having a lot of advantages * providing flexible number representation regardless of * number size. mXparser is fully based on double numbers * and that is why is providing intelligent ULP rounding * to minimize misleading results. By default this option is * enabled resulting in automatic rounding only in some cases. * Disabling this mode 0.1 + 0.1 + 0.1 will be slightly different than 0.3. * * @param {boolean} canonicalRoundingState True to enable, false to disable */ public static setCanonicalRounding(canonicalRoundingState: boolean) { mXparserConstants.canonicalRounding = canonicalRoundingState; } /** * Enables almost integer rounding option causing * rounding final calculation result to precise integer * if and only if result is very close to integer. * Very close condition depends on epsilon. * * @see mXparser#setEpsilon(double) * @see mXparser#getEpsilon() * @see Expression#calculate() */ public static enableAlmostIntRounding() { mXparserConstants.almostIntRounding = true; } /** * Disables almost integer rounding option causing * rounding final calculation result to precise integer * if and only if result is very close to integer. * Very close condition depends on epsilon. * * @see mXparser#setEpsilon(double) * @see mXparser#getEpsilon() * @see Expression#calculate() */ public static disableAlmostIntRounding() { mXparserConstants.almostIntRounding = false; } /** * Enables / disables almost integer rounding option causing * rounding final calculation result to precise integer * if and only if result is very close to integer. * Very close condition depends on epsilon. * * @param {boolean} almostIntRoundingState True to enable, false to disable */ public static setAlmostIntRounding(almostIntRoundingState: boolean) { mXparserConstants.almostIntRounding = almostIntRoundingState; } /** * Returns state of almost integer rounding option causing * rounding final calculation result to precise integer * if and only if result is very close to integer. * Very close condition depends on epsilon. * * @return {boolean} true if option enabled, false otherwise * * @see mXparser#setEpsilon(double) * @see mXparser#getEpsilon() * @see Expression#calculate() */ public static checkIfAlmostIntRounding(): boolean { return mXparserConstants.almostIntRounding; } /** * Internal limit to avoid infinite loops while calculating * expression defined in the way shown by below examples. * * Argument x = new Argument("x = 2*y"); * Argument y = new Argument("y = 2*x"); * x.addDefinitions(y); * y.addDefinitions(x); * * Function f = new Function("f(x) = 2*g(x)"); * Function g = new Function("g(x) = 2*f(x)"); * f.addDefinitions(g); * g.addDefinitions(f); * * Currently does not affect properly defined recursive mode. * * @param {number} maxAllowedRecursionDepth Maximum number of allowed recursion calls */ public static setMaxAllowedRecursionDepth(maxAllowedRecursionDepth: number) { mXparserConstants.MAX_RECURSION_CALLS = maxAllowedRecursionDepth; } /** * Internal limit to avoid infinite loops while calculating * expression defined in the way shown by below examples. * * Argument x = new Argument("x = 2*y"); * Argument y = new Argument("y = 2*x"); * x.addDefinitions(y); * y.addDefinitions(x); * * Function f = new Function("f(x) = 2*g(x)"); * Function g = new Function("g(x) = 2*f(x)"); * f.addDefinitions(g); * g.addDefinitions(f); * * Currently does not affect properly defined recursive mode. * * @return {number} Max allowed recursion calls */ public static getMaxAllowedRecursionDepth(): number { return mXparserConstants.MAX_RECURSION_CALLS_$LI$(); } /** * Set mXparser to operate in radians mode for * trigonometric functions */ public static setRadiansMode() { mXparserConstants.degreesMode = false; } /** * Set mXparser to operate in degrees mode for * trigonometric functions */ public static setDegreesMode() { mXparserConstants.degreesMode = true; } /** * Sets initial search size for the toFraction method * * @param {number} n initial search size, has to be non-zero positive. * @see NumberTheory#toFraction(double) */ public static setToFractionInitSearchSize(n: number) { NumberTheory.setToFractionInitSearchSize(n); } /** * Gets initial search size used by the toFraction method * * @return {number} initial search size used by the toFraction method * @see NumberTheory#toFraction(double) */ public static getToFractionInitSearchSize(): number { return NumberTheory.getToFractionInitSearchSize(); } /** * Removes built-in tokens form the list of tokens recognized by the parsers. * Procedure affects only tokens classified to built-in functions, built-in * constants, built-in units, built-in random variables. * * @param {java.lang.String[]} tokens List of tokens to remove. */ public static removeBuiltinTokens(...tokens: string[]) { if (tokens == null) return; { for (let index189 = 0; index189 < tokens.length; index189++) { let token = tokens[index189]; if (token != null) if (token.length > 0) if (!mXparserConstants.tokensToRemove_$LI$().contains(token)) mXparserConstants.tokensToRemove_$LI$().add(token); } mXparserConstants.optionsChangesetNumber++; }; } /** * Un-marks tokens previously marked to be removed. * @param {java.lang.String[]} tokens List of tokens to un-mark. */ public static unremoveBuiltinTokens(...tokens: string[]) { if (tokens == null) return; if (tokens.length === 0) return; if (mXparserConstants.tokensToRemove_$LI$().size() === 0) return; { for (let index190 = 0; index190 < tokens.length; index190++) { let token = tokens[index190]; if (token != null) mXparserConstants.tokensToRemove_$LI$().remove(token); } mXparserConstants.optionsChangesetNumber++; }; } /** * Un-marks all tokens previously marked to be removed. */ public static unremoveAllBuiltinTokens() { { mXparserConstants.tokensToRemove_$LI$().clear(); mXparserConstants.optionsChangesetNumber++; }; } /** * Returns current list of tokens marked to be removed. * @return {java.lang.String[]} Current list of tokens marked to be removed */ public static getBuiltinTokensToRemove(): string[] { { const tokensNum: number = mXparserConstants.tokensToRemove_$LI$().size(); const tokensToRemoveArray: string[] = (s => { let a = []; while (s-- > 0) a.push(null); return a; })(tokensNum); for (let i: number = 0; i < tokensNum; i++) { tokensToRemoveArray[i] = mXparserConstants.tokensToRemove_$LI$().get(i); } return tokensToRemoveArray; }; } public static modifyBuiltinToken$java_lang_String$java_lang_String(currentToken: string, newToken: string) { if (currentToken == null) return; if (currentToken.length === 0) return; if (newToken == null) return; if (newToken.length === 0) return; { for (let index191 = mXparserConstants.tokensToModify_$LI$().iterator(); index191.hasNext();) { let tm = index191.next(); if (tm.currentToken === currentToken) return; } const tma: TokenModification = new TokenModification(); tma.currentToken = currentToken; tma.newToken = newToken; tma.newTokenDescription = null; mXparserConstants.tokensToModify_$LI$().add(tma); mXparserConstants.optionsChangesetNumber++; }; } public static modifyBuiltinToken$java_lang_String$java_lang_String$java_lang_String(currentToken: string, newToken: string, newTokenDescription: string) { if (currentToken == null) return; if (currentToken.length === 0) return; if (newToken == null) return; if (newToken.length === 0) return; { for (let index192 = mXparserConstants.tokensToModify_$LI$().iterator(); index192.hasNext();) { let tm = index192.next(); if (tm.currentToken === currentToken) return; } const tma: TokenModification = new TokenModification(); tma.currentToken = currentToken; tma.newToken = newToken; tma.newTokenDescription = newTokenDescription; mXparserConstants.tokensToModify_$LI$().add(tma); mXparserConstants.optionsChangesetNumber++; }; } /** * Method to change definition of built-in token - more precisely * using this method allows to modify token string recognized by the parser * (i.e. sin(x) to sinus(x)). * Procedure affects only tokens classified to built-in functions, built-in * constants, built-in units, built-in random variables. * @param {string} currentToken Current token name * @param {string} newToken New token name * @param {string} newTokenDescription New token description (if null the previous one will be used) */ public static modifyBuiltinToken(currentToken?: any, newToken?: any, newTokenDescription?: any) { if (((typeof currentToken === 'string') || currentToken === null) && ((typeof newToken === 'string') || newToken === null) && ((typeof newTokenDescription === 'string') || newTokenDescription === null)) { return <any>mXparser.modifyBuiltinToken$java_lang_String$java_lang_String$java_lang_String(currentToken, newToken, newTokenDescription); } else if (((typeof currentToken === 'string') || currentToken === null) && ((typeof newToken === 'string') || newToken === null) && newTokenDescription === undefined) { return <any>mXparser.modifyBuiltinToken$java_lang_String$java_lang_String(currentToken, newToken); } else throw new Error('invalid overload'); } /** * Un-marks tokens previously marked to be modified. * @param {java.lang.String[]} currentOrNewTokens List of tokens to be un-marked (current or modified). */ public static unmodifyBuiltinTokens(...currentOrNewTokens: string[]) { if (currentOrNewTokens == null) return; if (currentOrNewTokens.length === 0) return; if (mXparserConstants.tokensToModify_$LI$().size() === 0) return; { const toRemove: java.util.List<TokenModification> = <any>(new java.util.ArrayList<TokenModification>()); for (let index193 = 0; index193 < currentOrNewTokens.length; index193++) { let token = currentOrNewTokens[index193]; if (token != null) if (token.length > 0) { for (let index194 = mXparserConstants.tokensToModify_$LI$().iterator(); index194.hasNext();) { let tm = index194.next(); if ((token === tm.currentToken) || (token === tm.newToken)) toRemove.add(tm); } } } for (let index195 = toRemove.iterator(); index195.hasNext();) { let tm = index195.next(); mXparserConstants.tokensToModify_$LI$().remove(tm) } mXparserConstants.optionsChangesetNumber++; }; } /** * Un-marks all tokens previously marked to be modified. */ public static unmodifyAllBuiltinTokens() { { mXparserConstants.tokensToModify_$LI$().clear(); mXparserConstants.optionsChangesetNumber++; }; } /** * Return details on tokens marked to be modified. * @return {java.lang.String[][]} String[i][0] - current token, String[i][1] - new token, * String[i][2] - new token description. */ public static getBuiltinTokensToModify(): string[][] { { const tokensNum: number = mXparserConstants.tokensToModify_$LI$().size(); const tokensToModifyArray: string[][] = <any>(function (dims) { let allocate = function (dims) { if (dims.length === 0) { return null; } else { let array = []; for (let i = 0; i < dims[0]; i++) { array.push(allocate(dims.slice(1))); } return array; } }; return allocate(dims); })([tokensNum, 3]); for (let i: number = 0; i < tokensNum; i++) { { const tm: TokenModification = mXparserConstants.tokensToModify_$LI$().get(i); tokensToModifyArray[i][0] = tm.currentToken; tokensToModifyArray[i][1] = tm.newToken; tokensToModifyArray[i][2] = tm.newTokenDescription; }; } return tokensToModifyArray; }; } /** * Sets mXparser to override built-in tokens * by user defined tokens. */ public static setToOverrideBuiltinTokens() { mXparserConstants.overrideBuiltinTokens = true; mXparserConstants.optionsChangesetNumber++; } /** * Sets mXparser not to override built-in tokens * by user defined tokens. */ public static setNotToOverrideBuiltinTokens() { mXparserConstants.overrideBuiltinTokens = false; mXparserConstants.optionsChangesetNumber++; } /** * Checks whether mXparser is set to override built-in tokens. * * @return {boolean} True if mXparser is set to override built-in tokens by * user defined tokens, otherwise false. */ public static checkIfsetToOverrideBuiltinTokens(): boolean { return mXparserConstants.overrideBuiltinTokens; } /** * Sets default mXparser options */ public static setDefaultOptions() { mXparser.enableUlpRounding(); mXparser.enableAlmostIntRounding(); mXparser.setMaxAllowedRecursionDepth(mXparserConstants.DEFAULT_MAX_RECURSION_CALLS); mXparser.setNotToOverrideBuiltinTokens(); mXparser.unmodifyAllBuiltinTokens(); mXparser.setRadiansMode(); mXparserConstants.resetCancelCurrentCalculationFlag(); mXparser.setDefaultEpsilon(); mXparser.setEpsilonComparison(); mXparser.setToFractionInitSearchSize(NumberTheory.DEFAULT_TO_FRACTION_INIT_SEARCH_SIZE); mXparserConstants.optionsChangesetNumber++; } /** * Returns token type description. * * @param {number} tokenTypeId Token type id * @return {string} String representing token type description. */ public static getTokenTypeDescription(tokenTypeId: number): string { let type: string = ""; switch ((tokenTypeId)) { case ParserSymbol.TYPE_ID: type = ParserSymbol.TYPE_DESC; break; case ParserSymbol.NUMBER_TYPE_ID: type = "Number"; break; case Operator.TYPE_ID: type = Operator.TYPE_DESC; break; case BooleanOperator.TYPE_ID: type = BooleanOperator.TYPE_DESC; break; case BinaryRelation.TYPE_ID: type = BinaryRelation.TYPE_DESC; break; case Function1Arg.TYPE_ID: type = Function1Arg.TYPE_DESC; break; case Function2Arg.TYPE_ID: type = Function2Arg.TYPE_DESC; break; case Function3Arg.TYPE_ID: type = Function3Arg.TYPE_DESC; break; case FunctionVariadic.TYPE_ID: type = FunctionVariadic.TYPE_DESC; break; case CalculusOperator.TYPE_ID: type = CalculusOperator.TYPE_DESC; break; case RandomVariable.TYPE_ID: type = RandomVariable.TYPE_DESC; break; case ConstantValue.TYPE_ID: type = ConstantValue.TYPE_DESC; break; case ArgumentConstants.TYPE_ID: type = ArgumentConstants.TYPE_DESC; break; case RecursiveArgument.TYPE_ID_RECURSIVE: type = RecursiveArgument.TYPE_DESC_RECURSIVE; break; case FunctionConstants.TYPE_ID: type = FunctionConstants.TYPE_DESC; break; case Constant.TYPE_ID: type = Constant.TYPE_DESC; break; case Unit.TYPE_ID: type = Unit.TYPE_DESC; break; case BitwiseOperator.TYPE_ID: type = BitwiseOperator.TYPE_DESC; break; } return type; } public static numberToHexString$int(number: number): string { return javaemul.internal.IntegerHelper.toHexString(number); } /** * Converts integer number to hex string (plain text) * * @param {number} number Integer number * @return {string} Hex string (i.e. FF23) */ public static numberToHexString(number?: any): any { if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToHexString$int(number); } else if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToHexString$long(number); } else if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToHexString$double(number); } else throw new Error('invalid overload'); } public static numberToHexString$long(number: number): string { return javaemul.internal.LongHelper.toHexString(number); } public static numberToHexString$double(number: number): string { return mXparser.numberToHexString$long((n => n < 0 ? Math.ceil(n) : Math.floor(n))(<number>number)); } /** * Converts hex string into ASCII string, where each letter is * represented by two hex digits (byte) from the hex string. * * @param {string} hexString Hex string (i.e. 48656C6C6F) * @return {string} ASCII string (i.e. '48656C6C6F' = 'Hello') */ public static hexString2AsciiString(hexString: string): string { let hexByteStr: string; let hexByteInt: number; let asciiString: string = ""; for (let i: number = 0; i < hexString.length; i += 2) { { hexByteStr = hexString.substring(i, i + 2); hexByteInt = javaemul.internal.IntegerHelper.parseInt(hexByteStr, 16); asciiString = asciiString + String.fromCharCode(hexByteInt); }; } return asciiString; } public static numberToAsciiString$int(number: number): string { return mXparser.hexString2AsciiString(mXparser.numberToHexString$int(number)); } /** * Converts number into ASCII string, where each letter is * represented by two hex digits (byte) from the hex representation * of the original number * * @param {number} number Integer number (i.e. 310939249775 = '48656C6C6F') * @return {string} ASCII string (i.e. '48656C6C6F' = 'Hello') */ public static numberToAsciiString(number?: any): any { if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToAsciiString$int(number); } else if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToAsciiString$long(number); } else if (((typeof number === 'number') || number === null)) { return <any>mXparser.numberToAsciiString$double(number); } else throw new Error('invalid overload'); } public static numberToAsciiString$long(number: number): string { return mXparser.hexString2AsciiString(mXparser.numberToHexString$long(number)); } public static numberToAsciiString$double(number: number): string { return mXparser.hexString2AsciiString(mXparser.numberToHexString$double(number)); } public static convOthBase2Decimal$java_lang_String$int(numberLiteral: string, numeralSystemBase: number): number { return NumberTheory.convOthBase2Decimal$java_lang_String$int(numberLiteral, numeralSystemBase); } /** * Other base (base between 1 and 36) number literal conversion to decimal number. * * @param {string} numberLiteral Number literal in given numeral system with base between * 1 and 36. Digits: 0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, * 8:8, 9:9, 10:A, 11:B, 12:C, 13:D, 14:E, 15:F, 16:G, 17:H, * 18:I, 19:J, 20:K, 21:L, 22:M, 23:N, 24:O, 25:P, 26:Q, 27:R, * 28:S, 29:T, 30:U, 31:V, 32:W, 33:X, 34:Y, 35:Z * @param {number} numeralSystemBase Numeral system base, between 1 and 36 * @return {number} Decimal number after conversion. If conversion was not * possible the Double.NaN is returned. */ public static convOthBase2Decimal(numberLiteral?: any, numeralSystemBase?: any): any { if (((typeof numberLiteral === 'string') || numberLiteral === null) && ((typeof numeralSystemBase === 'number') || numeralSystemBase === null)) { return <any>mXparser.convOthBase2Decimal$java_lang_String$int(numberLiteral, numeralSystemBase); } else if (((typeof numberLiteral === 'number') || numberLiteral === null) && ((numeralSystemBase != null && numeralSystemBase instanceof <any>Array && (numeralSystemBase.length == 0 || numeralSystemBase[0] == null || (typeof numeralSystemBase[0] === 'number'))) || numeralSystemBase === null)) { return <any>mXparser.convOthBase2Decimal$int$int_A(numberLiteral, ...numeralSystemBase); } else if (((typeof numberLiteral === 'number') || numberLiteral === null) && ((numeralSystemBase != null && numeralSystemBase instanceof <any>Array && (numeralSystemBase.length == 0 || numeralSystemBase[0] == null || (typeof numeralSystemBase[0] === 'number'))) || numeralSystemBase === null)) { return <any>mXparser.convOthBase2Decimal$double$double_A(numberLiteral, ...numeralSystemBase); } else if (((typeof numberLiteral === 'string') || numberLiteral === null) && numeralSystemBase === undefined) { return <any>mXparser.convOthBase2Decimal$java_lang_String(numberLiteral); } else throw new Error('invalid overload'); } public static convOthBase2Decimal$java_lang_String(numberLiteral: string): number { return NumberTheory.convOthBase2Decimal$java_lang_String(numberLiteral); } public static convOthBase2Decimal$int$int_A(numeralSystemBase: number, ...digits: number[]): number { return NumberTheory.convOthBase2Decimal$int$int_A.apply(null, [numeralSystemBase].concat(<any[]>digits)); } public static convOthBase2Decimal$double$double_A(numeralSystemBase: number, ...digits: number[]): number { return NumberTheory.convOthBase2Decimal$double$double_A.apply(null, [numeralSystemBase].concat(<any[]>digits)); } public static convDecimal2OthBase$double$int(decimalNumber: number, numeralSystemBase: number): string { return NumberTheory.convDecimal2OthBase$double$int(decimalNumber, numeralSystemBase); } public static convDecimal2OthBase$double$int$int(decimalNumber: number, numeralSystemBase: number, format: number): string { return NumberTheory.convDecimal2OthBase$double$int$int(decimalNumber, numeralSystemBase, format); } /** * Decimal number to other numeral system conversion with base * between 1 and 36. * * @param {number} decimalNumber Decimal number * @param {number} numeralSystemBase Numeral system base between 1 and 36 * @param {number} format If 1 then always bxx. is used, i.e. b1. or b16. * If 2 then for binary b. is used, for octal o. is used, * for hexadecimal h. is used, otherwise bxx. is used * where xx is the numeral system base specification. * * @return {string} Number literal representing decimal number in * given numeral numeral system. * * Base format: b1. b2. b. b3. b4. b5. b6. b7. b8. o. b9. b10. b11. b12. * b13. b14. b15. b16. h. b17. b18. b19. b20. b21. b22. b23. b24. b25. b26. * b27. b28. b29. b30. b31. b32. b33. b34. b35. b36. * * Digits: 0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:A, 11:B, 12:C, * 13:D, 14:E, 15:F, 16:G, 17:H, 18:I, 19:J, 20:K, 21:L, 22:M, 23:N, 24:O, 25:P, * 26:Q, 27:R, 28:S, 29:T, 30:U, 31:V, 32:W, 33:X, 34:Y, 35:Z * * If conversion was not possible the "NaN" string is returned. */ public static convDecimal2OthBase(decimalNumber?: any, numeralSystemBase?: any, format?: any): any { if (((typeof decimalNumber === 'number') || decimalNumber === null) && ((typeof numeralSystemBase === 'number') || numeralSystemBase === null) && ((typeof format === 'number') || format === null)) { return <any>mXparser.convDecimal2OthBase$double$int$int(decimalNumber, numeralSystemBase, format); } else if (((typeof decimalNumber === 'number') || decimalNumber === null) && ((typeof numeralSystemBase === 'number') || numeralSystemBase === null) && format === undefined) { return <any>mXparser.convDecimal2OthBase$double$int(decimalNumber, numeralSystemBase); } else throw new Error('invalid overload'); } /** * Converts double value to its fraction representation. * * @param {number} value Value to be converted * * @return {double[]} Array representing fraction. Sign at index 0, * numerator at index 1, denominator at index 2. * If conversion is not possible then Double.NaN is * assigned to all the fields. */ public static toFraction(value: number): number[] { return NumberTheory.toFraction(value); } /** * Converts double value to its mixed fraction representation. * * @param {number} value Value to be converted * * @return {double[]} Array representing fraction. * Sign at index 0, whole number at index 1, * numerator at index 2, denominator at index 3. * If conversion is not possible then Double.NaN is * assigned to both numerator and denominator. */ public static toMixedFraction(value: number): number[] { return NumberTheory.toMixedFraction(value); } /** * Converts array representing fraction to fraction string representation. * * @param {double[]} fraction Array representing fraction (including mix fractions) * @return {string} String representation of fraction. * * @see NumberTheory#toFraction(double) * @see NumberTheory#toMixedFraction(double) */ public static fractionToString(fraction: number[]): string { return NumberTheory.fractionToString(fraction); } /** * Converts number to its fraction string representation. * * @param {number} value Given number * @return {string} String representation of fraction. * * @see NumberTheory#toFraction(double) * @see NumberTheory#fractionToString(double[]) */ public static toFractionString(value: number): string { return NumberTheory.toFractionString(value); } /** * Converts number to its mixed fraction string representation. * * @param {number} value Given number * @return {string} String representation of fraction. * * @see NumberTheory#toMixedFraction(double) * @see NumberTheory#fractionToString(double[]) */ public static toMixedFractionString(value: number): string { return NumberTheory.toMixedFractionString(value); } /** * Resets console output string, console output * string is being built by consolePrintln(), consolePrint(). * * @see mXparser#consolePrint(Object) * @see mXparser#consolePrintln(Object) * @see mXparser#consolePrintln() * @see mXparser#resetConsoleOutput() */ public static resetConsoleOutput() { { mXparserConstants.CONSOLE_OUTPUT = ""; mXparserConstants.CONSOLE_ROW_NUMBER = 1; }; } /** * Sets default console prefix. */ public static setDefaultConsolePrefix() { { mXparserConstants.CONSOLE_PREFIX = "[mXparser-v." + mXparserConstants.VERSION + "] "; }; } /** * Sets default console output string prefix. */ public static setDefaultConsoleOutputPrefix() { { mXparserConstants.CONSOLE_OUTPUT_PREFIX = "[mXparser-v." + mXparserConstants.VERSION + "] "; }; } /** * Sets console prefix. * * @param {string} consolePrefix String containing console prefix definition. */ public static setConsolePrefix(consolePrefix: string) { { mXparserConstants.CONSOLE_PREFIX = consolePrefix; }; } /** * Sets console output string prefix. * * @param {string} consoleOutputPrefix String containing console output prefix definition. */ public static setConsoleOutputPrefix(consoleOutputPrefix: string) { { mXparserConstants.CONSOLE_OUTPUT_PREFIX = consoleOutputPrefix; }; } /** * Returns console output string, console output string * is being built by consolePrintln(), consolePrint(). * * @return {string} Console output string * * @see mXparser#consolePrint(Object) * @see mXparser#consolePrintln(Object) * @see mXparser#consolePrintln() * @see mXparser#resetConsoleOutput() */ public static getConsoleOutput(): string { return mXparserConstants.CONSOLE_OUTPUT; } public static getHelp$(): string { { return mXparser.mXparserExp_$LI$().getHelp$(); }; } public static getHelp$java_lang_String(word: string): string { { return mXparser.mXparserExp_$LI$().getHelp$java_lang_String(word); }; } /** * General mXparser expression help - in-line key word searching * @param {string} word Key word to be searched * @return {string} String with all help content * lines containing given keyword */ public static getHelp(word?: any): any { if (((typeof word === 'string') || word === null)) { return <any>mXparser.getHelp$java_lang_String(word); } else if (word === undefined) { return <any>mXparser.getHelp$(); } else throw new Error('invalid overload'); } public static consolePrintHelp$() { console.info(mXparser.getHelp$()); } public static consolePrintHelp$java_lang_String(word: string) { console.info(mXparser.getHelp$java_lang_String(word)); } /** * Prints filtered help content. * @param {string} word Key word. */ public static consolePrintHelp(word?: any) { if (((typeof word === 'string') || word === null)) { return <any>mXparser.consolePrintHelp$java_lang_String(word); } else if (word === undefined) { return <any>mXparser.consolePrintHelp$(); } else throw new Error('invalid overload'); } public static getKeyWords$(): java.util.List<KeyWord> { { return mXparser.mXparserExp_$LI$().getKeyWords$(); }; } public static getKeyWords$java_lang_String(query: string): java.util.List<KeyWord> { { return mXparser.mXparserExp_$LI$().getKeyWords$java_lang_String(query); }; } /** * Returns list of key words known to the parser * * @param {string} query Give any string to filter list of key words against this string. * User more precise syntax: str=tokenString, desc=tokenDescription, * syn=TokenSyntax, sin=tokenSince, wid=wordId, tid=wordTypeId * to narrow the result. * * @return {*} List of keywords known to the parser filter against query string. * * @see KeyWord * @see KeyWord#wordTypeId * @see mXparser#getHelp(String) */ public static getKeyWords(query?: any): any { if (((typeof query === 'string') || query === null)) { return <any>mXparser.getKeyWords$java_lang_String(query); } else if (query === undefined) { return <any>mXparser.getKeyWords$(); } else throw new Error('invalid overload'); } /** * Prints tokens to the console. * @param {*} tokens Tokens list. * * @see Expression#getCopyOfInitialTokens() * @see Token */ public static consolePrintTokens(tokens: java.util.List<Token>) { Expression.showTokens(tokens); } /** * Gets license info * * @return {string} license info as string */ public static getLicense(): string { return mXparserConstants.LICENSE_$LI$(); } /** * Waits given number of milliseconds * * @param {number} n Number of milliseconds */ public static wait(n: number) { let t0: number; let t1: number; t0 = java.lang.System.currentTimeMillis(); do { { t1 = java.lang.System.currentTimeMillis(); } } while ((t1 - t0 < n)); } } mXparser["__class"] = "org.mariuszgromada.math.mxparser.mXparser";
the_stack
import { AlertsListComponent } from './alerts-list.component'; import { ComponentFixture, async, TestBed, fakeAsync, tick } from '@angular/core/testing'; import { Component, Input, Directive } from '@angular/core'; import { RouterTestingModule } from '@angular/router/testing'; import { SearchService } from 'app/service/search.service'; import { UpdateService } from 'app/service/update.service'; import { ConfigureTableService } from 'app/service/configure-table.service'; import { AlertsService } from 'app/service/alerts.service'; import { ClusterMetaDataService } from 'app/service/cluster-metadata.service'; import { SaveSearchService } from 'app/service/save-search.service'; import { MetaAlertService } from 'app/service/meta-alert.service'; import { GlobalConfigService } from 'app/service/global-config.service'; import { DialogService } from 'app/service/dialog.service'; import { TIMESTAMP_FIELD_NAME } from 'app/utils/constants'; import { By } from '@angular/platform-browser'; import { Observable, Subject, of, throwError } from 'rxjs'; import { Filter } from 'app/model/filter'; import { QueryBuilder, FilteringMode } from './query-builder'; import { SearchResponse } from 'app/model/search-response'; import { AutoPollingService } from './auto-polling/auto-polling.service'; import { Router, NavigationStart } from '@angular/router'; import { Alert } from 'app/model/alert'; import { AlertSource } from 'app/model/alert-source'; import { SearchRequest } from 'app/model/search-request'; import { query } from '@angular/core/src/render3'; import { RestError } from 'app/model/rest-error'; import { DialogType } from 'app/shared/metron-dialog/metron-dialog.component'; import { SaveSearch } from 'app/model/save-search'; @Component({ selector: 'app-auto-polling', template: '<div></div>', }) class MockAutoPollingComponent {} @Component({ selector: 'app-configure-rows', template: '<div></div>', }) class MockConfigureRowsComponent { @Input() refreshInterval = 0; @Input() srcElement = {}; @Input() pageSize = 0; } @Component({ selector: 'app-modal-loading-indicator', template: '<div></div>', }) class MockModalLoadingIndicatorComponent { @Input() show = false; } @Component({ selector: 'app-time-range', template: '<div></div>', }) class MockTimeRangeComponent { @Input() disabled = false; @Input() selectedTimeRange = {}; } @Directive({ selector: '[appAceEditor]', }) class MockAceEditorDirective { @Input() text = ''; } @Component({ selector: 'app-alert-filters', template: '<div></div>', }) class MockAlertFilterComponent { @Input() facets = []; } @Component({ selector: 'app-group-by', template: '<div></div>', }) class MockGroupByComponent { @Input() facets = []; } @Component({ selector: 'app-table-view', template: '<div></div>', }) class MockTableViewComponent { @Input() alerts = []; @Input() pagination = {}; @Input() alertsColumnsToDisplay = []; @Input() selectedAlerts = []; } @Component({ selector: 'app-tree-view', template: '<div></div>', }) class MockTreeViewComponent { @Input() alerts = []; @Input() pagination = {}; @Input() alertsColumnsToDisplay = []; @Input() selectedAlerts = []; @Input() globalConfig = {}; @Input() query = ''; @Input() groups = []; } describe('AlertsListComponent', () => { let component: AlertsListComponent; let fixture: ComponentFixture<AlertsListComponent>; let queryBuilder: QueryBuilder; let searchService: SearchService; beforeEach(async(() => { const searchResponseFake = new SearchResponse(); searchResponseFake.facetCounts = {}; TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes([{path: 'alerts-list', component: AlertsListComponent}]), ], declarations: [ AlertsListComponent, MockAutoPollingComponent, MockModalLoadingIndicatorComponent, MockTimeRangeComponent, MockAceEditorDirective, MockConfigureRowsComponent, MockAlertFilterComponent, MockGroupByComponent, MockTableViewComponent, MockTreeViewComponent, ], providers: [ { provide: SearchService, useClass: () => { return { search: () => of(searchResponseFake), } } }, { provide: UpdateService, useClass: () => { return { alertChanged$: new Observable(), updateAlertState: () => of(), } } }, { provide: ConfigureTableService, useClass: () => { return { getTableMetadata: () => new Observable(), tableChanged$: new Observable(), saveTableMetaData: () => of(), } } }, { provide: AlertsService, useClass: () => { return {} } }, { provide: ClusterMetaDataService, useClass: () => { return { getDefaultColumns: () => new Observable(), } } }, { provide: SaveSearchService, useClass: () => { return { loadSavedSearch$: new Observable(), setCurrentQueryBuilderAndTableColumns: () => {}, fireLoadSavedSearch: (savedSearch: any) => { this.loadSavedSearch$.next(savedSearch); }, saveAsRecentSearches: () => of(null), } } }, { provide: MetaAlertService, useClass: () => { return { alertChanged$: new Observable(), selectedAlerts: [] } } }, { provide: GlobalConfigService, useClass: () => { return { get: () => new Observable(), } } }, { provide: DialogService, useClass: () => { return {} } }, { provide: QueryBuilder, useClass: () => { return { filters: [], query: '*', searchRequest: () => { return new SearchResponse(); }, addOrUpdateFilter: () => {}, clearSearch: () => {}, isTimeStampFieldPresent: () => {}, getManualQuery: () => {}, setManualQuery: () => {}, getFilteringMode: () => {}, setFilteringMode: () => {}, generateNameForSearchRequest: () => '', setSearch: () => {}, } } }, { provide: AutoPollingService, useClass: () => { return { data: new Subject<SearchResponse>(), getIsCongestion: () => {}, getInterval: () => {}, getIsPollingActive: () => {}, dropNextAndContinue: () => {}, onDestroy: () => {}, setSuppression: () => {}, setInterval: () => {}, } } }, ] }) .compileComponents(); queryBuilder = TestBed.get(QueryBuilder); searchService = TestBed.get(SearchService); })); beforeEach(() => { fixture = TestBed.createComponent(AlertsListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should exist', () => { expect(component).toBeTruthy(); }); it('should get global config on init', () => { const globalConfig = { 'source.type.field': 'test'} const globalConfigService = TestBed.get(GlobalConfigService); spyOn(globalConfigService, 'get').and.returnValue(of(globalConfig)); component.ngOnInit(); component.alertsColumns = [ { name: 'ip:source', type: 'testType' }, { name: 'source:type', type: 'testType' } ]; fixture.detectChanges(); expect(component.globalConfig).toEqual(globalConfig); expect(component.alertsColumns.length).toEqual(2); }); it('should clear selected alerts if NavigationStart', () => { const router = TestBed.get(Router); spyOn(router, 'events').and.returnValue({url: '/alerts-list'} instanceof NavigationStart); component.ngOnInit(); fixture.detectChanges(); expect(component.selectedAlerts).toEqual([]); }); it('should set default query time range', () => { expect(component.selectedTimeRange instanceof Filter).toBeTruthy(); expect(component.selectedTimeRange.value).toBe('last-15-minutes'); }); it('default query time range from date should be set', () => { expect(component.selectedTimeRange.dateFilterValue.fromDate).toBeTruthy(); }); it('default query time range to date should be set', () => { expect(component.selectedTimeRange.dateFilterValue.toDate).toBeTruthy(); }); it('shows subtotals in view when onTreeViewChange is truthy', () => { component.onTreeViewChange(4); fixture.detectChanges(); let subtotal = fixture.nativeElement.querySelector('[data-qe-id="alert-subgroup-total"]'); expect(subtotal.textContent).toEqual('Alerts in Groups (4)'); component.onTreeViewChange(0); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('[data-qe-id="alert-subgroup-total"]')).toBeNull(); }); describe('filtering by query builder or manual query', () => { it('should be able to toggle the query builder mode', () => { spyOn(component, 'setSearchRequestSize'); spyOn(queryBuilder, 'setFilteringMode'); queryBuilder.getFilteringMode = () => FilteringMode.BUILDER; component.toggleQueryBuilderMode(); expect(queryBuilder.setFilteringMode).toHaveBeenCalledWith(FilteringMode.MANUAL); queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; component.toggleQueryBuilderMode(); expect(queryBuilder.setFilteringMode).toHaveBeenCalledWith(FilteringMode.BUILDER); }); it('isQueryBuilderModeManual should return true if queryBuilder is in manual mode', () => { queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; expect(component.isQueryBuilderModeManual()).toBe(true); queryBuilder.getFilteringMode = () => FilteringMode.BUILDER; expect(component.isQueryBuilderModeManual()).toBe(false); }); it('should show manual input dom element depending on mode', () => { let input = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')); expect(input).toBeFalsy(); queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; fixture.detectChanges(); input = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')); expect(input).toBeTruthy(); queryBuilder.getFilteringMode = () => FilteringMode.BUILDER; fixture.detectChanges(); input = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')); expect(input).toBeFalsy(); }); it('should bind default manual query from query builder', () => { spyOn(queryBuilder, 'getManualQuery').and.returnValue('test manual query string') queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; fixture.detectChanges(); let input: HTMLInputElement = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')).nativeElement; expect(input.value).toBe('test manual query string'); }); it('should pass the manual query value to the query builder when editing mode is manual', fakeAsync(() => { spyOn(queryBuilder, 'setManualQuery'); queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')); const el = input.nativeElement; el.value = 'test'; (el as HTMLElement).dispatchEvent(new Event('keyup')); fixture.detectChanges(); tick(300); expect(queryBuilder.setManualQuery).toHaveBeenCalledWith('test'); })); }); describe('handling pending search requests', () => { it('should set pendingSearch on search', () => { spyOn(searchService, 'search').and.returnValue(of(new SearchResponse())); spyOn(component, 'saveCurrentSearch'); spyOn(component, 'setSearchRequestSize'); spyOn(component, 'setSelectedTimeRange'); spyOn(component, 'createGroupFacets'); component.search(); expect(component.pendingSearch).toBeTruthy(); }); it('should clear pendingSearch on search success', (done) => { const fakeObservable = new Subject(); spyOn(searchService, 'search').and.returnValue(fakeObservable); spyOn(component, 'saveCurrentSearch'); spyOn(component, 'setSearchRequestSize'); spyOn(component, 'setSelectedTimeRange'); spyOn(component, 'createGroupFacets'); component.search(); setTimeout(() => { fakeObservable.next(new SearchResponse()); }, 0); fakeObservable.subscribe(() => { expect(component.pendingSearch).toBe(null); done(); }) }); }); describe('stale data state', () => { it('should set staleDataState flag to true on filter change', () => { expect(component.staleDataState).toBe(false); component.onAddFilter(new Filter('ip_src_addr', '0.0.0.0')); expect(component.staleDataState).toBe(true); }); it('should set staleDataState flag to true on filter clearing', () => { spyOn(component, 'setSearchRequestSize'); expect(component.staleDataState).toBe(false); component.onClear(); expect(component.staleDataState).toBe(true); }); it('should set staleDataState flag to true on timerange change', () => { expect(component.staleDataState).toBe(false); component.onTimeRangeChange(new Filter(TIMESTAMP_FIELD_NAME, 'this-year')); expect(component.staleDataState).toBe(true); }); it('should set staleDataState flag to false when the query resolves', () => { spyOn(searchService, 'search').and.returnValue(of(new SearchResponse())); spyOn(component, 'saveCurrentSearch'); spyOn(component, 'setSearchRequestSize'); spyOn(component, 'setSelectedTimeRange'); spyOn(component, 'createGroupFacets'); component.staleDataState = true; component.search(); expect(component.staleDataState).toBe(false); }); it('should set stale date true when query changes in manual mode', fakeAsync(() => { queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('[data-qe-id="manual-query-input"]')); const el = input.nativeElement; el.value = 'test'; (el as HTMLElement).dispatchEvent(new Event('keyup')); fixture.detectChanges(); tick(300); expect(component.staleDataState).toBe(true); })); it('should show warning if data is in a stale state', () => { expect(fixture.debugElement.query(By.css('[data-qe-id="staleDataWarning"]'))).toBe(null); component.staleDataState = true; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('[data-qe-id="staleDataWarning"]'))).toBeTruthy(); }); }); describe('auto polling', () => { it('should refresh view on data emit', () => { const fakeResponse = new SearchResponse(); spyOn(component, 'setData'); TestBed.get(AutoPollingService).data.next(fakeResponse); expect(component.setData).toHaveBeenCalledWith(fakeResponse); }); it('should set staleDataState false on auto polling refresh', () => { spyOn(component, 'setData'); component.staleDataState = true; TestBed.get(AutoPollingService).data.next(new SearchResponse()); expect(component.staleDataState).toBe(false); }); it('should show warning on auto polling congestion', () => { expect(fixture.debugElement.query(By.css('[data-qe-id="pollingCongestionWarning"]'))).toBeFalsy(); TestBed.get(AutoPollingService).getIsCongestion = () => true; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('[data-qe-id="pollingCongestionWarning"]'))).toBeTruthy(); TestBed.get(AutoPollingService).getIsCongestion = () => false; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('[data-qe-id="pollingCongestionWarning"]'))).toBeFalsy(); }); it('should pass refresh interval to row config component', () => { TestBed.get(AutoPollingService).getInterval = () => 44; fixture.detectChanges(); expect(fixture.debugElement.query(By.directive(MockConfigureRowsComponent)).componentInstance.refreshInterval).toBe(44); }); it('should drop pending auto polling result if user trigger search request manually', () => { const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(autoPollingSvc, 'dropNextAndContinue'); spyOn(component, 'setSearchRequestSize'); autoPollingSvc.getIsPollingActive = () => false; component.search() expect(autoPollingSvc.dropNextAndContinue).not.toHaveBeenCalled(); autoPollingSvc.getIsPollingActive = () => true; component.search() expect(autoPollingSvc.dropNextAndContinue).toHaveBeenCalled(); }); it('should show different stale data warning when polling is active', () => { const autoPollingSvc = TestBed.get(AutoPollingService); autoPollingSvc.getIsPollingActive = () => false; const warning = component.getStaleDataWarning(); autoPollingSvc.getIsPollingActive = () => true; const warningWhenPolling = component.getStaleDataWarning(); expect(warning).not.toEqual(warningWhenPolling); }); it('should show getIsCongestion scennarios', () => { const autoPollingSvc = TestBed.get(AutoPollingService); autoPollingSvc.getIsCongestion = () => false; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('[data-qe-id="pollingCongestionWarning"]'))).toBeFalsy(); autoPollingSvc.getIsCongestion = () => true; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('[data-qe-id="pollingCongestionWarning"]'))).toBeTruthy(); }); it('should suppress polling when user select alerts', () => { const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(autoPollingSvc, 'setSuppression'); component.onSelectedAlertsChange([{ source: { metron_alert: [] } }]); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(true); }); it('should restore polling from suppression when user deselect alerts', () => { const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(autoPollingSvc, 'setSuppression'); component.onSelectedAlertsChange([]); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(false); }); it('should suppress polling when open details pane', () => { const autoPollingSvc = TestBed.get(AutoPollingService); const router = TestBed.get(Router); spyOn(router, 'navigate').and.returnValue(true); spyOn(router, 'navigateByUrl').and.returnValue(true); spyOn(autoPollingSvc, 'setSuppression'); component.showConfigureTable(); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(true); }); it('should suppress polling when open column config pane', () => { const router = TestBed.get(Router); const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(router, 'navigate'); spyOn(router, 'navigateByUrl'); spyOn(autoPollingSvc, 'setSuppression'); const fakeAlert = new Alert(); fakeAlert.source = new AlertSource(); component.showDetails(fakeAlert); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(true); }); it('should suppress polling when open Saved Searches pane', () => { const router = TestBed.get(Router); const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(router, 'navigate'); spyOn(router, 'navigateByUrl'); spyOn(autoPollingSvc, 'setSuppression'); component.showSavedSearches(); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(true); }); it('should suppress polling when open Save Search dialogue pane', () => { const router = TestBed.get(Router); const autoPollingSvc = TestBed.get(AutoPollingService); const saveSearchSvc = TestBed.get(SaveSearchService); spyOn(router, 'navigate'); spyOn(router, 'navigateByUrl'); spyOn(autoPollingSvc, 'setSuppression'); spyOn(saveSearchSvc, 'setCurrentQueryBuilderAndTableColumns'); component.showSaveSearch(); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(true); }); it('should restore the polling supression on bulk status update (other scenario of deselecting alerts)', () => { const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(autoPollingSvc, 'setSuppression'); component.updateSelectedAlertStatus('fakeState'); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(false); }); it('should restore the polling supression when returning from a subroute', fakeAsync(() => { const autoPollingSvc = TestBed.get(AutoPollingService); spyOn(autoPollingSvc, 'setSuppression'); autoPollingSvc.getIsPollingActive = () => false; fixture.ngZone.run(() => { TestBed.get(Router).navigate(['/alerts-list']); }); expect(autoPollingSvc.setSuppression).not.toHaveBeenCalled(); autoPollingSvc.getIsPollingActive = () => true; fixture.ngZone.run(() => { TestBed.get(Router).navigate(['/alerts-list']); }); expect(autoPollingSvc.setSuppression).toHaveBeenCalledWith(false); })); }); describe('search', () => { it('should fire onSearch if in manual search mode', () => { const testQuery = 'test'; spyOn(queryBuilder, 'setFilteringMode').and.returnValue(FilteringMode.BUILDER); spyOn(queryBuilder, 'setSearch'); spyOn(component, 'search'); component.toggleQueryBuilderMode(); fixture.detectChanges(); component.onSearch(testQuery); expect(queryBuilder.setSearch).toHaveBeenCalledWith(testQuery); }); it('should show notification on http error', fakeAsync(() => { const fakeDialogService = TestBed.get(DialogService); spyOn(searchService, 'search').and.returnValue(throwError(new RestError())); fakeDialogService.launchDialog = () => {}; spyOn(fakeDialogService, 'launchDialog'); component.search(); expect(fakeDialogService.launchDialog).toHaveBeenCalledWith('Server were unable to apply query string.', DialogType.Error); })); it('should save current search', () => { const saveSearchService = TestBed.get(SaveSearchService); const search = new SaveSearch(); spyOn(saveSearchService, 'saveAsRecentSearches').and.callThrough(); spyOn(queryBuilder, 'query').and.returnValue('test'); component.saveCurrentSearch(search); expect(saveSearchService.saveAsRecentSearches).toHaveBeenCalledWith(search); }); }); describe('actions', () => { const testAlert: Alert = { id: '123', score: 123, source: new AlertSource(), status: 'TEST', index: 'test' } it('should prevent a user from selecting a new alert state if disabled', () => { const updateService = TestBed.get(UpdateService); spyOn(updateService, 'updateAlertState') spyOn(component, 'preventDropdownOptionIfDisabled'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const openButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-open-button"'); expect(openButton.classList).toContain('disabled'); openButton.dispatchEvent(new Event('click')); expect(component.preventDropdownOptionIfDisabled).toHaveBeenCalled(); expect(updateService.updateAlertState).not.toHaveBeenCalled(); }); it('should update the alert state to open when selected', () => { component.selectedAlerts.push(testAlert); fixture.detectChanges(); const updateService = TestBed.get(UpdateService); spyOn(updateService, 'updateAlertState').and.returnValue(of({})); spyOn(component, 'processOpen').and.callThrough(); spyOn(component, 'updateSelectedAlertStatus'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const openButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-open-button"'); openButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(component.processOpen).toHaveBeenCalled(); expect(updateService.updateAlertState).toHaveBeenCalledWith(component.selectedAlerts, 'OPEN', false); }); it('should update the alert state to dismiss when selected', () => { component.selectedAlerts.push(testAlert); fixture.detectChanges(); const updateService = TestBed.get(UpdateService); spyOn(updateService, 'updateAlertState').and.returnValue(of()); spyOn(component, 'processDismiss').and.callThrough(); spyOn(component, 'updateSelectedAlertStatus'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const dismissButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-dismiss-button"'); dismissButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(component.processDismiss).toHaveBeenCalled(); expect(updateService.updateAlertState).toHaveBeenCalledWith(component.selectedAlerts, 'DISMISS', false); }); it('should update the alert state to escalate when selected', () => { component.selectedAlerts.push(testAlert); fixture.detectChanges(); const updateService = TestBed.get(UpdateService); spyOn(updateService, 'updateAlertState').and.returnValue(of()); spyOn(component, 'processEscalate').and.callThrough(); spyOn(component, 'updateSelectedAlertStatus'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const escalateButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-escalate-button"'); escalateButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(component.processEscalate).toHaveBeenCalled(); expect(updateService.updateAlertState).toHaveBeenCalledWith(component.selectedAlerts, 'ESCALATE', false); }); it('should update the alert state to resolve when selected', () => { component.selectedAlerts.push(testAlert); fixture.detectChanges(); const updateService = TestBed.get(UpdateService); spyOn(updateService, 'updateAlertState').and.returnValue(of()); spyOn(component, 'processResolve').and.callThrough(); spyOn(component, 'updateSelectedAlertStatus'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const resolveButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-resolve-button"'); resolveButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(component.processResolve).toHaveBeenCalled(); expect(updateService.updateAlertState).toHaveBeenCalledWith(component.selectedAlerts, 'RESOLVE', false); }); it('should add to alert when selected', () => { component.selectedAlerts.push(testAlert); fixture.detectChanges(); const metaAlertService = TestBed.get(MetaAlertService); const router = TestBed.get(Router); spyOn(component, 'processAddToAlert').and.callThrough(); spyOn(component, 'updateSelectedAlertStatus'); spyOn(router, 'navigateByUrl'); const actionsButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="dropdown-menu-button"'); actionsButton.click(); const processAddToAlertButton = fixture.debugElement.nativeElement.querySelector('[data-qe-id="action-add-to-alert-button"'); processAddToAlertButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(component.processAddToAlert).toHaveBeenCalled(); expect(metaAlertService.selectedAlerts).toEqual(component.selectedAlerts); expect(router.navigateByUrl).toHaveBeenCalledWith('/alerts-list(dialog:add-to-meta-alert)'); }); }); describe('table configuration', () => { it('should reconfigure rows when value is emitted to configRowsChange', () => { const configureTableService = TestBed.get(ConfigureTableService); spyOn(component, 'updatePollingInterval'); spyOn(component, 'search'); spyOn(configureTableService, 'saveTableMetaData').and.callThrough(); component.onConfigRowsChange({ values: { pageSize: 10, refreshInterval: 1000 }, triggerQuery: true }); expect(component.tableMetaData.size).toEqual(10); expect(configureTableService.saveTableMetaData).toHaveBeenCalledWith(component.tableMetaData); expect(component.search).toHaveBeenCalled(); }); }); describe('save/load manual query search', () => { it('should switch to manual mode if the saved search is manual', () => { const saveSearchSvc = TestBed.get(SaveSearchService); const savedSearch = new SaveSearch(); savedSearch.isManual = true; savedSearch.searchRequest = new SearchRequest(); savedSearch.searchRequest.query = 'foo:bar'; savedSearch.filters = []; saveSearchSvc.loadSavedSearch$ = of(savedSearch); const spySetFilteringMode = spyOn(component.queryBuilder, 'setFilteringMode'); const spySetManualQuery = spyOn(component.queryBuilder, 'setManualQuery'); component.addLoadSavedSearchListener(); expect(spySetFilteringMode).toHaveBeenCalledTimes(1); expect(spySetFilteringMode).toHaveBeenCalledWith(FilteringMode.MANUAL); expect(spySetManualQuery).toHaveBeenCalledWith('foo:bar'); }); it('should switch to builder mode if the saved search is not manual', () => { const saveSearchSvc = TestBed.get(SaveSearchService); const savedSearch = new SaveSearch(); savedSearch.isManual = false; savedSearch.searchRequest = new SearchRequest(); savedSearch.searchRequest.query = 'foo:bar'; savedSearch.filters = []; saveSearchSvc.loadSavedSearch$ = of(savedSearch); const spySetFilteringMode = spyOn(component.queryBuilder, 'setFilteringMode'); const spySetManualQuery = spyOn(component.queryBuilder, 'setManualQuery'); component.addLoadSavedSearchListener(); expect(spySetFilteringMode).toHaveBeenCalledTimes(1); expect(spySetFilteringMode).toHaveBeenCalledWith(FilteringMode.BUILDER); expect(spySetManualQuery).not.toHaveBeenCalledWith('foo:bar'); }); it('should save the search filter mode (manual)', (done) => { const saveSearchSvc = TestBed.get(SaveSearchService); saveSearchSvc.saveAsRecentSearches = (saveSearch) => { expect(saveSearch.isManual).toBe(true); expect(saveSearch.searchRequest.query).toBe('foo:bar'); done(); return of(null); }; component.queryBuilder.getFilteringMode = () => FilteringMode.MANUAL; component.queryBuilder.query = 'foo:bar'; component.saveCurrentSearch(); }); it('should save the search filter mode (builder)', (done) => { const saveSearchSvc = TestBed.get(SaveSearchService); saveSearchSvc.saveAsRecentSearches = (saveSearch) => { expect(saveSearch.isManual).toBe(false); expect(saveSearch.searchRequest.query).toBe(''); done(); return of(null); }; component.queryBuilder.getFilteringMode = () => FilteringMode.BUILDER; component.queryBuilder.query = 'foo:bar'; component.saveCurrentSearch(); }); }); });
the_stack
import {Tree, SchematicsException} from '@angular-devkit/schematics'; import {InsertChange, Change} from '@schematics/angular/utility/change'; import {getAppModulePath} from '@schematics/angular/utility/ng-ast-utils'; import * as ts from 'typescript'; import {getMainPath, getTypeScriptSourceFile} from '.'; /** * Import and add module to the root module. * @param host {Tree} The source tree. * @param importedModuleName {String} The name of the imported module. * @param importedModulePath {String} The location of the imported module. * @param projectName {String} The name of the project. */ export function addModuleImportToRootModule( host: Tree, importedModuleName: string, importedModulePath: string, projectName?: string, ) { const mainPath = getMainPath(host, projectName); const appModulePath = getAppModulePath(host, mainPath); addModuleImportToModule( host, appModulePath, importedModuleName, importedModulePath, ); } /** * Import and add module to specific module path. * @param host {Tree} The source tree. * @param moduleToImportIn {String} The location of the module to import in. * @param importedModuleName {String} The name of the imported module. * @param importedModulePath {String} The location of the imported module. */ function addModuleImportToModule( host: Tree, moduleToImportIn: string, importedModuleName: string, importedModulePath: string, ) { const moduleSource = getTypeScriptSourceFile(host, moduleToImportIn); if (!moduleSource) { throw new SchematicsException(`Module not found: ${moduleToImportIn}`); } const changes = addImportToModule( moduleSource, importedModulePath, importedModuleName, ); const recorder = host.beginUpdate(moduleToImportIn); const inserted = insertImport( moduleSource, moduleToImportIn, importedModuleName, importedModulePath, ); if (inserted && inserted instanceof InsertChange) { recorder.insertLeft(inserted.pos, inserted.toAdd); } changes .filter((change: Change) => change instanceof InsertChange) .forEach((change: InsertChange) => recorder.insertLeft(change.pos, change.toAdd), ); host.commitUpdate(recorder); } function addImportToModule( source: ts.SourceFile, modulePath: string, symbolName: string, ): Change[] { return _addSymbolToNgModuleMetadata( source, modulePath, 'imports', symbolName, ); } function _addSymbolToNgModuleMetadata( source: ts.SourceFile, ngModulePath: string, metadataField: string, expression: string, ): Change[] { const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core'); let node: any = nodes[0]; // Find the decorator declaration. if (!node) { return []; } // Get all the children property assignment of object literals. const matchingProperties: ts.ObjectLiteralElement[] = ( node as ts.ObjectLiteralExpression ).properties .filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment) // Filter out every fields that's not "metadataField". Also handles string literals // (but not expressions). .filter((prop: ts.PropertyAssignment) => { const name = prop.name; switch (name.kind) { case ts.SyntaxKind.Identifier: return (name as ts.Identifier).getText(source) == metadataField; case ts.SyntaxKind.StringLiteral: return (name as ts.StringLiteral).text == metadataField; } return false; }); // Get the last node of the array literal. if (!matchingProperties) { return []; } if (matchingProperties.length == 0) { // We haven't found the field in the metadata declaration. Insert a new field. const expr = node as ts.ObjectLiteralExpression; let position: number; let toInsert: string; if (expr.properties.length == 0) { position = expr.getEnd() - 1; toInsert = ` ${metadataField}: [${expression}]\n`; } else { node = expr.properties[expr.properties.length - 1]; position = node.getEnd(); // Get the indentation of the last element, if any. const text = node.getFullText(source); if (text.match('^\r?\r?\n')) { toInsert = `,${ text.match(/^\r?\n\s+/)[0] }${metadataField}: [${expression}]`; } else { toInsert = `, ${metadataField}: [${expression}]`; } } const newMetadataProperty = new InsertChange( ngModulePath, position, toInsert, ); return [newMetadataProperty]; } const assignment = matchingProperties[0] as ts.PropertyAssignment; // If it's not an array, nothing we can do really. if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { return []; } const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression; if (arrLiteral.elements.length == 0) { // Forward the property. node = arrLiteral; } else { node = arrLiteral.elements; } if (!node) { console.log( 'No app module found. Please add your new class to your component.', ); return []; } const isArray = Array.isArray(node); if (isArray) { const nodeArray = node as {} as Array<ts.Node>; const symbolsArray = nodeArray.map((node) => node.getText()); if (symbolsArray.includes(expression)) { return []; } node = node[node.length - 1]; } let toInsert: string; let position = node.getEnd(); if (!isArray && node.kind == ts.SyntaxKind.ObjectLiteralExpression) { // We haven't found the field in the metadata declaration. Insert a new // field. const expr = node as ts.ObjectLiteralExpression; if (expr.properties.length == 0) { position = expr.getEnd() - 1; toInsert = ` ${metadataField}: [${expression}]\n`; } else { node = expr.properties[expr.properties.length - 1]; position = node.getEnd(); // Get the indentation of the last element, if any. const text = node.getFullText(source); if (text.match('^\r?\r?\n')) { toInsert = `,${ text.match(/^\r?\n\s+/)[0] }${metadataField}: [${expression}]`; } else { toInsert = `, ${metadataField}: [${expression}]`; } } } else if (!isArray && node.kind == ts.SyntaxKind.ArrayLiteralExpression) { // We found the field but it's empty. Insert it just before the `]`. position--; toInsert = `${expression}`; } else { // Get the indentation of the last element, if any. const text = node.getFullText(source); if (text.match(/^\r?\n/)) { toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${expression}`; } else { toInsert = `, ${expression}`; } } const insert = new InsertChange(ngModulePath, position, toInsert); return [insert]; } function getDecoratorMetadata( source: ts.SourceFile, identifier: string, module: string, ): ts.Node[] { const angularImports: {[name: string]: string} = findNodes( source, ts.SyntaxKind.ImportDeclaration, ) .map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, source)) .reduce( (acc: {[name: string]: string}, current: {[name: string]: string}) => { for (const key of Object.keys(current)) { acc[key] = current[key]; } return acc; }, {}, ); return getSourceNodes(source) .filter((node) => { return ( node.kind == ts.SyntaxKind.Decorator && (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression ); }) .map((node) => (node as ts.Decorator).expression as ts.CallExpression) .filter((expr) => { if (expr.expression.kind == ts.SyntaxKind.Identifier) { const id = expr.expression as ts.Identifier; return ( id.getFullText(source) == identifier && angularImports[id.getFullText(source)] === module ); } else if ( expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression ) { // This covers foo.NgModule when importing * as foo. const paExpr = expr.expression as ts.PropertyAccessExpression; // If the left expression is not an identifier, just give up at that point. if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) { return false; } const id = paExpr.name.text; const moduleId = (paExpr.expression as ts.Identifier).getText(source); return id === identifier && angularImports[moduleId + '.'] === module; } return false; }) .filter( (expr) => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression, ) .map((expr) => expr.arguments[0] as ts.ObjectLiteralExpression); } function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] { const nodes: ts.Node[] = [sourceFile]; const result = []; while (nodes.length > 0) { const node = nodes.shift(); if (node) { result.push(node); if (node.getChildCount(sourceFile) >= 0) { nodes.unshift(...node.getChildren()); } } } return result; } function findNodes( node: ts.Node, kind: ts.SyntaxKind | ts.SyntaxKind[], max = Infinity, ): ts.Node[] { if (!node || max == 0) { return []; } const arr: ts.Node[] = []; const hasMatch = Array.isArray(kind) ? kind.includes(node.kind) : node.kind === kind; if (hasMatch) { arr.push(node); max--; } if (max > 0) { for (const child of node.getChildren()) { findNodes(child, kind, max).forEach((node) => { if (max > 0) { arr.push(node); } max--; }); if (max <= 0) { break; } } } return arr; } function _angularImportsFromNode( node: ts.ImportDeclaration, _sourceFile: ts.SourceFile, ): {[name: string]: string} { const ms = node.moduleSpecifier; let modulePath: string; switch (ms.kind) { case ts.SyntaxKind.StringLiteral: modulePath = (ms as ts.StringLiteral).text; break; default: return {}; } if (!modulePath.startsWith('@angular/')) { return {}; } if (node.importClause) { if (node.importClause.name) { // This is of the form `import Name from 'path'`. Ignore. return {}; } else if (node.importClause.namedBindings) { const nb = node.importClause.namedBindings; if (nb.kind == ts.SyntaxKind.NamespaceImport) { // This is of the form `import * as name from 'path'`. Return `name.`. return { [(nb as ts.NamespaceImport).name.text + '.']: modulePath, }; } else { // This is of the form `import {a,b,c} from 'path'` const namedImports = nb as ts.NamedImports; return namedImports.elements .map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text, ) .reduce((acc: {[name: string]: string}, curr: string) => { acc[curr] = modulePath; return acc; }, {}); } } return {}; } else { // This is of the form `import 'path';`. Nothing to do. return {}; } } export function insertImport( source: ts.SourceFile, fileToEdit: string, symbolName: string, fileName: string, isDefault = false, ) { const rootNode = source; const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration); // get nodes that map to import statements from the file fileName const relevantImports = allImports.filter((node) => { // StringLiteral of the ImportDeclaration is the import file (fileName in this case). const importFiles = node .getChildren() .filter((child) => child.kind === ts.SyntaxKind.StringLiteral) .map((n) => (n as ts.StringLiteral).text); return importFiles.filter((file) => file === fileName).length === 1; }); if (relevantImports.length > 0) { let importsAsterisk = false; // imports from import file const imports: ts.Node[] = []; relevantImports.forEach((n) => { Array.prototype.push.apply( imports, findNodes(n, ts.SyntaxKind.Identifier), ); if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) { importsAsterisk = true; } }); // if imports * from fileName, don't add symbolName if (importsAsterisk) { return null; } const importTextNodes = imports.filter( (n) => (n as ts.Identifier).text === symbolName, ); // insert import if it's not there if (importTextNodes.length === 0) { const fallbackPos = findNodes( relevantImports[0], ts.SyntaxKind.CloseBraceToken, )[0].getStart() || findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart(); return insertAfterLastOccurrence( imports, `, ${symbolName}`, fileToEdit, fallbackPos, ); } return null; } // no such import declaration exists const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral).filter( (n: ts.StringLiteral) => n.text === 'use strict', ); let fallbackPos = 0; if (useStrict.length > 0) { fallbackPos = useStrict[0].end; } const open = isDefault ? '' : '{ '; const close = isDefault ? '' : ' }'; // if there are no imports or 'use strict' statement, insert import at beginning of file const insertAtBeginning = allImports.length === 0 && useStrict.length === 0; const separator = insertAtBeginning ? '' : ';\n'; const toInsert = `${separator}import ${open}${symbolName}${close}` + ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`; return insertAfterLastOccurrence( allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral, ); } function insertAfterLastOccurrence( nodes: ts.Node[], toInsert: string, file: string, fallbackPos: number, syntaxKind?: ts.SyntaxKind, ): Change { // sort() has a side effect, so make a copy so that we won't overwrite the parent's object. let lastItem = [...nodes].sort(nodesByPosition).pop(); if (!lastItem) { throw new Error(); } if (syntaxKind) { lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop(); } if (!lastItem && fallbackPos == undefined) { throw new Error( `tried to insert ${toInsert} as first occurrence with no fallback position`, ); } const lastItemPosition: number = lastItem ? lastItem.getEnd() : fallbackPos; return new InsertChange(file, lastItemPosition, toInsert); } function nodesByPosition(first: ts.Node, second: ts.Node): number { return first.getStart() - second.getStart(); }
the_stack
import AnchoredOperationModel from '../../models/AnchoredOperationModel'; import CreateOperation from './CreateOperation'; import DeactivateOperation from './DeactivateOperation'; import DidState from '../../models/DidState'; import DocumentComposer from './DocumentComposer'; import Encoder from './Encoder'; import ErrorCode from './ErrorCode'; import IOperationProcessor from '../../interfaces/IOperationProcessor'; import JsObject from './util/JsObject'; import JsonCanonicalizer from './util/JsonCanonicalizer'; import Logger from '../../../common/Logger'; import Multihash from './Multihash'; import Operation from './Operation'; import OperationType from '../../enums/OperationType'; import RecoverOperation from './RecoverOperation'; import SidetreeError from '../../../common/SidetreeError'; import UpdateOperation from './UpdateOperation'; /** * Implementation of IOperationProcessor. */ export default class OperationProcessor implements IOperationProcessor { public async apply ( anchoredOperationModel: AnchoredOperationModel, didState: DidState | undefined ): Promise<DidState | undefined> { // If DID state is undefined, then the operation given must be a create operation, otherwise the operation cannot be applied. if (didState === undefined && anchoredOperationModel.type !== OperationType.Create) { return undefined; } const previousOperationTransactionNumber = didState ? didState.lastOperationTransactionNumber : undefined; let appliedDidState: DidState | undefined; if (anchoredOperationModel.type === OperationType.Create) { appliedDidState = await this.applyCreateOperation(anchoredOperationModel, didState); } else if (anchoredOperationModel.type === OperationType.Update) { appliedDidState = await this.applyUpdateOperation(anchoredOperationModel, didState!); } else if (anchoredOperationModel.type === OperationType.Recover) { appliedDidState = await this.applyRecoverOperation(anchoredOperationModel, didState!); } else if (anchoredOperationModel.type === OperationType.Deactivate) { appliedDidState = await this.applyDeactivateOperation(anchoredOperationModel, didState!); } else { throw new SidetreeError(ErrorCode.OperationProcessorUnknownOperationType); } try { // If the operation was not applied, log some info in case needed for debugging. if (appliedDidState === undefined || appliedDidState.lastOperationTransactionNumber === previousOperationTransactionNumber) { const index = anchoredOperationModel.operationIndex; const time = anchoredOperationModel.transactionTime; const number = anchoredOperationModel.transactionNumber; const didUniqueSuffix = anchoredOperationModel.didUniqueSuffix; Logger.info(`Ignored invalid operation for DID '${didUniqueSuffix}' in transaction '${number}' at time '${time}' at operation index ${index}.`); } } catch (error) { Logger.info(`Failed logging ${error}.`); // If logging fails, just move on. } return appliedDidState; } public async getMultihashRevealValue (anchoredOperationModel: AnchoredOperationModel): Promise<Buffer> { if (anchoredOperationModel.type === OperationType.Create) { throw new SidetreeError(ErrorCode.OperationProcessorCreateOperationDoesNotHaveRevealValue); } const operation = await Operation.parse(anchoredOperationModel.operationBuffer); const multihashRevealValue = (operation as RecoverOperation | UpdateOperation | DeactivateOperation).revealValue; const multihashRevealValueBuffer = Encoder.decodeAsBuffer(multihashRevealValue); return multihashRevealValueBuffer; } /** * @returns new DID state if operation is applied successfully; the given DID state otherwise. */ private async applyCreateOperation ( anchoredOperationModel: AnchoredOperationModel, didState: DidState | undefined ): Promise<DidState | undefined> { // If DID state is already created by a previous create operation, then we cannot apply a create operation again. if (didState !== undefined) { return didState; } // When delta parsing fails, operation.delta is undefined. const operation = await CreateOperation.parse(anchoredOperationModel.operationBuffer); const newDidState: DidState = { document: { }, nextRecoveryCommitmentHash: operation.suffixData.recoveryCommitment, nextUpdateCommitmentHash: undefined, lastOperationTransactionNumber: anchoredOperationModel.transactionNumber }; if (operation.delta === undefined) { return newDidState; } // Verify the delta hash against the expected delta hash. const deltaPayload = JsonCanonicalizer.canonicalizeAsBuffer(operation.delta); // If code execution gets to this point, delta is defined. const isMatchingDelta = Multihash.verifyEncodedMultihashForContent(deltaPayload, operation.suffixData.deltaHash); if (!isMatchingDelta) { return newDidState; }; // Apply the given patches against an empty object. const delta = operation.delta; // Update the commitment hash regardless of patch application outcome. newDidState.nextUpdateCommitmentHash = delta.updateCommitment; try { const document = { }; DocumentComposer.applyPatches(document, delta.patches); newDidState.document = document; } catch (error) { const didUniqueSuffix = anchoredOperationModel.didUniqueSuffix; const transactionNumber = anchoredOperationModel.transactionNumber; Logger.info( `Partial update on next commitment hash applied because: ` + `Unable to apply delta patches for transaction number ${transactionNumber} for DID ${didUniqueSuffix}: ${SidetreeError.stringify(error)}.`); } return newDidState; } /** * @returns new DID state if operation is applied successfully; the given DID state otherwise. */ private async applyUpdateOperation ( anchoredOperationModel: AnchoredOperationModel, didState: DidState ): Promise<DidState> { const operation = await UpdateOperation.parse(anchoredOperationModel.operationBuffer); // Verify the update key hash. const isValidUpdateKey = Multihash.canonicalizeAndVerifyDoubleHash(operation.signedData.updateKey, didState.nextUpdateCommitmentHash!); if (!isValidUpdateKey) { return didState; } // Verify the signature. const signatureIsValid = await operation.signedDataJws.verifySignature(operation.signedData.updateKey); if (!signatureIsValid) { return didState; } if (operation.delta === undefined) { return didState; } // Verify the delta hash against the expected delta hash. const deltaPayload = JsonCanonicalizer.canonicalizeAsBuffer(operation.delta); const isMatchingDelta = Multihash.verifyEncodedMultihashForContent(deltaPayload, operation.signedData.deltaHash); if (!isMatchingDelta) { return didState; }; // Passed all verifications, must update the update commitment value even if the application of patches fail. const newDidState = { nextRecoveryCommitmentHash: didState.nextRecoveryCommitmentHash, document: didState.document, nextUpdateCommitmentHash: operation.delta.updateCommitment, lastOperationTransactionNumber: anchoredOperationModel.transactionNumber }; try { // NOTE: MUST pass DEEP COPY of the DID Document to `DocumentComposer` such that in the event of a patch failure, // the original document is not modified. const documentDeepCopy = JsObject.deepCopyObject(didState.document); DocumentComposer.applyPatches(documentDeepCopy, operation.delta.patches); newDidState.document = documentDeepCopy; } catch (error) { const didUniqueSuffix = anchoredOperationModel.didUniqueSuffix; const transactionNumber = anchoredOperationModel.transactionNumber; Logger.info(`Unable to apply document patch in transaction number ${transactionNumber} for DID ${didUniqueSuffix}: ${SidetreeError.stringify(error)}.`); } return newDidState; } /** * @returns new DID state if operation is applied successfully; the given DID state otherwise. */ private async applyRecoverOperation ( anchoredOperationModel: AnchoredOperationModel, didState: DidState ): Promise<DidState> { // When delta parsing fails, operation.delta is undefined. const operation = await RecoverOperation.parse(anchoredOperationModel.operationBuffer); // Verify the recovery key hash. const isValidRecoveryKey = Multihash.canonicalizeAndVerifyDoubleHash(operation.signedData.recoveryKey, didState.nextRecoveryCommitmentHash!); if (!isValidRecoveryKey) { return didState; } // Verify the signature. const signatureIsValid = await operation.signedDataJws.verifySignature(operation.signedData.recoveryKey); if (!signatureIsValid) { return didState; } const newDidState: DidState = { nextRecoveryCommitmentHash: operation.signedData.recoveryCommitment, document: { }, nextUpdateCommitmentHash: undefined, lastOperationTransactionNumber: anchoredOperationModel.transactionNumber }; if (operation.delta === undefined) { return newDidState; } // Verify the delta hash against the expected delta hash. const deltaPayload = JsonCanonicalizer.canonicalizeAsBuffer(operation.delta); const isMatchingDelta = Multihash.verifyEncodedMultihashForContent(deltaPayload, operation.signedData.deltaHash); if (!isMatchingDelta) { return newDidState; }; // Apply the given patches against an empty object. const delta = operation.delta; // update the commitment hash regardless newDidState.nextUpdateCommitmentHash = delta.updateCommitment; try { const document = { }; DocumentComposer.applyPatches(document, delta.patches); newDidState.document = document; } catch (error) { const didUniqueSuffix = anchoredOperationModel.didUniqueSuffix; const transactionNumber = anchoredOperationModel.transactionNumber; Logger.info( `Partial update on next commitment hash applied because: ` + `Unable to apply delta patches for transaction number ${transactionNumber} for DID ${didUniqueSuffix}: ${SidetreeError.stringify(error)}.`); } return newDidState; } /** * @returns new DID state if operation is applied successfully; the given DID state otherwise. */ private async applyDeactivateOperation ( anchoredOperationModel: AnchoredOperationModel, didState: DidState ): Promise<DidState> { const operation = await DeactivateOperation.parse(anchoredOperationModel.operationBuffer); // Verify the recovery key hash. const isValidRecoveryKey = Multihash.canonicalizeAndVerifyDoubleHash(operation.signedData.recoveryKey, didState.nextRecoveryCommitmentHash!); if (!isValidRecoveryKey) { return didState; } // Verify the signature. const signatureIsValid = await operation.signedDataJws.verifySignature(operation.signedData.recoveryKey); if (!signatureIsValid) { return didState; } // The operation passes all checks. const newDidState = { document: didState.document, // New values below. nextRecoveryCommitmentHash: undefined, nextUpdateCommitmentHash: undefined, lastOperationTransactionNumber: anchoredOperationModel.transactionNumber }; return newDidState; } }
the_stack
import type {Output} from "@swim/codec"; import {Item, Attr, Slot, Value, Record, Text, Num} from "@swim/structure"; import {Converter} from "./Converter"; /** @public */ export class CssConverter extends Converter { override convert<O>(output: Output<O>, model: Item): O { if (model instanceof Record) { output = this.writeStylesheet(output, model); } else if (model instanceof Text) { output = output.write(model.value); } return output.bind(); } writeStylesheet<O>(output: Output<O>, stylesheet: Record): Output<O> { if (stylesheet.tag !== void 0) { output = this.writeBlock(output, stylesheet); } else { for (let i = 0, n = stylesheet.length; i < n; i += 1) { const item = stylesheet.getItem(i); if (item instanceof Record) { output = this.writeBlock(output, item); } } } return output; } writeBlock<O>(output: Output<O>, block: Record): Output<O> { const head = block.head(); if (head instanceof Attr) { const tag = head.key.value; if (tag === "rule") { output = this.writeRuleset(output, Value.absent(), head.value, block.tail().branch()); } else if (tag === "media") { output = this.writeRuleset(output, head.value, Value.absent(), block.tail().branch()); } } else { output = this.writeStylesheet(output, block); } return output; } writeRuleset<O>(output: Output<O>, mediaQueries: Value, selectors: Value, declarations: Value): Output<O> { let inMedia = false; let inRule = false; let isEmpty = true; if (declarations instanceof Record) { for (let i = 0, n = declarations.length; i < n; i += 1) { const declaration = declarations.getItem(i); const head = declaration.head(); if (head instanceof Attr) { const tag = head.key.value; if (tag === "rule") { if (inRule) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inRule = false; } if (inMedia) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inMedia = false; } output = this.writeRuleset(output, mediaQueries, this.nestedSelector(selectors, head.value), declaration.tail().branch()); isEmpty = false; } else if (tag === "media") { if (inRule) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inRule = false; } if (inMedia) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inMedia = false; } output = this.writeRuleset(output, this.nestedMediaQuery(mediaQueries, head.value), selectors, declaration.tail().branch()); isEmpty = false; } } else if (declaration instanceof Slot) { if (!inMedia && mediaQueries.isDistinct()) { output = output.write(64/*'@'*/); output = output.write("media"); output = output.write(32/*' '*/); output = this.writeMediaQueries(output, mediaQueries); output = output.write(32/*' '*/); output = output.write(123/*'{'*/); output = output.write(10/*'\n'*/); inMedia = true; isEmpty = false; } if (!inRule) { output = this.writeSelectors(output, selectors); output = output.write(32/*' '*/); output = output.write(123/*'{'*/); output = output.write(10/*'\n'*/); inRule = true; isEmpty = false; } output = this.writeDeclaration(output, declaration.key, declaration.value); } else if (declaration instanceof Record && !declaration.isEmpty()) { if (declaration.fieldCount === 0) { if (inRule) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inRule = false; } if (inMedia) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inMedia = false; } output = this.writeRuleset(output, mediaQueries, selectors, declaration); isEmpty = false; } else { if (!inMedia && mediaQueries.isDistinct()) { output = output.write(64/*'@'*/); output = output.write("media"); output = output.write(32/*' '*/); output = this.writeMediaQueries(output, mediaQueries); output = output.write(32/*' '*/); output = output.write(123/*'{'*/); output = output.write(10/*'\n'*/); inMedia = true; isEmpty = false; } if (!inRule) { output = this.writeSelectors(output, selectors); output = output.write(32/*' '*/); output = output.write(123/*'{'*/); output = output.write(10/*'\n'*/); inRule = true; isEmpty = false; } output = this.writeDeclarations(output, declaration); } } } } if (isEmpty && mediaQueries.isDistinct()) { output = output.write(64/*'@'*/); output = output.write("media"); output = output.write(32/*' '*/); output = this.writeMediaQueries(output, mediaQueries); output = output.write(32/*' '*/); output = output.write(123/*'{'*/); output = output.write(10/*'\n'*/); inMedia = true; isEmpty = false; } if (inRule) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inRule = false; } if (inMedia) { output = output.write(125/*'}'*/); output = output.write(10/*'\n'*/); inMedia = false; } return output; } nestedMediaQuery(mediaQueries: Value, subMediaQueries: Value): Value { if (mediaQueries.isDistinct()) { return Record.create(3).attr("and").item(mediaQueries).item(subMediaQueries); } else { return subMediaQueries; } } writeMediaQueries<O>(output: Output<O>, mediaQueries: Value): Output<O> { if (mediaQueries instanceof Record) { output = this.writeMediaExpression(output, mediaQueries); } else { output = this.writeMediaQuery(output, mediaQueries); } return output; } writeMediaExpression<O>(output: Output<O>, mediaExpression: Record): Output<O> { const tag = mediaExpression.tag; if (tag === "and") { output = this.writeMediaAnd(output, mediaExpression.tail().branch()); } else if (tag === "not") { output = this.writeMediaNot(output, mediaExpression.tail().branch()); } else { for (let i = 0, n = mediaExpression.length; i < n; i += 1) { const mediaQuery = mediaExpression.getItem(i); if (i !== 0) { output = output.write(44/*','*/); output = output.write(32/*' '*/); } output = this.writeMediaQuery(output, mediaQuery); } } return output; } writeMediaQuery<O>(output: Output<O>, mediaQuery: Item): Output<O> { if (mediaQuery instanceof Slot) { output = output.write(40/*'('*/); output = this.writeMediaFeature(output, mediaQuery.key, mediaQuery.value); output = output.write(41/*')'*/); } else if (mediaQuery instanceof Record) { output = this.writeMediaExpression(output, mediaQuery); } else { output = output.write(mediaQuery.stringValue("")); } return output; } writeMediaAnd<O>(output: Output<O>, mediaQuery: Record): Output<O> { for (let i = 0, n = mediaQuery.length; i < n; i += 1) { const medium = mediaQuery.getItem(i); if (i !== 0) { output = output.write(32/*' '*/); output = output.write("and"); output = output.write(32/*' '*/); } output = this.writeMediaQuery(output, medium); } return output; } writeMediaNot<O>(output: Output<O>, mediaQuery: Record): Output<O> { output = output.write("not"); output = output.write(32/*' '*/); const n = mediaQuery.length; if (n === 1) { output = output.write(40/*'('*/); } for (let i = 0; i < n; i += 1) { const medium = mediaQuery.getItem(i); output = this.writeMediaQuery(output, medium); } if (n === 1) { output = output.write(41/*')'*/); } return output; } writeMediaFeature<O>(output: Output<O>, name: Value, value: Value): Output<O> { output = output.write(name.stringValue("")); output = output.write(58/*':'*/); output = output.write(32/*' '*/); if (value instanceof Num) { output = output.write(value.value + "px"); } else { output = output.write(value.stringValue("")); } return output; } nestedSelector(selectors: Value, subSelectors: Value): Value { if (selectors.isDistinct()) { const nested = Record.create(); selectors.forEach(function (selector: Item): void { subSelectors.forEach(function (subselector: Item): void { nested.push(selector.stringValue() + " " + subselector.stringValue()); }, this); }, this); return nested; } else { return subSelectors; } } writeSelectors<O>(output: Output<O>, selectors: Value): Output<O> { if (selectors instanceof Record) { for (let i = 0, n = selectors.length; i < n; i += 1) { const selector = selectors.getItem(i); if (i !== 0) { output = output.write(44/*','*/); output = output.write(10/*'\n'*/); } output = this.writeSelector(output, selector); } } else { output = this.writeSelector(output, selectors); } return output; } writeSelector<O>(output: Output<O>, selector: Value): Output<O> { output = output.write(selector.stringValue("")); return output; } writeDeclarations<O>(output: Output<O>, declarations: Record): Output<O> { for (let i = 0, n = declarations.length; i < n; i += 1) { const declaration = declarations.getItem(i); if (declaration instanceof Slot) { output = this.writeDeclaration(output, declaration.key, declaration.value); } else if (declaration instanceof Record) { output = this.writeDeclarations(output, declaration); } } return output; } writeDeclaration<O>(output: Output<O>, property: Value, expression: Value): Output<O> { output = this.writeProperty(output, property); output = output.write(58/*':'*/); output = output.write(32/*' '*/); output = this.writeExpression(output, expression); output = output.write(59/*';'*/); output = output.write(10/*'\n'*/); return output; } writeProperty<O>(output: Output<O>, property: Value): Output<O> { output = output.write(property.stringValue("")); return output; } writeExpression<O>(output: Output<O>, expression: Value): Output<O> { output = output.write(expression.stringValue("")); return output; } }
the_stack
import { Actor, Animation, AssetContainer, AssetLike, AssetUserType, Color3, Color3Like, Color4, Color4Like, Guid, Vector2, Vector2Like, ZeroGuid } from '..'; import { observe, Patchable, readPath } from '../internal'; import { AssetInternal } from './assetInternal'; // break import cycle import { Asset } from './asset'; /** * Describes the properties of a Material. */ export interface MaterialLike { /** The base color of this material. */ color: Partial<Color4Like>; /** The main (albedo) texture asset ID */ mainTextureId: Guid; /** The main texture's offset from default */ mainTextureOffset: Vector2Like; /** The main texture's scale from default */ mainTextureScale: Vector2Like; /** The lighting-independent color of this material. */ emissiveColor: Partial<Color3Like>; /** The emissive (unlit) texture asset ID */ emissiveTextureId: Guid; /** The emissive texture's offset from default */ emissiveTextureOffset: Vector2Like; /** The emissive texture's scale from default */ emissiveTextureScale: Vector2Like; /** How the color/texture's alpha channel should be handled */ alphaMode: AlphaMode; /** Visibility threshold in masked alpha mode */ alphaCutoff: number; } /** * Controls how transparency is handled. */ export enum AlphaMode { /** The object is rendered opaque, and transparency info is discarded. */ Opaque = 'opaque', /** * Any parts with alpha above a certain cutoff ([[Material.alphaCutoff]]) * will be rendered solid. Everything else is fully transparent. */ Mask = 'mask', /** * A pixel's transparency is directly proportional to its alpha value. */ Blend = 'blend' } /** * Represents a material on a mesh. */ export class Material extends Asset implements MaterialLike, Patchable<AssetLike> { private _color = Color4.FromColor3(Color3.White(), 1.0); private _mainTextureId = ZeroGuid; private _mainTextureOffset = Vector2.Zero(); private _mainTextureScale = Vector2.One(); private _emissiveColor = Color3.Black(); private _emissiveTextureId = ZeroGuid; private _emissiveTextureOffset = Vector2.Zero(); private _emissiveTextureScale = Vector2.One(); private _alphaMode = AlphaMode.Opaque; private _alphaCutoff = 0.5; private _internal = new AssetInternal(this); /** @hidden */ public get internal() { return this._internal; } /** @inheritdoc */ public get color() { return this._color; } public set color(value) { if (value) { this._color.copy(value); } } /** @returns A shared reference to this material's texture asset */ public get mainTexture() { return this.container.context.internal.lookupAsset(this._mainTextureId)?.texture; } public set mainTexture(value) { this.mainTextureId = value?.id ?? ZeroGuid; } /** @inheritdoc */ public get mainTextureId() { return this._mainTextureId; } public set mainTextureId(value) { if (!value) { value = ZeroGuid; } if (!this.container.context.internal.lookupAsset(value)) { value = ZeroGuid; // throw? } if (value === this._mainTextureId) { return; } if (this.mainTexture) { this.mainTexture.clearReference(this); } this._mainTextureId = value; if (this.mainTexture) { this.mainTexture.addReference(this); } this.materialChanged('mainTextureId'); } /** @inheritdoc */ public get mainTextureOffset() { return this._mainTextureOffset; } public set mainTextureOffset(value) { if (value) { this._mainTextureOffset.copy(value); } } /** @inheritdoc */ public get mainTextureScale() { return this._mainTextureScale; } public set mainTextureScale(value) { if (value) { this._mainTextureScale.copy(value); } } /** @inheritdoc */ public get emissiveColor() { return this._emissiveColor; } public set emissiveColor(value) { if (value) { this._emissiveColor.copy(value); } } /** @returns A shared reference to this material's texture asset */ public get emissiveTexture() { return this.container.context.internal.lookupAsset(this._emissiveTextureId)?.texture; } public set emissiveTexture(value) { this.emissiveTextureId = value?.id ?? ZeroGuid; } /** @inheritdoc */ public get emissiveTextureId() { return this._emissiveTextureId; } public set emissiveTextureId(value) { if (!value) { value = ZeroGuid; } if (!this.container.context.internal.lookupAsset(value)) { value = ZeroGuid; // throw? } if (value === this._emissiveTextureId) { return; } if (this.emissiveTexture) { this.emissiveTexture.clearReference(this); } this._emissiveTextureId = value; if (this.emissiveTexture) { this.emissiveTexture.addReference(this); } this.materialChanged('emissiveTextureId'); } /** @inheritdoc */ public get emissiveTextureOffset() { return this._emissiveTextureOffset; } public set emissiveTextureOffset(value) { if (value) { this._emissiveTextureOffset.copy(value); } } /** @inheritdoc */ public get emissiveTextureScale() { return this._emissiveTextureScale; } public set emissiveTextureScale(value) { if (value) { this._emissiveTextureScale.copy(value); } } /** @inheritdoc */ public get alphaMode() { return this._alphaMode; } public set alphaMode(value) { this._alphaMode = value; this.materialChanged('alphaMode'); } /** @inheritdoc */ public get alphaCutoff() { return this._alphaCutoff; } public set alphaCutoff(value) { this._alphaCutoff = value; this.materialChanged('alphaCutoff'); } /** @inheritdoc */ public get material(): Material { return this; } /** The list of animations that target this actor, by ID. */ /* public get targetingAnimations() { return this.container.context.animations .filter(anim => anim.targetIds.includes(this.id)) .reduce( (map, anim) => { map.set(anim.id, anim); return map; }, new Map<Guid, Animation>() ) as ReadonlyMap<Guid, Animation>; }*/ /** The list of animations that target this actor, by name. */ /* public get targetingAnimationsByName() { return this.container.context.animations .filter(anim => anim.targetIds.includes(this.id) && anim.name) .reduce( (map, anim) => { map.set(anim.name, anim); return map; }, new Map<string, Animation>() ) as ReadonlyMap<string, Animation>; }*/ /** INTERNAL USE ONLY. To create a new material from scratch, use [[AssetManager.createMaterial]]. */ public constructor(container: AssetContainer, def: AssetLike) { super(container, def); if (!def.material) { throw new Error("Cannot construct material from non-material definition"); } this.copy(def); // material patching: observe the nested material properties // for changed values, and write them to a patch observe({ target: this._color, targetName: 'color', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); observe({ target: this._mainTextureOffset, targetName: 'mainTextureOffset', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); observe({ target: this._mainTextureScale, targetName: 'mainTextureScale', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); observe({ target: this._emissiveColor, targetName: 'emissiveColor', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); observe({ target: this._emissiveTextureOffset, targetName: 'emissiveTextureOffset', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); observe({ target: this._emissiveTextureScale, targetName: 'emissiveTextureScale', notifyChanged: (...path: string[]) => this.materialChanged(...path) }); } public copy(from: Partial<AssetLike>): this { if (!from) { return this; } // Pause change detection while we copy the values into the actor. const wasObserving = this.internal.observing; this.internal.observing = false; super.copy(from); if (from.material) { if (from.material.color) { this.color.copy(from.material.color); } if (from.material.mainTextureOffset) { this.mainTextureOffset.copy(from.material.mainTextureOffset); } if (from.material.mainTextureScale) { this.mainTextureScale.copy(from.material.mainTextureScale); } if (from.material.mainTextureId) { this.mainTextureId = from.material.mainTextureId; } if (from.material.emissiveColor) { this.emissiveColor.copy(from.material.emissiveColor); } if (from.material.emissiveTextureOffset) { this.emissiveTextureOffset.copy(from.material.emissiveTextureOffset); } if (from.material.emissiveTextureScale) { this.emissiveTextureScale.copy(from.material.emissiveTextureScale); } if (from.material.emissiveTextureId) { this.emissiveTextureId = from.material.emissiveTextureId; } if (from.material.alphaMode) { this.alphaMode = from.material.alphaMode; } if (from.material.alphaCutoff) { this.alphaCutoff = from.material.alphaCutoff; } } this.internal.observing = wasObserving; return this; } /** @hidden */ public toJSON(): AssetLike { return { ...super.toJSON(), material: { color: this.color.toJSON(), mainTextureId: this.mainTextureId, mainTextureOffset: this.mainTextureOffset.toJSON(), mainTextureScale: this.mainTextureScale.toJSON(), emissiveColor: this.emissiveColor.toJSON(), emissiveTextureId: this.emissiveTextureId, emissiveTextureOffset: this.emissiveTextureOffset.toJSON(), emissiveTextureScale: this.emissiveTextureScale.toJSON(), alphaMode: this.alphaMode, alphaCutoff: this.alphaCutoff } }; } private materialChanged(...path: string[]): void { if (this.internal.observing) { this.container.context.internal.incrementGeneration(); this.internal.patch = this.internal.patch || { material: {} } as AssetLike; readPath(this, this.internal.patch.material, ...path); } } /** @hidden */ public breakReference(ref: AssetUserType) { if (ref instanceof Actor && ref.appearance.material === this) { ref.appearance.material = null; } else if (ref instanceof Animation && ref.isOrphan()) { ref.delete(); } } }
the_stack
import { createRun } from '../../../utils/testhelper'; import HomeReducer, { HomeState, mergeTo, mergeWithSeparatePool } from '../Home.state'; const defaultHomeParameters = { _order: '-ts_epoch', _limit: '30', _group_limit: '30', status: 'completed,failed,running', }; const EmptyState: HomeState = { initialised: false, showLoader: false, page: 1, isLastPage: false, rungroups: {}, newRuns: [], params: defaultHomeParameters, placeHolderParameters: null, isScrolledFromTop: false, }; describe('Home.state', () => { it('HomeReducer', () => { expect(HomeReducer(EmptyState, { type: 'setPage', page: 1 })).to.eql(EmptyState); }); it('HomeReducer - setPage', () => { expect(HomeReducer(EmptyState, { type: 'setPage', page: 2 })).to.eql({ ...EmptyState, page: 2 }); expect(HomeReducer(EmptyState, { type: 'setPage', page: 99 })).to.eql({ ...EmptyState, page: 99 }); // Placeholder parameters should cleared expect( HomeReducer({ ...EmptyState, placeHolderParameters: { _limit: '1', _page: '1' } }, { type: 'setPage', page: 2 }), ).to.eql({ ...EmptyState, page: 2 }); }); it('HomeReducer - setLastPage', () => { expect(HomeReducer(EmptyState, { type: 'setLastPage', isLast: true })).to.eql({ ...EmptyState, isLastPage: true }); expect(HomeReducer({ ...EmptyState, isLastPage: true }, { type: 'setLastPage', isLast: false })).to.eql(EmptyState); }); it('HomeReducer - setLoader', () => { expect(HomeReducer(EmptyState, { type: 'setLoader', show: true })).to.eql({ ...EmptyState, showLoader: true }); expect(HomeReducer({ ...EmptyState, showLoader: true }, { type: 'setLoader', show: false })).to.eql(EmptyState); }); it('HomeReducer - setParams', () => { // Activates loader. and page should jump to 1 expect( HomeReducer( { ...EmptyState, page: 2 }, { type: 'setParams', params: { ...defaultHomeParameters, flow_id: 'TestFlow' }, cachedResult: false }, ), ).to.eql({ ...EmptyState, params: { ...EmptyState.params, flow_id: 'TestFlow' }, placeHolderParameters: null, page: 1, showLoader: true, initialised: true, }); // When cached result is true, we are loading more recent content using placeholder params expect( HomeReducer( { ...EmptyState, page: 2 }, { type: 'setParams', params: { flow_id: 'TestFlow', _limit: '10' }, cachedResult: true }, ), ).to.eql({ ...EmptyState, params: { flow_id: 'TestFlow', _limit: '10' }, placeHolderParameters: { _limit: '20', _page: '1' }, page: 2, showLoader: true, initialised: true, }); // When reordering, page keeps on current page, placeholder params will load whole batch. expect( HomeReducer( { ...EmptyState, page: 2, params: { _order: '+flow_id', _limit: '10' } }, { type: 'setParams', params: { _order: '-flow_id', _limit: '10' }, cachedResult: false }, ), ).to.eql({ ...EmptyState, params: { _limit: '10', _order: '-flow_id' }, placeHolderParameters: { _limit: '20', _page: '1' }, page: 2, showLoader: true, initialised: true, }); }); it('HomeReducer - data', () => { // Run gets assigned to 'undefined' group when grouping is not set expect(HomeReducer(EmptyState, { type: 'data', data: [createRun({})], replace: false })).to.eql({ ...EmptyState, rungroups: { undefined: [createRun({})] }, }); // Replace parameter clears old data expect( HomeReducer( { ...EmptyState, rungroups: { undefined: [createRun({})] }, }, { type: 'data', data: [createRun({ run_number: 999 })], replace: true }, ), ).to.eql({ ...EmptyState, rungroups: { undefined: [createRun({ run_number: 999 })] }, }); // Without replace add to array expect( HomeReducer( { ...EmptyState, rungroups: { undefined: [createRun({})] }, }, { type: 'data', data: [createRun({ run_number: 999 })], replace: false }, ), ).to.eql({ ...EmptyState, rungroups: { undefined: [createRun({}), createRun({ run_number: 999 })] }, }); // Clear newruns section if replacing expect( HomeReducer( { ...EmptyState, newRuns: [createRun({})], }, { type: 'data', data: [], replace: true }, ), ).to.eql({ ...EmptyState, newRuns: [], }); }); it('HomeReducer - realtimeData', () => { // When isScrolledFromTop is false and no grouping, just add data to run groups expect(HomeReducer(EmptyState, { type: 'realtimeData', data: [createRun({})] })).to.eql({ ...EmptyState, rungroups: { undefined: [createRun({})], }, }); // When scrolled from top, we dont want to cause layout shift so add data to separate pool. expect( HomeReducer( { ...EmptyState, isScrolledFromTop: true, }, { type: 'realtimeData', data: [createRun({})] }, ), ).to.eql({ ...EmptyState, isScrolledFromTop: true, newRuns: [createRun({})], }); }); it('HomeReducer - groupReset', () => { expect( HomeReducer( { ...EmptyState, rungroups: { undefined: [createRun({})] }, newRuns: [createRun({})], page: 10 }, { type: 'groupReset' }, ), ).to.eql({ ...EmptyState, showLoader: true }); }); it('HomeReducer - setScroll', () => { // When there is no groups, just change isScrolledFromTopValue expect(HomeReducer(EmptyState, { type: 'setScroll', isScrolledFromTop: true })).to.eql({ ...EmptyState, isScrolledFromTop: true, }); // When scrolling from down to top, merge new runs to groups expect( HomeReducer( { ...EmptyState, isScrolledFromTop: true, newRuns: [createRun({ run_number: 123 })], rungroups: { undefined: [createRun({})] }, }, { type: 'setScroll', isScrolledFromTop: false }, ), ).to.eql({ ...EmptyState, rungroups: { undefined: [createRun({}), createRun({ run_number: 123 })] }, newRuns: [], }); }); it('mergeTo', () => { // Health check expect(mergeTo([], {}, {})).to.eql({}); // Create new run group expect(mergeTo([createRun({})], {}, {})).to.eql({ undefined: [createRun({})] }); // Add to exsiting run group expect( mergeTo( [createRun({ run_number: 1 })], { undefined: [createRun({ run_number: 2 })] }, { _order: defaultHomeParameters._order }, ), ).to.eql({ undefined: [createRun({ run_number: 2 }), createRun({ run_number: 1 })], }); // Includes sorting expect( mergeTo([createRun({ run_number: 2 })], { undefined: [createRun({ run_number: 1 })] }, { _order: '-run_number' }), ).to.eql({ undefined: [createRun({ run_number: 1 }), createRun({ run_number: 2 })], }); // Add when grouping on expect(mergeTo([createRun({ flow_id: 'TestFlow' })], {}, { _group: 'flow_id' })).to.eql({ TestFlow: [createRun({ flow_id: 'TestFlow' })], }); // Merge run with same run_number and group parameter expect( mergeTo( [createRun({ flow_id: 'TestFlow', finished_at: 123 })], { TestFlow: [createRun({ flow_id: 'TestFlow', finished_at: undefined })] }, { _group: 'flow_id', _order: defaultHomeParameters._order }, ), ).to.eql({ TestFlow: [createRun({ flow_id: 'TestFlow', finished_at: 123 })] }); // Add to existing group expect( mergeTo( [createRun({ flow_id: 'TestFlow', run_number: 1 })], { TestFlow: [createRun({ flow_id: 'TestFlow', run_number: 2 })] }, { _group: 'flow_id', _order: defaultHomeParameters._order }, ), ).to.eql({ TestFlow: [createRun({ flow_id: 'TestFlow', run_number: 2 }), createRun({ flow_id: 'TestFlow', run_number: 1 })], }); // Add to new group expect( mergeTo( [createRun({ flow_id: 'Test2Flow', run_number: 1 })], { TestFlow: [createRun({ flow_id: 'TestFlow', run_number: 2 })] }, { _group: 'flow_id', _order: defaultHomeParameters._order }, ), ).to.eql({ TestFlow: [createRun({ flow_id: 'TestFlow', run_number: 2 })], Test2Flow: [createRun({ flow_id: 'Test2Flow', run_number: 1 })], }); }); it('mergeWithSeparatePool', () => { expect(mergeWithSeparatePool([], { rungroups: {}, newRuns: [] }, {})).to.eql({ rungroups: {}, newRuns: [] }); expect(mergeWithSeparatePool([createRun({})], { rungroups: {}, newRuns: [] }, {})).to.eql({ rungroups: {}, newRuns: [createRun({})], }); // Replace existing if runnumber matches expect( mergeWithSeparatePool( [createRun({ finished_at: 123 })], { rungroups: {}, newRuns: [createRun({ finished_at: undefined })] }, {}, ), ).to.eql({ rungroups: {}, newRuns: [createRun({ finished_at: 123 })] }); // Add to new runs expect( mergeWithSeparatePool([createRun({ run_number: 2 })], { rungroups: {}, newRuns: [createRun({})] }, {}), ).to.eql({ rungroups: {}, newRuns: [createRun({}), createRun({ run_number: 2 })], }); // Merge one to existing and add one to new runs expect( mergeWithSeparatePool( [createRun({ finished_at: 123 }), createRun({ run_number: 2 })], { rungroups: { undefined: [createRun({})] }, newRuns: [] }, { _order: defaultHomeParameters._order }, ), ).to.eql({ rungroups: { undefined: [createRun({ finished_at: 123 })] }, newRuns: [createRun({ run_number: 2 })], }); }); });
the_stack
import type { Declaration, Root, Result, AtRule } from 'postcss'; import stylelint from 'stylelint'; import shortCSS from 'shortcss'; import list from 'shortcss/lib/list'; import cssValues from 'css-values'; import { validProperties, validOptions, expected, getTypes, getIgnoredVariablesOrFunctions, getIgnoredKeywords, getIgnoredValues, getAutoFixFunc, } from './lib/validation'; import defaults, { ruleName, SecondaryOptions, IgnoreValue, RegExpString, } from './defaults'; const { utils } = stylelint; const messages = utils.ruleMessages(ruleName, { expected, }); /** * RegExp to skip non-CSS properties. * * @internal */ const reSkipProp = /^(?:@|\$|--).+$/; /** * RegExp to parse CSS, SCSS and less variables. * - allowing CSS variables to be multi line * - Sass namespaces and CSS <ident-token> supported * * @internal * @see https://github.com/sass/sass/blob/master/accepted/module-system.md#member-references * @see https://drafts.csswg.org/css-syntax-3/#ident-token-diagram */ // eslint-disable-next-line no-control-regex const reVar = /^-?(?:@.+|(?:(?:[a-zA-Z_-]|[^\x00-\x7F])+(?:[a-zA-Z0-9_-]|[^\x00-\x7F])*\.)?\$.+|var\(\s*--[\s\S]+\))$/; /** * RegExp to parse functions. * - irgnoring CSS variables `var(--*)` * - allow multi line arguments * * @internal */ const reFunc = /^(?!var\(\s*--)[\s\S]+\([\s\S]*\)$/; /** * RegExp to parse regular expressions. * - supporting patterns * - and optional flags * * @internal */ const reRegex = /^\/(.*)\/([a-zA-Z]*)$/; /** * @internal */ const reColorProp = /color/; type RegExpArray = [string, string?]; /** * Checks if string is a Regular Expression. * * @internal * @param value - Any string. */ const checkCssValue = (prop: string, value: string) => (reColorProp.test(prop) && value === 'transparent') || reVar.test(value) || reFunc.test(value) || cssValues(prop, value); const isRegexString = (value: string): value is RegExpString => reRegex.test(value); /** * Get pattern and flags of a Regular Expression string. * * @internal * @param value - Any string representing a Regular Expression. * @returns An Array of pattern and flags of a Regular Expression string. */ const getRegexString = (value: string): RegExpArray => value.match(reRegex)!.slice(1) as RegExpArray; /** * Convert a Regular Expression string to an RegExp object. * * @internal * @param value - Any string representing a Regular Expression. * @returns A Regular Expression object. */ const stringToRegex = (value: RegExpString) => { const [pattern, flags] = getRegexString(value); return new RegExp(pattern, flags); }; /** * Map ignored value config to a Regular expression. * * @internal * @param ignoreValue - A ignored value property. * @returns A Regular Expression to match ignored values. */ const mapIgnoreValue = (ignoreValue: IgnoreValue) => isRegexString(`${ignoreValue}`) ? stringToRegex(`${ignoreValue}`) : new RegExp(`^${ignoreValue}$`); /** * A rule function essentially returns a little PostCSS plugin. * It will report violations of this rule. * * @param root - PostCSS root (the parsed AST). * @param result - PostCSS lazy result. */ type PostCSSPlugin = (root: Root, result: Result) => void | PromiseLike<void>; /** * Third Stylelint plugin context parameter. */ interface StylelintContext { /** * Wheter or not stylelint was executed with `--fix` option. * * @defaultValue false */ fix?: boolean; } /** * A string or regular expression matching a CSS property name. */ type CSSPropertyName = string | RegExpString; /** * Primary options, a CSS property or list of CSS properties to lint. * - Regular Expression strings are supported */ type PrimaryOptions = CSSPropertyName | CSSPropertyName[]; /** * Stylelint declaration strict value rule function. * * @see https://stylelint.io/developer-guide/plugins * @param properties - Primary options, a CSS property or list of CSS properties to lint. * @param options- Secondary options, configure edge cases. * @param context - Only used for autofixing. * * @returns Returns a PostCSS Plugin. */ interface StylelintRuleFunction { ( primaryOption: PrimaryOptions, secondaryOptions?: SecondaryOptions, context?: StylelintContext ): PostCSSPlugin; primaryOptionArray: boolean; } const ruleFunction: StylelintRuleFunction = ( properties: string | string[], options: SecondaryOptions, context: StylelintContext = {} ) => (root: Root, result: Result) => { // fix #142 // @see https://github.com/stylelint/stylelint/pull/672/files#diff-78f1c80ffb2836008dd194b3b0ca28f9b46e4897b606f0b3d25a29e57a8d3e61R74 // @see https://stylelint.io/user-guide/configure#message /* eslint-disable @typescript-eslint/no-explicit-any */ if ( result && (result as any).stylelint && (result as any).stylelint.customMessages && (result as any).stylelint.customMessages[ruleName] ) { // eslint-disable-next-line no-param-reassign delete (result as any).stylelint.customMessages[ruleName]; } /* eslint-enable @typescript-eslint/no-explicit-any */ // validate stylelint plugin options const hasValidOptions = utils.validateOptions( result, ruleName, { actual: properties, possible: validProperties, }, { actual: options, possible: validOptions, optional: true, } ); if (!hasValidOptions) return; // normalize options if (!Array.isArray(properties)) { // eslint-disable-next-line no-param-reassign properties = [properties]; } const config: SecondaryOptions = { ...defaults, ...options, }; const { ignoreVariables, ignoreFunctions, ignoreKeywords, ignoreValues, message, disableFix, autoFixFunc, expandShorthand, recurseLonghand, } = config; const autoFixFuncNormalized = getAutoFixFunc( autoFixFunc, disableFix, context.fix ); /** * A hash of regular expression to ignore for a CSS properties. * @internal */ interface RegExpMap { // [key: CSSPropertyName]: RegExp; [key: string]: RegExp; } /** * A hash of regular expression to ignore for a CSS properties or `null`. * @internal */ type RegExpKeywordMap = null | RegExpMap; /** * A hash of regular expression lists to ignore for a CSS property. * @internal */ interface RegExpList { // [key: CSSPropertyName]: RegExp[]; [key: string]: RegExp[]; } /** * A hash of regular expression lists to ignore for a CSS property or `null`. * @internal */ type RegExpValuesList = null | RegExpList; const reKeywords: RegExpKeywordMap = ignoreKeywords ? {} : null; const reValues: RegExpValuesList = ignoreValues ? {} : null; let cssLoaderValues: RegExp; if (ignoreVariables) { const cssLoaderValuesNames: string[] = []; root.walkAtRules('value', (rule: AtRule) => { const { params } = rule; const name = params.split(':')[0].trim(); cssLoaderValuesNames.push(name); }); cssLoaderValues = new RegExp(`^-?(:?${cssLoaderValuesNames.join('|')})$`); } // loop through all properties properties.forEach((property) => { let propFilter: string | RegExp = property; // parse RegExp if (isRegexString(propFilter)) { propFilter = stringToRegex(propFilter); } // walk through all declarations filtered by configured properties root.walkDecls(filterDecl); /** * Filter declarations for matching properties and expand shorthand properties. * * @internal * @param node - A Declaration-Node from PostCSS AST-Parser. */ function filterDecl(node: Declaration) { const { value, prop } = node; // skip variable declarations if (reSkipProp.test(prop)) return; const isShortHand = expandShorthand && shortCSS.isShorthand(prop); if ( prop === propFilter || (!isShortHand && propFilter instanceof RegExp && propFilter.test(prop)) ) { const values: string[] = list.space(value); // handle multi-value props, like scrollbar-color if (values.length > 1) { let failedFlag = false; values.forEach((valueItem) => { if (!failedFlag) { failedFlag = lintDeclStrictValue(node, prop, valueItem); } }); } else { lintDeclStrictValue(node); } } else if (isShortHand) { const expandedProps = shortCSS.expand(prop, value, recurseLonghand); let failedFlag = false; Object.keys(expandedProps).forEach((longhandProp) => { const longhandValue = expandedProps[longhandProp]; if ( !failedFlag && (longhandProp === propFilter || (propFilter instanceof RegExp && propFilter.test(longhandProp))) ) { failedFlag = lintDeclStrictValue( node, longhandProp, longhandValue, true ); } }); } } /** * Lint usages of declarations values against, variables, functions * or custom keywords - as configured. * * @internal * @param node - A Declaration-Node from PostCSS AST-Parser. * @param longhandProp - A Declaration-Node from PostCSS AST-Parser. * @param longhandValue - A Declaration-Node from PostCSS AST-Parser. * @param isExpanded - Whether or not this declaration was expanded. * @returns Returns `true` if invalid declaration found, else `false`. */ function lintDeclStrictValue( node: Declaration, longhandProp?: string, longhandValue?: string, isExpanded = false ) { const { value: nodeValue, prop: nodeProp } = node; const value = longhandValue || nodeValue; // falsify everything by default let validVar = false; let validFunc = false; let validKeyword = false; let validValue = false; // test variable if (ignoreVariables) { // @TODO: deviant regexes to primary options need to be evaluated const ignoreVariable = getIgnoredVariablesOrFunctions( ignoreVariables, property ); if (ignoreVariable) { validVar = reVar.test(value) || cssLoaderValues.test(value); } } // test function if (ignoreFunctions && !validVar) { // @TODO: deviant regexes to primary options need to be evaluated const ignoreFunction = getIgnoredVariablesOrFunctions( ignoreFunctions, property ); if (ignoreFunction) { validFunc = reFunc.test(value); } } // test expanded shorthands are valid if ( isExpanded && (!ignoreVariables || (ignoreVariables && !validVar)) && (!ignoreFunctions || (ignoreFunctions && !validFunc)) && checkCssValue(longhandProp!, longhandValue!) !== true ) { return false; } // test keywords if (ignoreKeywords && (!validVar || !validFunc)) { let reKeyword = reKeywords![property]; if (!reKeyword) { const ignoreKeyword = getIgnoredKeywords(ignoreKeywords, property); if (ignoreKeyword) { reKeyword = new RegExp(`^${ignoreKeyword.join('$|^')}$`); reKeywords![property] = reKeyword; } } if (reKeyword) { validKeyword = reKeyword.test(value); } } if (ignoreValues && (!validVar || !validFunc || !validKeyword)) { let reValueList = reValues![property]; if (!reValueList) { const ignoreValue = getIgnoredValues(ignoreValues, property); if (ignoreValue) { reValueList = ignoreValue.map(mapIgnoreValue); reValues![property] = reValueList; } } if (reValueList) { validValue = reValueList.filter((reValue) => reValue.test(value)).length > 0; } } // report only if all failed if (!validVar && !validFunc && !validKeyword && !validValue) { const types = getTypes(config, property); // support auto fixing if (context.fix && !disableFix && autoFixFuncNormalized) { const fixedValue = autoFixFuncNormalized( node, { validVar, validFunc, validKeyword, validValue, longhandProp, longhandValue, }, root, config ); // apply fixed value if returned if (fixedValue) { // eslint-disable-next-line no-param-reassign node.value = fixedValue; } } else { const { raws } = node; // eslint-disable-next-line prefer-destructuring const start = node.source!.start; utils.report({ ruleName, result, node, line: start!.line, // column: start!.column + nodeProp.length + raws.between!.length, message: messages.expected(types, value, nodeProp, message), }); } return true; } return false; } }); }; ruleFunction.primaryOptionArray = true; const declarationStrictValuePlugin = stylelint.createPlugin( ruleName, ruleFunction ); export default declarationStrictValuePlugin; export { ruleName, messages };
the_stack
import { Contract, ContractTransaction, EventFilter, Signer } from 'ethers'; import { Listener, Provider } from 'ethers/providers'; import { Arrayish, BigNumber, BigNumberish, Interface } from 'ethers/utils'; import { TransactionOverrides, TypedEventDescription, TypedFunctionDescription, } from '.'; interface WETHInterface extends Interface { functions: { allowance: TypedFunctionDescription<{ encode([owner, spender]: [string, string]): string; }>; approve: TypedFunctionDescription<{ encode([spender, amount]: [string, BigNumberish]): string; }>; balanceOf: TypedFunctionDescription<{ encode([account]: [string]): string; }>; totalSupply: TypedFunctionDescription<{ encode([]: []): string }>; transfer: TypedFunctionDescription<{ encode([recipient, amount]: [string, BigNumberish]): string; }>; transferFrom: TypedFunctionDescription<{ encode([sender, recipient, amount]: [ string, string, BigNumberish, ]): string; }>; deposit: TypedFunctionDescription<{ encode([]: []): string }>; withdraw: TypedFunctionDescription<{ encode([amount]: [BigNumberish]): string; }>; }; events: { Approval: TypedEventDescription<{ encodeTopics([owner, spender, value]: [ string | null, string | null, null, ]): string[]; }>; Transfer: TypedEventDescription<{ encodeTopics([from, to, value]: [ string | null, string | null, null, ]): string[]; }>; }; } export class WETH extends Contract { connect(signerOrProvider: Signer | Provider | string): WETH; attach(addressOrName: string): WETH; deployed(): Promise<WETH>; on(event: EventFilter | string, listener: Listener): WETH; once(event: EventFilter | string, listener: Listener): WETH; addListener(eventName: EventFilter | string, listener: Listener): WETH; removeAllListeners(eventName: EventFilter | string): WETH; removeListener(eventName: any, listener: Listener): WETH; interface: WETHInterface; functions: { /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Returns the amount of tokens owned by `account`. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens owned by `account`. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; deposit(overrides?: TransactionOverrides): Promise<ContractTransaction>; 'deposit()'(overrides?: TransactionOverrides): Promise<ContractTransaction>; withdraw( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; 'withdraw(uint256)'( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; }; /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Returns the amount of tokens owned by `account`. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens owned by `account`. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; deposit(overrides?: TransactionOverrides): Promise<ContractTransaction>; 'deposit()'(overrides?: TransactionOverrides): Promise<ContractTransaction>; withdraw( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; 'withdraw(uint256)'( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; filters: { Approval( owner: string | null, spender: string | null, value: null, ): EventFilter; Transfer(from: string | null, to: string | null, value: null): EventFilter; }; estimate: { /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default. This value changes when {approve} or {transferFrom} are called. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 Emits an {Approval} event. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens owned by `account`. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens owned by `account`. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the amount of tokens in existence. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; deposit(overrides?: TransactionOverrides): Promise<BigNumber>; 'deposit()'(overrides?: TransactionOverrides): Promise<BigNumber>; withdraw( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; 'withdraw(uint256)'( amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; }; }
the_stack
import * as React from 'react'; import * as tsStyles from './UploadStyles'; import InfiniteScroll from 'react-infinite-scroller'; import styles from './UplaodFromSharePoint.module.scss'; import { Callout, DefaultButton, DefaultPalette, DetailsList, DetailsListLayoutMode, Dialog, DialogFooter, DialogType, FontWeights, IColumn, Icon, IconButton, IconType, IFacepilePersona, IPersonaSharedProps, Label, mergeStyleSets, MessageBar, MessageBarType, Persona, PersonaBase, PersonaSize, PrimaryButton, Selection, SelectionMode, ShimmeredDetailsList, Spinner, SpinnerSize, Stack, TextField, TooltipHost, BaseButton, Button } from 'office-ui-fabric-react'; import { format, parse, parseISO } from 'date-fns'; import { GroupOrder, IGrouping, IViewField, ListView } from '@pnp/spfx-controls-react/lib/ListView'; import { IListViewItems } from './IListViewItems'; import { IUploadFromSharePointProps } from './IUploadFromSharePointProps'; import { IUploadFromSharePointState } from './IUploadFromSharePointState'; import { PagedItemCollection } from '@pnp/sp'; import { utilities } from '../../utilities'; import { ITaskExternalReference } from '../../services/ITaskExternalReference'; import * as strings from 'MyTasksWebPartStrings'; export class UploadFromSharePoint extends React.Component<IUploadFromSharePointProps, IUploadFromSharePointState> { private _listItems: PagedItemCollection<any[]> ; private _selection: Selection; private util = new utilities(); private _selectedItem : IListViewItems; constructor(props: IUploadFromSharePointProps) { super(props); const columns: IColumn[] = [ { key: 'column1', name: 'File_x0020_Type', className: tsStyles.classNames.fileIconCell, iconClassName: tsStyles.classNames.fileIconHeaderIcon, iconName: 'Page', isIconOnly: true, fieldName: 'name', minWidth: 16, maxWidth: 16, onColumnClick: this._onColumnClick, onRender: (item: IListViewItems) => { return <Icon iconType={IconType.Image} imageProps={{src: item.fileTypeImageUrl, height: 22, width: 22}} />; } }, { name: 'Name', key: 'column2', fieldName: 'FileLeafRef', minWidth: 200, maxWidth: 250, isResizable: true, isSorted: false, isSortedDescending: false, sortAscendingAriaLabel: 'Sorted A to Z', sortDescendingAriaLabel: 'Sorted Z to A', onColumnClick: this._onColumnClick, data: 'string', isPadded: true }, { key: 'column3', name: 'Date Modified', fieldName: 'Modified', minWidth: 70, maxWidth: 90, isResizable: true, isSorted: true, isSortedDescending: false, onColumnClick: this._onColumnClick, data: 'string', isPadded: true } ]; this.state = { selectItem: undefined, hasError: false, messageError: undefined, isloading: true, hideDialog: !this.props.displayDialog, listViewItems: [], hasMoreItems: false, disableSaveButton: true, columns: columns, messageInfo:'', }; this._selection = new Selection({ onSelectionChanged: () => { this._getSelectionDetails(); } }); } /** * Returns upload from share point * @returns did mount */ public async componentDidMount(): Promise<void> { this.setState({isloading:true}); await this._getListItems('Modified', false); } /** * Components did update * @param prevProps * @param prevState * @returns did update */ public async componentDidUpdate(prevProps: IUploadFromSharePointProps, prevState: IUploadFromSharePointState): Promise<void> { if (this.props.groupId !== prevProps.groupId || this.props.displayDialog !== prevProps.displayDialog) { this.setState({ hideDialog: !this.props.displayDialog }); this.setState({isloading:true}); await this._getListItems('Modified', false); } } /** * Get list items of upload from share point */ private _getListItems = async (sortField: string , ascending:boolean) => { const { spservice, groupId } = this.props; const items: IListViewItems[] = []; try { this._listItems = await spservice.getSharePointFiles(groupId,sortField, ascending); for (const item of this._listItems.results) { if (item.File === undefined) continue; const fileTypeImageUrl = await this.util.GetFileImageUrl(item.File.Name); items.push({ FileLeafRef : item.File.Name, Modified: format(parseISO(item.File.TimeLastModified),'P'), fileTypeImageUrl: fileTypeImageUrl , fileUrl: item.File.ServerRelativeUrl}); } this.setState({ listViewItems: items, hasError: false, messageError: '' , isloading: false, hasMoreItems: this._listItems.hasNext}); } catch (error) { this.setState({ hasError: true, messageError: error.message ,isloading: false}); } } /** * Get list items next page of upload from share point */ private _getListItemsNextPage = async () => { this._listItems = await this._listItems.getNext(); let items: IListViewItems[]=[]; let {listViewItems} = this.state; for (const item of this._listItems.results) { console.log(item.File); if (item.File === undefined) continue; const fileTypeImageUrl = await this.util.GetFileImageUrl(item.File.Name); items.push({ FileLeafRef : item.File.Name, Modified: format(parseISO(item.File.TimeLastModified),'P'), fileTypeImageUrl: fileTypeImageUrl , fileUrl: item.File.ServerRelativeUrl}); } this.setState({ listViewItems: listViewItems.concat(items), hasError: false, messageError: '' , isloading: false, hasMoreItems: this._listItems.hasNext}); } /** * Close dialog of upload from share point */ private _closeDialog = (ev?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { this.setState({ hideDialog: true }); this.props.onDismiss(); } /** * Determines whether column click on */ private _onColumnClick = async (ev: React.MouseEvent<HTMLElement>, column: IColumn): Promise<void> => { // tslint:disable-next-line: no-shadowed-variable const { columns , hasMoreItems} = this.state; const newColumns: IColumn[] = columns.slice(); const currColumn: IColumn = newColumns.filter(currCol => column.key === currCol.key)[0]; newColumns.forEach((newCol: IColumn) => { if (newCol === currColumn) { currColumn.isSortedDescending = !currColumn.isSortedDescending; currColumn.isSorted = true; } else { newCol.isSorted = false; newCol.isSortedDescending = true; } }); if ( hasMoreItems) { // has more items to load get items sorted by clicked columns and direction await this._getListItems(currColumn.fieldName, currColumn.isSortedDescending); } let {listViewItems} = this.state; // Sort Items const newItems = this._copyAndSort(listViewItems , currColumn.fieldName!, currColumn.isSortedDescending); this.setState({ columns: newColumns, listViewItems : newItems }); } /** * Copys and sort * @template T * @param items * @param columnKey * @param [isSortedDescending] * @returns and sort */ private _copyAndSort<T>(items: T[], columnKey: string, isSortedDescending?: boolean): T[] { const key = columnKey as keyof T; return items.slice(0).sort((a: T, b: T) => ((isSortedDescending ? a[key] < b[key] : a[key] > b[key]) ? 1 : -1)); } /** * Gets selection details */ private _getSelectionDetails() { const selectionCount = this._selection.getSelectedCount(); switch (selectionCount) { case 0: this.setState({ selectItem: null, disableSaveButton: true, }); break; case 1: const currentReferences = this.props.currentReferences; const fileServerRelativeUrl = (this._selection.getSelection()[0] as IListViewItems).fileUrl; const fileFullUrl: string = (`${location.origin}${fileServerRelativeUrl}`).replace(/\./g, '%2E').replace(/\:/g, '%3A') + `?web=1`; if ( currentReferences[fileFullUrl] == null) { this.setState({ selectItem: this._selection.getSelection()[0] as IListViewItems, disableSaveButton: false, messageInfo: '', }); }else{ this.setState({messageInfo: strings.FileAlreadyAddedToTaskLabel}); } break; default: } } /** * Determines whether select file on */ private _onSelectFile = async (event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement | HTMLDivElement | BaseButton | Button, MouseEvent>) => { try { this.props.onSelectedFile({fileUrl: this.state.selectItem.fileUrl,FileLeafRef: this.state.selectItem.FileLeafRef}); this.setState({ hideDialog: true }); } catch (error) { } } private _onActiveItemChanged = (item:IListViewItems,index:number, ev:React.FocusEvent<HTMLElement>) => { ev.preventDefault(); this._selectedItem = item; } /** * Renders upload from sharepoint * @returns render */ public render(): React.ReactElement<IUploadFromSharePointProps> { return ( <div> <Dialog hidden={this.state.hideDialog} onDismiss={this._closeDialog} minWidth={650} maxWidth={650} dialogContentProps={{ type: DialogType.normal, title: strings.DocumentsLabel }} modalProps={{ isBlocking: true, styles: tsStyles.modalStyles // topOffsetFixed: true }}> {this.state.isloading ? ( <div style={{ height: 300, overflow: 'auto' }}> <Spinner size={SpinnerSize.medium} label={strings.LoadingLabel}></Spinner> </div> ) : ( <> {this.state.hasError && <MessageBar messageBarType={MessageBarType.error}>{this.state.messageError}</MessageBar>} <div style={{ height: 300, overflow: 'auto' }}> <Label>{this.state.messageInfo}</Label> <InfiniteScroll pageStart={0} loadMore={this._getListItemsNextPage} hasMore={this.state.hasMoreItems} threshold={20} useWindow={false}> <DetailsList items={this.state.listViewItems} compact={false} columns={this.state.columns} selectionMode={SelectionMode.single} setKey="none" layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={true} selection={this._selection} /> </InfiniteScroll> </div> </> )} <DialogFooter> <PrimaryButton onClick={this._onSelectFile} text={strings.SaveLabel} disabled={this.state.disableSaveButton}/> <DefaultButton onClick={this._closeDialog} text={strings.CancelLabel} /> </DialogFooter> </Dialog> </div> ); } }
the_stack
import { Vector2 } from "../Vector2" import { Rect } from "../Rect"; import { BlockRegData, BlockParameterTypeRegData, BlockParameterEnumRegData, BlockParameterEditorRegData, BlockEditorComponentCreateFn, BlockParametersChangeSettings, BlockStyleSettings, BlockPortEditorComponentCreateFn, BlockMenuSettings, BlockPortRegData, BlockMouseEventFn, PortAnyFlexableData, BlockPortAnyFlexablesData } from "../Define/BlockDef"; import { BlockPort, BlockPortDirection } from "../Define/Port"; import CommonUtils from "../../utils/CommonUtils"; import AllEditors from "../TypeEditors/AllEditors"; import ParamTypeServiceInstance from "../../sevices/ParamTypeService"; import { Block, OnBlockEditorEventCallback, OnUserAddPortCallback } from "../Define/Block"; import { ConnectorEditor } from "../Editor/ConnectorEditor"; import { BlockEditorOwner } from "./BlockEditorOwner"; import StringUtils from "../../utils/StringUtils"; import HtmlUtils from "../../utils/HtmlUtils"; import ToolTipUtils from "../../utils/ToolTipUtils"; import BlockUtils from "../Blocks/Utils/BlockUtils"; import { BlockPortEditor, BlockPortIcons } from "./BlockPortEditor"; import { MouseEventDelegate } from "@/utils/EventHandler"; export const SIZE_LEFT = 0x1; export const SIZE_RIGHT = 0x2; export const SIZE_TOP = 0x4; export const SIZE_BOTTOM = 0x8; /** * 编辑器模式下的单元。 * 扩展了单元的编辑事件操作与管理,供编辑器使用。 * 运行时中不会声明此类。 */ export class BlockEditor extends Block { public position : Vector2 = new Vector2(); public size : Vector2 = new Vector2(150, 200); public name = ''; public description = ''; /** * 块的用户注释 */ public mark = ''; public markOpen = false; public logo = ''; public selected = false; public hover = false; private rect = new Rect(); public editor : BlockEditorOwner = null; public constructor(regData ?: BlockRegData) { super(regData, true); this.onAddPortElement.addListener(this, (block, port) => this.addPortElement(port)); this.onRemovePortElement.addListener(this, (block, port) => this.removePortElement(port)); this.onUpdatePortElement.addListener(this, (block, port) => this.updatePortElement(port)); this.onPortValueUpdate.addListener(this, (block, port) => this.updatePortParamDisplayVal(port)); this.onPortConnectorActive.addListener(this, (port, connector) => { if(this.currentRunner && this.currentRunner.state != 'stopped') (<ConnectorEditor>connector).active(port); }); this.onPortRemove.addListener(this, this.onPortRemoveCallback); this.onEnterBlock.addListener(this, () => this.markActive()); this.onLeaveBlock.addListener(this, () => this.markDective()); } public blockStyleSettings = new BlockStyleSettings(); public blockMenuSettings = new BlockMenuSettings(); public getRect() { this.rect.setPos(this.position); this.rect.setSize(this.size); return this.rect; } public el : HTMLDivElement = null; public els = new BlockEditorHTMLData(); public created = false; public forceNotUnConnect = false; public create(editor : BlockEditorOwner) { this.isEditorBlock = true; this.editor = editor; this.created = true; if(this.regData) { this.name = this.regData.baseInfo.name; this.description = this.regData.baseInfo.description; this.logo = this.regData.baseInfo.logo; this.blockStyleSettings = this.regData.blockStyle; this.blockMenuSettings = this.regData.blockMenu; this.portAnyFlexables = this.regData.portAnyFlexables; this.onCreateCustomEditor = this.regData.callbacks.onCreateCustomEditor; this.onUserAddPort = this.regData.callbacks.onUserAddPort; this.onCreatePortCustomEditor = this.regData.callbacks.onCreatePortCustomEditor; this.onSave = this.regData.callbacks.onSave; this.onMouseEvent = this.regData.callbacks.onBlockMouseEvent; this.portsChangeSettings = this.regData.settings.portsChangeSettings; this.parametersChangeSettings = this.regData.settings.parametersChangeSettings; } let host = this.editor.getBlockHostElement(this.blockStyleSettings.layer); this.el = document.createElement('div'); this.el.classList.add("flow-block"); this.el.setAttribute("id", this.uid); if(!StringUtils.isNullOrEmpty(this.blockStyleSettings.minWidth)) this.el.style.minWidth = this.blockStyleSettings.minWidth; if(!StringUtils.isNullOrEmpty(this.blockStyleSettings.minHeight)) this.el.style.minHeight = this.blockStyleSettings.minHeight; this.els.elSizeDragger = document.createElement('div'); this.els.elSizeDragger.classList.add('size-dragger'); if(!this.userCanResize) HtmlUtils.hideElement(this.els.elSizeDragger); //#region Ports let content = document.createElement('div'); let areaPorts = document.createElement('div'); let areaPortsBottom = document.createElement('div'); this.els.elInputPorts = document.createElement('div'); this.els.elInputPorts.classList.add("ports", 'input'); this.els.elOutputPorts = document.createElement('div'); this.els.elOutputPorts.classList.add("ports", 'output'); this.els.elAddInputBehaviorPort = document.createElement('a'); this.els.elAddOutputBehaviorPort = document.createElement('a'); this.els.elAddInputBehaviorPort.classList.add('port-add','iconfont', 'Behavior', BlockPortIcons.portBehaviorAddIcon); this.els.elAddOutputBehaviorPort.classList.add('port-add','iconfont', 'Behavior',BlockPortIcons.portBehaviorAddIcon); this.els.elAddInputBehaviorPort.setAttribute('data-title', '添加入端口'); this.els.elAddOutputBehaviorPort.setAttribute('data-title', '添加出端口'); ToolTipUtils.registerElementTooltip(this.els.elAddInputBehaviorPort); ToolTipUtils.registerElementTooltip(this.els.elAddOutputBehaviorPort); this.els.elAddInputBehaviorPort.onclick = this.onUserAddInputPort.bind(this); this.els.elAddOutputBehaviorPort.onclick = this.onUserAddOutputPort.bind(this); this.els.elAddInputParamPort = document.createElement('a'); this.els.elAddOutputParamPort = document.createElement('a'); this.els.elAddInputParamPort.classList.add('port-add','iconfont', 'Param', BlockPortIcons.portParamAddIcon); this.els.elAddOutputParamPort.classList.add('port-add','iconfont', 'Param', BlockPortIcons.portParamAddIcon); this.els.elAddInputParamPort.setAttribute('data-title', '添加入参数'); this.els.elAddOutputParamPort.setAttribute('data-title', '添加出参数'); ToolTipUtils.registerElementTooltip(this.els.elAddInputParamPort); ToolTipUtils.registerElementTooltip(this.els.elAddOutputParamPort); this.els.elAddInputParamPort.onclick = this.onUserAddInputParam.bind(this); this.els.elAddOutputParamPort.onclick = this.onUserAddOutputParam.bind(this); areaPorts.classList.add("area"); areaPorts.appendChild(this.els.elInputPorts); areaPorts.appendChild(this.els.elOutputPorts); areaPortsBottom.classList.add("area-bottom"); areaPortsBottom.appendChild(this.els.elAddInputBehaviorPort); areaPortsBottom.appendChild(this.els.elAddInputParamPort); areaPortsBottom.appendChild(this.els.elAddOutputParamPort); areaPortsBottom.appendChild(this.els.elAddOutputBehaviorPort); content.appendChild(areaPorts); content.appendChild(areaPortsBottom); content.classList.add("content"); //#endregion //#region Title and logo this.els.elTitle = document.createElement('div'); this.els.elTitle.classList.add("title"); this.els.elTitle.setAttribute('data-title', this.description); if(!this.blockStyleSettings.noTooltip) ToolTipUtils.registerElementTooltip(this.els.elTitle); this.els.elBackground = document.createElement('div'); this.els.elBackground.classList.add("background"); if(!CommonUtils.isNullOrEmpty(this.blockStyleSettings.titleColor)) this.els.elTitle.style.color = this.blockStyleSettings.titleColor; if(!CommonUtils.isNullOrEmpty(this.blockStyleSettings.titleBakgroundColor)) this.els.elTitle.style.background = this.blockStyleSettings.titleBakgroundColor; if(this.blockStyleSettings.smallTitle) this.els.elTitle.classList.add("small"); if(this.blockStyleSettings.noTitle) this.els.elTitle.classList.add("hide"); this.els.elBreakPointArrow = document.createElement('div'); this.els.elBreakPointArrow.classList.add('breakpoint-arrow','iconfont', 'icon-zuo'); this.els.elBreakPointArrow.style.display = 'none'; this.els.elBreakPointStatus = document.createElement('div'); this.els.elBreakPointStatus.classList.add('breakpoint-status','iconfont'); this.els.elBreakPointStatus.style.display = 'none'; this.els.elCustomEditor = document.createElement('div'); this.els.elCustomEditor.classList.add("custom-editor"); if(this.blockStyleSettings.smallTitle || this.blockStyleSettings.noTitle) this.els.elCustomEditor.classList.add('without-title'); if(this.blockStyleSettings.smallTitle && !this.blockStyleSettings.noTitle) { let titleSmall = document.createElement('div'); let titleSmallSpan = document.createElement('span'); titleSmall.classList.add('title-small'); titleSmallSpan.innerText = this.name titleSmall.setAttribute('data-title', this.description); titleSmall.appendChild(titleSmallSpan); if(!this.blockStyleSettings.noTooltip) ToolTipUtils.registerElementTooltip(titleSmall); this.el.appendChild(titleSmall); } this.els.elTitleText = document.createElement('span'); this.els.elLogo = document.createElement('div'); this.els.elLogo.classList.add("logo"); this.els.elLogoRight = document.createElement('div'); this.els.elLogoRight.classList.add("logo-right"); this.els.elLogoBottom = document.createElement('div'); this.els.elLogoBottom.classList.add("logo-bottom"); this.els.elLogo.style.display = (CommonUtils.isNullOrEmpty(this.logo) || this.blockStyleSettings.hideLogo) ? 'none' : 'inline-block'; if(this.logo.startsWith('<')) this.els.elLogo.innerHTML = this.logo; else if(!CommonUtils.isNullOrEmpty(this.logo)) this.els.elLogo.style.backgroundImage = 'url(' + this.logo + ')'; this.els.elLogoBottom.style.display = CommonUtils.isNullOrEmpty(this.blockStyleSettings.logoBottom) ? 'none' : 'inline-block'; if(this.logo.startsWith('<')) this.els.elLogoBottom.innerHTML = this.blockStyleSettings.logoBottom; else if(!CommonUtils.isNullOrEmpty(this.els.elLogoBottom)) this.els.elLogoBottom.style.backgroundImage = 'url(' + this.blockStyleSettings.logoBottom + ')'; this.els.elLogoRight.style.display = CommonUtils.isNullOrEmpty(this.blockStyleSettings.logoRight) ? 'none' : 'inline-block'; if(this.logo.startsWith('<')) this.els.elLogoRight.innerHTML = this.blockStyleSettings.logoRight; else if(!CommonUtils.isNullOrEmpty(this.els.elLogoRight)) this.els.elLogoRight.style.backgroundImage = 'url(' + this.blockStyleSettings.logoRight + ')'; if(!CommonUtils.isNullOrEmpty(this.blockStyleSettings.logoBackground)) { if(this.blockStyleSettings.logoBackground.startsWith('title:')) this.els.elBackground.innerHTML = '<span class="big-title">' + this.blockStyleSettings.logoBackground.substr(6) + "</span>"; else if(this.blockStyleSettings.logoBackground.startsWith('<')) this.els.elBackground.innerHTML = this.blockStyleSettings.logoBackground; else this.els.elBackground.style.backgroundImage = 'url(' + this.blockStyleSettings.logoBackground + ')'; } this.el.appendChild(this.els.elBackground); this.els.elTitle.appendChild(this.els.elLogo); this.els.elTitle.appendChild(this.els.elTitleText); this.els.elTitle.appendChild(this.els.elLogoRight); this.els.elTitle.appendChild(this.els.elLogoBottom); //#endregion //#region Comment if(!this.blockStyleSettings.noComment) { this.els.elBottomInfoHost = document.createElement('div'); this.els.elBottomInfoHost.classList.add('bottom-info'); this.els.elBottomInfoHost.style.display = 'none'; content.appendChild(this.els.elBottomInfoHost); this.els.elComment = document.createElement('div'); this.els.elComment.classList.add('flow-block-comment', 'flow-block-no-move'); this.els.elCommentText = document.createElement('div'); this.els.elCommentText.classList.add('flow-block-comment-text', 'flow-block-no-move'); this.els.elCommentText.setAttribute('contenteditable', 'true'); this.els.elCommentPlaceHolder = document.createElement('span'); this.els.elCommentPlaceHolder.classList.add('flow-block-comment-place-holder'); this.els.elCommentPlaceHolder.innerText = '点击添加注释'; this.els.elCommentOpen = document.createElement('a'); this.els.elCommentOpen.setAttribute('data-title', '打开注释气泡'); this.els.elCommentOpen.classList.add('flow-block-comment-open','iconfont','icon-qipao'); ToolTipUtils.registerElementTooltip(this.els.elCommentOpen); this.els.elCommentClose = document.createElement('a'); this.els.elCommentClose.classList.add('iconfont','icon-close-'); this.els.elCommentClose.setAttribute('data-title', '隐藏注释气泡'); ToolTipUtils.registerElementTooltip(this.els.elCommentClose); this.els.elCommentOpen.onclick = () => { this.markOpen = true; this.updateComment(); }; this.els.elCommentClose.onclick = () => { this.markOpen = false; this.updateComment(); }; this.els.elCommentPlaceHolder.onclick = () => { this.els.elCommentPlaceHolder.style.display = 'none'; this.els.elCommentText.focus(); }; this.els.elCommentText.oninput = () => { this.els.elComment.style.top = -(this.els.elCommentText.offsetHeight - 23 + 40) + 'px'; }; this.els.elCommentText.onblur = () => { this.mark = this.els.elCommentText.innerText; this.updateComment(); }; this.els.elComment.appendChild(this.els.elCommentPlaceHolder); this.els.elComment.appendChild(this.els.elCommentText); this.els.elComment.appendChild(this.els.elCommentClose); this.el.appendChild(this.els.elCommentOpen); this.el.appendChild(this.els.elComment); } //#endregion this.el.appendChild(this.els.elTitle); this.el.appendChild(this.els.elCustomEditor); this.el.appendChild(content); this.el.appendChild(this.els.elBreakPointStatus); this.el.appendChild(this.els.elBreakPointArrow); this.el.appendChild(this.els.elSizeDragger); //size if(this.userCanResize) { if(this.size.x > 0) this.el.style.width = this.size.x + 'px'; if(this.size.y > 0) this.el.style.height = this.size.y + 'px'; } //Events this.el.addEventListener('mouseenter', this.onMouseEnter.bind(this)); this.el.addEventListener('mouseleave', this.onMouseOut.bind(this)); this.el.addEventListener('mousemove', this.onMouseMove.bind(this)); this.el.addEventListener('mouseup', this.onMouseUp.bind(this)); this.el.addEventListener('mousedown', this.onMouseDown.bind(this)); this.el.addEventListener('resize', this.onResize.bind(this)); this.el.addEventListener('wheel', this.onMouseWhell.bind(this)); this.el.addEventListener('contextmenu', this.onContextMenu.bind(this)); if(!this.blockStyleSettings.noTooltip) ToolTipUtils.registerElementTooltip(this.el); //load port elements this.allPorts.forEach(port => { if((<BlockPortEditor>port).editorData == null) this.addPortElement(port); }); host.appendChild(this.el); this.fnonMouseUp = this.onMouseUp.bind(this); this.fnonMouseMove = this.onMouseMove.bind(this); this.onEditorCreate.invoke(this); if(typeof this.onCreateCustomEditor == 'function') this.onCreateCustomEditor(this.els.elCustomEditor, this, this.regData); this.onResize(); this.flushAllPortElementCreateState(); this.updateContent(); this.updateBreakPointStatus(); this.updateComment(); //运行平台如果不符则抛出错误 if(!this.isPlatformSupport) this.throwError('单元不支持当前平台,因此无法在编辑器中调试该单元。', null, 'warning'); } public destroy() { this.onDestroy.invoke(this); this.editor.onBlockDelete(this); this.created = false; this.el.removeEventListener('mouseenter', this.onMouseEnter.bind(this)); this.el.removeEventListener('mouseleave', this.onMouseOut.bind(this)); this.el.removeEventListener('mousedown', this.onMouseDown.bind(this)); this.el.removeEventListener('resize', this.onResize.bind(this)); this.el.removeEventListener('wheel', this.onMouseWhell.bind(this)); this.el.removeEventListener('contextmenu', this.onContextMenu.bind(this)); this.inputPorts = null; this.outputPorts = null; this.allPorts = null; this.el.parentNode.removeChild(this.el); } public clone() { //保存自定义数据 if(typeof this.onSave === 'function') this.onSave(this); let blockEditor = new BlockEditor(this.regData); blockEditor.options = this.options; blockEditor.breakpoint = this.breakpoint; blockEditor.markOpen = this.markOpen; blockEditor.mark = this.mark; this.allPorts.forEach(port => { if(port.isDyamicAdd) blockEditor.addPort(port.regData, true, port.getUserSetValue()); }); return blockEditor; } /** * 更新位置 * @param pos 位置 */ public setPos(pos ?: Vector2) { if(typeof pos != 'undefined') this.position.Set(pos); this.el.style.left = this.position.x + 'px'; this.el.style.top = this.position.y + 'px'; } public setSize(size ?: Vector2) { if(typeof this.size != 'undefined') this.size.Set(size); this.el.style.width = this.size.x + 'px'; this.el.style.height = this.size.y + 'px'; } /** * 断开端口的所有连接 * @param oldData 目标 */ public unConnectPort(oldData : BlockPort) { if(oldData.direction == 'input') { if(oldData.connectedFromPort.length > 0) oldData.connectedFromPort.forEach((c) => this.editor.unConnectConnector(<ConnectorEditor>c.connector)); } else if(oldData.direction == 'output') { if(oldData.connectedToPort.length > 0) oldData.connectedToPort.forEach((c) => this.editor.unConnectConnector(<ConnectorEditor>c.connector)); } } /** * 隐藏 */ public hide() { if(this.created) this.el.style.display = 'none'; } /** * 显示 */ public show() { if(this.created) this.el.style.display = ''; } //#region 数据更新 public updateZoom(zoom : number) { this.el.style.zoom = zoom.toString(); } public updateContent() { if(!this.created) return; if(this.blockStyleSettings.smallTitle || this.blockStyleSettings.noTitle) this.el.setAttribute('data-title', this.name + '\n' + this.description); else{ this.els.elTitleText.innerText = this.name; this.els.elTitle.setAttribute('data-title', this.description); } this.el.setAttribute('data-guid', this.guid); this.els.elTitle.style.color = this.blockStyleSettings.titleColor; this.els.elTitle.style.background = this.blockStyleSettings.titleBakgroundColor; if((!this.portsChangeSettings.userCanAddInputPort && !this.portsChangeSettings.userCanAddOutputPort && !this.parametersChangeSettings.userCanAddInputParameter && !this.parametersChangeSettings.userCanAddOutputParameter)) { this.els.elAddInputBehaviorPort.style.display = 'none'; this.els.elAddOutputBehaviorPort.style.display = 'none'; this.els.elAddInputParamPort.style.display = 'none'; this.els.elAddOutputParamPort.style.display = 'none'; } else { this.els.elAddInputBehaviorPort.style.display = ''; this.els.elAddOutputBehaviorPort.style.display = ''; this.els.elAddInputParamPort.style.display = ''; this.els.elAddOutputParamPort.style.display = ''; this.els.elAddInputBehaviorPort.style.visibility = this.portsChangeSettings.userCanAddInputPort ? '' : 'hidden'; this.els.elAddOutputBehaviorPort.style.visibility = this.portsChangeSettings.userCanAddOutputPort ? '' : 'hidden'; this.els.elAddInputParamPort.style.visibility = this.parametersChangeSettings.userCanAddInputParameter ? '' : 'hidden'; this.els.elAddOutputParamPort.style.visibility = this.parametersChangeSettings.userCanAddOutputParameter ? '' : 'hidden'; } if(this.userCanResize) HtmlUtils.showElement(this.els.elSizeDragger); else HtmlUtils.hideElement(this.els.elSizeDragger); } public updateSelectStatus(selected?:boolean) { if(typeof selected === 'boolean') this.selected = selected; if(!this.created) return; if(this.selected) this.el.classList.add("selected"); else this.el.classList.remove("selected"); } public updateBreakPointStatus() { if(!this.created) return; switch(this.breakpoint) { case 'disable': this.els.elBreakPointStatus.style.display = 'inline-block'; this.els.elBreakPointStatus.classList.add('icon-tx-babianxing'); this.els.elBreakPointStatus.classList.remove('icon-tx-fill-babianxing'); this.els.elBreakPointStatus.setAttribute('data-title', '此单元已禁用断点'); break; case 'enable': this.els.elBreakPointStatus.style.display = 'inline-block'; this.els.elBreakPointStatus.classList.remove('icon-tx-babianxing'); this.els.elBreakPointStatus.classList.add('icon-tx-fill-babianxing'); this.els.elBreakPointStatus.setAttribute('data-title', '此单元已启用断点'); break; case 'none': this.els.elBreakPointStatus.style.display = 'none'; break; } } public updateComment() { if(!this.created || this.blockStyleSettings.noComment) return; this.els.elComment.style.display = this.markOpen ? '' : 'none'; this.els.elCommentClose.style.display = this.markOpen ? '' : 'none'; this.els.elCommentOpen.style.display = this.markOpen ? 'none' : ''; this.els.elCommentText.innerText = this.mark; this.els.elCommentPlaceHolder.style.display = this.mark == '' ? '' : 'none'; } //#endregion //#region 节点元素更新 //=========================== public portsChangeSettings = { userCanAddInputPort: false, userCanAddOutputPort: false, }; public parametersChangeSettings : BlockParametersChangeSettings = { userCanAddInputParameter: false, userCanAddOutputParameter: false, }; private addPortElement(port : BlockPort) { if(this.created) (<BlockPortEditor>port).addPortElement(this); } public createOrReCreatePortCustomEditor(port : BlockPort) { (<BlockPortEditor>port).createOrReCreatePortCustomEditor(); } public updateAllPortElement() { this.allPorts.forEach((p) => this.updatePortElement(p)); } public updateAllParamPort() { this.allPorts.forEach((p) => { if(!p.paramType.isExecute()) p.updateOnputValue(this.currentRunningContext, undefined); }); } public updatePort(port : BlockPort) { this.updatePortElement(port); } public updatePortParamDisplayVal(port : BlockPort) { (<BlockPortEditor>port).updatePortParamDisplayVal(); } private updatePortElement(port : BlockPort) { if(this.created) (<BlockPortEditor>port).updatePortElement(); } private removePortElement(port : BlockPort) { if(this.created) (<BlockPortEditor>port).removePortElement(); } private onPortRemoveCallback(block : BlockEditor, port : BlockPort) { this.unConnectPort(port); } public flushAllPortElementCreateState() { this.allPorts.forEach((port) => { if((<BlockPortEditor>port).editorData == null) { this.addPortElement(port); } }) } public movePortElementUpOrDown(port : BlockPort, move : 'up'|'down') { let portE = (<BlockPortEditor>port); let refEl : Element = null; let parent = portE.editorData.el.parentNode; if(move == 'up') refEl = portE.editorData.el.previousElementSibling; else { let n = portE.editorData.el.nextElementSibling; if(n != null) { refEl = n.nextElementSibling; if(refEl == null) { parent.removeChild(portE.editorData.el); parent.appendChild(portE.editorData.el); } } } if(refEl != null) { parent.removeChild(portE.editorData.el); parent.insertBefore(portE.editorData.el, refEl); } } //#endregion //#region 编辑器显示状态更新 public forceUpdateParamValueToEditor(port : BlockPort) { let portE = (<BlockPortEditor>port); if(portE.editorData.editor != null) portE.editorData.editor.forceUpdateValue(port, portE.editorData.elEditor); } public updatePortConnectStatusElement(port : BlockPort) { (<BlockPortEditor>port).updatePortConnectStatusElement(); } public markBreakPointActiveState(active : boolean) { if(active) { this.el.classList.add('breakpoint-actived'); this.els.elBreakPointArrow.style.display = ''; } else { this.el.classList.remove('breakpoint-actived'); this.els.elBreakPointArrow.style.display = 'none'; } } public markActive() { this.activeFlashCount = 0; if(this.activeFlashInterval == null) { this.el.classList.add('actived'); this.activeFlashInterval = setInterval(() => { this.el.classList.toggle('actived'); this.activeFlashCount++; if(this.activeFlashCount >= 3) this.markDective(true); }, 200); } } public markDective(force = false) { if(force || this.currentRunner.stepMode) { this.el.classList.remove('actived'); clearInterval(this.activeFlashInterval); this.activeFlashInterval = null; Object.keys(this.inputPorts).forEach(key => { let port = (<BlockPort>this.inputPorts[key]); if(port.connectedFromPort.length > 0) port.connectedFromPort.forEach(element => (<ConnectorEditor>element.connector).clearActive()); }); } } public addBottomTip(icon : string, text : string, className : string = '', show = true) { let d = document.createElement('div'); d.setAttribute('class', className); d.innerHTML = '<i class="iconfont '+icon+' mr-2"></i>' + text; this.els.elBottomInfoHost.appendChild(d); this.els.elBottomInfoHost.style.display = ''; return d; } public updateBottomTip(el : HTMLElement, icon : string, text : string, className : string = '') { el.setAttribute('class', className); el.innerHTML = '<i class="iconfont '+icon+' mr-2"></i>' + text; return el; } public deleteBottomTip(el : HTMLElement) { this.els.elBottomInfoHost.removeChild(el); if(this.els.elBottomInfoHost.childNodes.length == 0) this.els.elBottomInfoHost.style.display = 'none'; } private activeFlashInterval : any = null; private activeFlashCount = 0; //#endregion //#region 其他事件 public onUserDeletePort(port : BlockPort) { this.editor.getVue().$confirm('确定删除此端口?', '提示', { type: 'warning', confirmButtonClass: 'el-button-danger', }).then(() => this.deletePort(port.guid)).catch(() => {}); } private callUserAddPort(direction : BlockPortDirection, type : 'execute'|'param') { let v = this.onUserAddPort(this, direction, type); if(CommonUtils.isArray(v)) { let arr = <BlockPortRegData[]>v; arr.forEach((p) => this.addPort(p, true)); }else { this.addPort(<BlockPortRegData>v, true) } return v; } private onUserAddInputPort() { this.callUserAddPort('input', 'execute'); } private onUserAddOutputPort() { this.callUserAddPort('output', 'execute'); } private onUserAddInputParam() { this.callUserAddPort('input', 'param'); } private onUserAddOutputParam() { this.callUserAddPort('output', 'param'); } private onResize() { this.size.Set( this.el.offsetWidth, this.el.offsetHeight ) } //#endregion //#region 鼠标事件 public mouseDown = false; public mouseConnectingPort = false; public mouseDownInPort = false; private mouseLastDownPos : Vector2 = new Vector2(); private mouseLastDownPosInViewPort : Vector2 = new Vector2(); private lastBlockPos : Vector2 = new Vector2(); private lastMovedBlock = false; private lastBlockSize : Vector2 = new Vector2(); private minBlockSize : Vector2 = new Vector2(); private currentSizeType = 0; public isLastMovedBlock() { return this.lastMovedBlock; } public updateLastPos() { this.lastBlockPos.Set(this.position); } public getLastPos() { return this.lastBlockPos; } public getCurrentSizeType() { return this.currentSizeType; } private onMouseEnter(e : MouseEvent) { this.hover = true; } private onMouseOut(e : MouseEvent) { this.hover = false; } private onMouseMove(e : MouseEvent) { if(this.mouseDown) { if(typeof this.onMouseEvent === 'function' && this.onMouseEvent(this, 'move', e)) return true; if(e.buttons == 1){ //Resize //===================== if(this.currentSizeType) { let mousePos = this.editor.windowPosToViewPortPos(new Vector2(e.x, e.y)); let size = new Vector2(this.size.x, this.size.y); if (((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) && ((this.currentSizeType & SIZE_TOP) == SIZE_TOP)) { //左上 size.x = (this.lastBlockPos.x + this.lastBlockSize.x - mousePos.x); size.y = (this.lastBlockPos.y + this.lastBlockSize.y - mousePos.y); this.setPos(mousePos); } else if(((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM) && ((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT)) { //右下 size.x = (mousePos.x - this.lastBlockPos.x); size.y = (mousePos.y - this.lastBlockPos.y); } else if (((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) && ((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM)) { //左下 size.x = (this.lastBlockPos.x + this.lastBlockSize.x - mousePos.x); size.y = (mousePos.y - this.lastBlockPos.y); this.setPos(new Vector2(mousePos.x, this.position.y)); } else if (((this.currentSizeType & SIZE_TOP) == SIZE_TOP) && ((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT)) { //右上 size.x = (mousePos.x - this.lastBlockPos.x); size.y = (this.lastBlockPos.y + this.lastBlockSize.y - mousePos.y); this.setPos(new Vector2(this.position.x, mousePos.y)); } else if((this.currentSizeType & SIZE_TOP) == SIZE_TOP) { //上 size.y = (this.lastBlockPos.y + this.lastBlockSize.y - mousePos.y); this.setPos(new Vector2(this.position.x, mousePos.y)); } else if((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM) { //下 size.y = (mousePos.y - this.lastBlockPos.y); } else if((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) { //左 size.x = (this.lastBlockPos.x + this.lastBlockSize.x - mousePos.x); this.setPos(new Vector2(mousePos.x, this.position.y)); } else if((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT) { //右 size.x = (mousePos.x - this.lastBlockPos.x); } if(size.x < this.minBlockSize.x) size.x = this.minBlockSize.x; if(size.y < this.minBlockSize.y) size.y = this.minBlockSize.y; this.setSize(size); } //Move //===================== else if(!this.mouseDownInPort && !this.mouseConnectingPort) { let zoom = 1 / this.editor.getViewZoom(); let pos = new Vector2( this.lastBlockPos.x + (e.x * zoom - this.mouseLastDownPos.x * zoom), this.lastBlockPos.y + (e.y * zoom - this.mouseLastDownPos.y * zoom) ); if(pos.x != this.position.x || pos.y != this.position.y) { this.lastMovedBlock = true; this.setPos(pos); this.editor.onMoveBlock(this, new Vector2(e.x * zoom - this.mouseLastDownPos.x * zoom, e.y * zoom - this.mouseLastDownPos.y * zoom)); //如果当前块没有选中,在这里切换选中状态 if(!this.selected) { let multiSelectBlocks = this.editor.getMultiSelectedBlocks(); if(multiSelectBlocks.length == 0 || multiSelectBlocks.contains(this)) { this.updateSelectStatus(true); this.editor.onUserSelectBlock(this, true); }else { this.editor.unSelectAllBlocks(); this.updateSelectStatus(true); this.editor.onUserSelectBlock(this, false); } } } } return true; } } else if(this.userCanResize) { //鼠标移动到边缘显示调整大小样式 this.testInResize(e); } return false; } private onMouseDown(e : MouseEvent) { if(this.blockStyleSettings.layer == 'background' && this.editor.isAnyConnectorHover()) return; if(!this.testIsDownInControl(e)) { this.mouseDown = true; this.mouseLastDownPos.Set(e.x, e.y); this.mouseLastDownPosInViewPort = this.editor.windowPosToViewPortPos(new Vector2(e.x, e.y)); this.lastMovedBlock = false; this.lastBlockPos.Set(this.position); this.lastBlockSize.Set(this.size); if(this.userCanResize) { this.minBlockSize.x = this.el.style.minWidth ? parseInt(this.el.style.minWidth) : 111; this.minBlockSize.y = this.el.style.minWidth ? parseInt(this.el.style.minHeight) : 100; this.testInResize(e); } if(typeof this.onMouseEvent === 'function') this.onMouseEvent(this, 'down', e); document.addEventListener('mousemove', this.fnonMouseMove); document.addEventListener('mouseup', this.fnonMouseUp); e.stopPropagation(); } this.updateCursor(); } private onMouseUp(e : MouseEvent) { if(this.mouseDown) { this.mouseDown = false; if(!this.testIsDownInControl(e)){ if(this.editor.isConnectorSelected()) this.editor.unSelectAllConnector(); if(this.lastMovedBlock) { this.editor.onMoveBlockEnd(this); }else if(this.editor.getMultiSelectedBlocks().length == 0 || e.button == 0) { this.updateSelectStatus(this.editor.onUserSelectBlock(this, true)); } if(typeof this.onMouseEvent === 'function') this.onMouseEvent(this, 'up', e); } this.updateCursor(); } document.removeEventListener('mousemove', this.fnonMouseMove); document.removeEventListener('mouseup', this.fnonMouseUp); } private onMouseWhell(e : WheelEvent) { if(this.testIsDownInControl(e)) e.stopPropagation(); } private onContextMenu(e : MouseEvent) { if(this.editor.isConnectorSelected()) { this.editor.showConnectorRightMenu(new Vector2(e.x, e.y)); }else { e.stopPropagation(); e.preventDefault(); this.editor.showBlockRightMenu(this, new Vector2(e.x, e.y)); } return false; } private testInResize(e : MouseEvent) { let pos = this.editor.windowPosToViewPortPos(new Vector2(e.x, e.y)); pos.substract(this.position); this.currentSizeType = 0; if(pos.x <= 6) this.currentSizeType |= SIZE_LEFT; else if(pos.x > this.size.x - 6) this.currentSizeType |= SIZE_RIGHT; if(pos.y <= 6) this.currentSizeType |= SIZE_TOP; else if(pos.y > this.size.y - 6) this.currentSizeType |= SIZE_BOTTOM; if(pos.x >= this.size.x - 20 && pos.y >= this.size.y - 20) this.currentSizeType |= (SIZE_BOTTOM | SIZE_RIGHT); this.updateCursor(); } private updateCursor() { if(this.currentSizeType > 0) { if( (((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) && ((this.currentSizeType & SIZE_TOP) == SIZE_TOP)) || (((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM) && ((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT)) ) this.el.style.cursor = 'nwse-resize'; else if( (((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) && ((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM)) || (((this.currentSizeType & SIZE_TOP) == SIZE_TOP) && ((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT)) ) this.el.style.cursor = 'nesw-resize'; else if(((this.currentSizeType & SIZE_TOP) == SIZE_TOP) || ((this.currentSizeType & SIZE_BOTTOM) == SIZE_BOTTOM)) this.el.style.cursor = 'ns-resize'; else if(((this.currentSizeType & SIZE_LEFT) == SIZE_LEFT) || ((this.currentSizeType & SIZE_RIGHT) == SIZE_RIGHT)) this.el.style.cursor = 'ew-resize'; else this.el.style.cursor = 'default'; }else if(this.mouseDown) { this.el.style.cursor = 'move'; }else { this.el.style.cursor = 'default'; } } //#endregion private testIsDownInControl(e : MouseEvent){ let target = (<HTMLElement>e.target); return (HtmlUtils.isEventInControl(e) || target.classList.contains('flow-block-no-move') || target.classList.contains('param-editor') || target.classList.contains('port-delete') || target.classList.contains('port') || target.classList.contains('custom-editor')); } //抛出错误处理 public throwError(err : string, port ?: BlockPort, level : 'warning'|'error' = 'error', breakFlow = false) { //添加错误提示 let errorNode = document.createElement('div'); errorNode.classList.add('block-error'); errorNode.classList.add(level); errorNode.innerHTML = `<i class="iconfont ${level==='warning'?'icon-error-1':'icon-error-'}"></i><span>${err}</span>`; ToolTipUtils.registerElementTooltip(errorNode) ToolTipUtils.updateElementTooltip(errorNode, errorNode.innerHTML); this.els.elBottomInfoHost.appendChild(errorNode); this.els.elBottomInfoHost.style.display = ''; if(port != null) { (<BlockPortEditor>port).editorData.forceDotErrorState = true; (<BlockPortEditor>port).updatePortConnectStatusElement(); } super.throwError(err, port, level, breakFlow); } /** * 清空所有错误 */ public clearErrors() { let nodes = this.els.elBottomInfoHost.childNodes; for(let i = nodes.length - 1; i >= 0; i--) { if((<HTMLElement>nodes[i]).classList.contains('block-error')) this.els.elBottomInfoHost.removeChild(nodes[i]); } if(this.els.elBottomInfoHost.childNodes.length == 0) this.els.elBottomInfoHost.style.display = 'none'; } private fnonMouseMove : MouseEventDelegate = null; private fnonMouseUp : MouseEventDelegate = null; public onCreateCustomEditor : BlockEditorComponentCreateFn = null; public onCreatePortCustomEditor : BlockPortEditorComponentCreateFn = null; public onUserAddPort : OnUserAddPortCallback = null; public onSave : OnBlockEditorEventCallback = null; public onMouseEvent : BlockMouseEventFn = null; //#region 端口连接处理事件 public connectedPortCount = 0; public portAnyFlexables : BlockPortAnyFlexablesData = {}; public isAnyPortConnected() { return this.connectedPortCount > 0; } public invokeOnPortConnect(port : BlockPort, portSource : BlockPort) { this.onPortConnect.invoke(this, port, portSource); this.connectedPortCount ++; } public invokeOnPortUnConnect(port : BlockPort) { this.onPortUnConnect.invoke(this, port); this.connectedPortCount--; if(!port.paramType.isExecute()) { let flexableKeys = Object.keys(this.portAnyFlexables); flexableKeys.forEach((key) => BlockUtils.testAndResetFlexablePortType(<BlockEditor><any>this, key) ); } } //弹性端口的参数变更 public doChangeBlockFlexablePort(port : BlockPort) { if(!port.paramType.isExecute()) { let flexableKeys = Object.keys(this.portAnyFlexables); for(let i = 0; i < flexableKeys.length; i++) { let key = flexableKeys[i]; let v = BlockUtils.doChangeBlockFlexablePort(this, port, key); if(CommonUtils.isDefined(v)) { if(typeof this.portAnyFlexables[key].setResultToData == 'string') this.data[this.portAnyFlexables[key].setResultToData] = v; if(typeof this.portAnyFlexables[key].setResultToOptions == 'string') this.options[this.portAnyFlexables[key].setResultToOptions] = v; } }; } } public testAndChangeFlexablePortType(portCurent: BlockPort, portTarget: BlockPort) { let currentIsAny = (portCurent.paramType.isAny() || (portCurent.paramSetType == 'dictionary' && portCurent.paramDictionaryKeyType.isAny())); let targetIsAny = (portTarget.paramType.isAny() || (portTarget.paramSetType == 'dictionary' && portTarget.paramDictionaryKeyType.isAny())); if(currentIsAny && !targetIsAny) { //目标 》 当前 if(portCurent.paramSetType == 'dictionary') portCurent.paramDictionaryKeyType.set(portTarget.paramDictionaryKeyType); this.changePortParamType(portCurent, portTarget.paramType); this.doChangeBlockFlexablePort(portCurent); return true; } else if(!currentIsAny && targetIsAny) { //当前 》 目标 if(portTarget.paramSetType == 'dictionary') portTarget.paramDictionaryKeyType.set(portCurent.paramDictionaryKeyType); portTarget.paramType.set(portCurent.paramType); (<BlockEditor>portTarget.parent).changePortParamType(portTarget, portCurent.paramType); (<BlockEditor>portTarget.parent).doChangeBlockFlexablePort(portTarget); return true; } return false; } //#endregion } /** * 单元的编辑器使用数据 */ export class BlockEditorHTMLData { elInputPorts : HTMLDivElement = null; elOutputPorts : HTMLDivElement = null; elAddInputBehaviorPort : HTMLElement = null; elAddOutputBehaviorPort : HTMLElement = null; elAddInputParamPort : HTMLElement = null; elAddOutputParamPort : HTMLElement = null; elBottomInfoHost : HTMLElement = null; elBackground : HTMLDivElement = null; elTitle : HTMLDivElement = null; elTitleText : HTMLElement = null; elCustomEditor : HTMLDivElement = null; elLogo : HTMLDivElement = null; elLogoRight : HTMLDivElement = null; elLogoBottom : HTMLDivElement = null; elSizeDragger : HTMLDivElement = null; elBreakPointArrow : HTMLDivElement = null; elBreakPointStatus : HTMLDivElement = null ; elComment : HTMLDivElement = null; elCommentText : HTMLDivElement = null; elCommentPlaceHolder : HTMLSpanElement = null; elCommentOpen : HTMLElement = null; elCommentClose : HTMLElement = null; }
the_stack
import { Observable, of, from, isObservable, combineLatest, throwError } from "rxjs"; import { map, catchError, switchMap } from "rxjs/operators"; import { forEach, isIterable } from "iterall"; import memoize from "memoizee"; import { ExecutionResult, DocumentNode, GraphQLObjectType, GraphQLSchema, FieldNode, GraphQLField, GraphQLOutputType, GraphQLFieldResolver, isObjectType, isNonNullType, responsePathAsArray, ExecutionArgs, OperationDefinitionNode, ResponsePath, GraphQLResolveInfo, GraphQLError, getOperationRootType, GraphQLList, GraphQLLeafType, isListType, isLeafType, isAbstractType, GraphQLAbstractType, } from "graphql"; import { ExecutionResultDataDefault, assertValidExecutionArguments, buildExecutionContext, ExecutionContext, collectFields, buildResolveInfo, getFieldDef, } from 'graphql/execution/execute'; import Maybe from 'graphql/tsutils/Maybe'; import { addPath } from "graphql/jsutils/Path"; import combinePropsLatest from "../rxutils/combinePropsLatest"; import { getArgumentValues } from "graphql/execution/values"; import { locatedError } from "graphql/error"; import invariant from "../jstutils/invariant"; import isInvalid from "../jstutils/isInvalid"; import inspect from "../jstutils/inspect"; import isNullish from "../jstutils/isNullish"; import mapPromiseToObservale from "../rxutils/mapPromiseToObservale"; import mapToFirstValue from "../rxutils/mapToFirstValue"; /** * Implements the "Evaluating requests" section of the GraphQL specification. * * Returns a RxJS's `Observable` of `ExecutionResult`. * * Note: reactive equivalent of `graphql-js`'s `execute`. */ export function execute<TData = ExecutionResultDataDefault>(args: ExecutionArgs) : Observable<ExecutionResult<TData>>; export function execute<TData = ExecutionResultDataDefault>( schema: GraphQLSchema, document: DocumentNode, rootValue?: unknown, contextValue?: unknown, variableValues?: Maybe<{ [key: string]: unknown }>, operationName?: Maybe<string>, fieldResolver?: Maybe<GraphQLFieldResolver<any, any>> ): Observable<ExecutionResult<TData>>; export function execute<TData>( argsOrSchema, document?, rootValue?, contextValue?, variableValues?, operationName?, fieldResolver?, ) { return isExecutionArgs(argsOrSchema, arguments) ? executeImpl<TData>( argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, ) : executeImpl<TData>( argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, ); } function isExecutionArgs( _argsOrSchema: GraphQLSchema | ExecutionArgs, args: IArguments ): _argsOrSchema is ExecutionArgs { return args.length === 1; } function executeImpl<TData>( schema: GraphQLSchema, document: DocumentNode, rootValue?: unknown, contextValue?: unknown, variableValues?: Maybe<{ [key: string]: unknown }>, operationName?: Maybe<string>, fieldResolver?: Maybe<GraphQLFieldResolver<any, any>> ): Observable<ExecutionResult<TData>> { // If arguments are missing or incorrect, throw an error. assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, // a "Response" with only errors is returned. const exeContext = buildExecutionContext( schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, ); // Return early errors if execution context failed. if (!isValidExecutionContext(exeContext)) { return of({ errors: exeContext }); } const data = executeOperation(exeContext, exeContext.operation, rootValue); return buildResponse<TData>(exeContext, data); } /** * Returns true if subject is a valid `ExecutionContext` and not array of `GraphQLError`. * * Note: reference implementation does a `Array.isArray` in `executeImpl` function body. In comparison, * `isValidExecutionContext` ensures typing correctness with type assertion. * @param subject value to be tested */ function isValidExecutionContext(subject: ReadonlyArray<GraphQLError> | ExecutionContext): subject is ExecutionContext { return !Array.isArray(subject); } /** * Given a completed execution context and data as Observable, build the `{ errors, data }` * response defined by the "Response" section of the GraphQL specification. * * Note: reactive equivalent of `graphql-js`'s `buildResponse`. */ function buildResponse<TData>( exeContext: ExecutionContext, data: Observable<{ [key: string]: unknown} | null> ): Observable<ExecutionResult<TData>> { // @ts-ignore `'{ [key: string]: unknown; }' is assignable to the constraint of type 'TData', but 'TData' could be instantiated with a different subtype of constraint '{}'` return data.pipe(map(d => { if (exeContext.errors.length === 0 && d !== null) { return { data: d, } } else { return { errors: exeContext.errors, data: d, } } })) } /** * Implements the "Evaluating operations" section of the spec. * * Note: reactive equivalent of `graphql-js`'s `executeOperation`. The difference lies * in the fact that, here, a RxJS's `Observable` is returned instead of a `Promise` (or plain value). */ function executeOperation( exeContext: ExecutionContext, operation: OperationDefinitionNode, rootValue: unknown ): Observable<({ [key: string]: unknown }) | null> { const type = getOperationRootType(exeContext.schema, operation); const fields = collectFields( exeContext, type, operation.selectionSet, Object.create(null), Object.create(null), ); const path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, // at which point we still log the error and null the parent field, which // in this case is the entire response. // // Similar to completeValueCatchingError. try { const result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); return result; } catch (error) { exeContext.errors.push(error); return of(null); } } /** * Implements the "Evaluating selection sets" section of the spec for "write" mode, * ie with serial execution. * * Note: reactive equivalent of `graphql-js`'s `executeFieldsSerially`. The difference * lies in the fact that: * - here, a RxJS's `Observable` is returned instead of a `Promise` (or plain value) * - in `graphql-js`, serial execution is implemented by waiting, one by one, for the * resolution of the `Promise` returned by the resolution of each `field`. Here we wait * for the first value of the resolved `Observable` to be emited before passing to * the next field resolution. * * Thus, in case of resolvers resolving `Promises`, we match * reference implementation's behavior. */ function executeFieldsSerially( exeContext: ExecutionContext, parentType: GraphQLObjectType, sourceValue: unknown, path: ResponsePath | undefined, fields: { [key: string]: FieldNode[]} ): Observable<{ [key: string]: unknown }> { const results: { [key: string]: Observable<unknown> } = {}; // during iteration, we keep track of the result of the previously // resolved field so that we can queue the resolution of the next field // after the emition of the first value of the previous result. let previousResolvedResult: (Observable<unknown> | undefined); for (let i = 0, keys = Object.keys(fields); i < keys.length; ++i) { const responseName = keys[i]; const fieldNodes = fields[responseName]; const fieldPath = addPath(path, responseName); const resolve = () => resolveField( exeContext, parentType, sourceValue, fieldNodes, fieldPath, ); const result = previousResolvedResult ? // queuing `resolve` after first emition of `previousResolvedResult` // using `mapToFirstValue` to get an Observable that represents this process mapToFirstValue(previousResolvedResult, resolve) : // first iteration: no previous result need to queue after resolve(); previousResolvedResult = result; if (result !== undefined) { results[responseName] = result; } } return combinePropsLatest(results); } /** * Implements the "Evaluating selection sets" section of the spec * for "read" mode. * * Note: reactive equivalent of `graphql-js`'s `executeFields`. The difference lies * in the fact that, here, a RxJS's `Observable` is returned instead of a `Promise` (or plain value). */ function executeFields( exeContext: ExecutionContext, parentType: GraphQLObjectType, sourceValue: unknown, path: ResponsePath | undefined, fields: { [key: string]: FieldNode[] } ): Observable<{ [key: string]: unknown }> { const results: { [key: string]: Observable<unknown> } = {}; for (let i = 0, keys = Object.keys(fields); i < keys.length; ++i) { const responseName = keys[i]; const fieldNodes = fields[responseName]; const fieldPath = addPath(path, responseName); const result = resolveField( exeContext, parentType, sourceValue, fieldNodes, fieldPath, ); if (result !== undefined) { results[responseName] = result; } } return combinePropsLatest(results); } /** * Resolves the field on the given source object. * * Note: reactive equivalent of `graphql-js`'s `resolveField`. The difference lies * in the fact that, here, a RxJS's `Observable` is returned instead of a `Promise` (or plain value). */ function resolveField( exeContext: ExecutionContext, parentType: GraphQLObjectType, source: unknown, fieldNodes: FieldNode[], path: ResponsePath, ): Observable<unknown> { const fieldNode = fieldNodes[0]; const fieldName = fieldNode.name.value; const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); if (!fieldDef) { return of(undefined); } const resolveFn = fieldDef.resolve || exeContext.fieldResolver; const info = buildResolveInfo( exeContext, fieldDef, fieldNodes, parentType, path, ); const result = resolveFieldValueOrError( exeContext, fieldDef, fieldNodes, resolveFn, source, info, ); return completeValueCatchingError( exeContext, fieldDef.type, fieldNodes, info, path, result, ); } /** * Note: reactive equivalent of `graphql-js`'s `resolveFieldValueOrError`. The difference lies * in the fact that, here, a RxJS's `Observable` is returned. */ function resolveFieldValueOrError<TSource>( exeContext: ExecutionContext, fieldDef: GraphQLField<TSource, any>, fieldNodes: ReadonlyArray<FieldNode>, resolveFn: GraphQLFieldResolver<TSource, any>, source: TSource, info: GraphQLResolveInfo ): (Error | Observable<unknown>) { try { const args = getArgumentValues( fieldDef, fieldNodes[0], exeContext.variableValues, ); const contextValue = exeContext.contextValue; const result = resolveFn(source, args, contextValue, info); if (isObservable(result)) { return result .pipe(catchError(err => throwError(asErrorInstance(err)))); } if (result instanceof Promise) { return from(result) .pipe(catchError(err => throwError(asErrorInstance(err)))); } // it lloks like plain value return of(result) } catch (err) { return asErrorInstance(err); } } /** * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a * consistent Error interface. * * Note: copy-paste of `graphql-js`'s `asErrorInstance` in `execute.js`. */ function asErrorInstance(error: unknown): Error { if (error instanceof Error) { return error; } return new Error('Unexpected error value: ' + inspect(error)); } /** * This is a small wrapper around completeValue which detects and logs errors * in the execution context. * * Note: reactive equivalent of `graphql-js`'s `completeValueCatchingError`. The difference lies * in the fact that, here, a RxJS's `Observable` is returned. */ function completeValueCatchingError( exeContext: ExecutionContext, returnType: GraphQLOutputType, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, path: ResponsePath, result: Error | Observable<unknown>, ): Observable<unknown> { if (result instanceof Error) { return of(handleFieldError( result, fieldNodes, path, returnType, exeContext, )); } try { return result .pipe( switchMap(res => completeValue( exeContext, returnType, fieldNodes, info, path, res, ) ) ) .pipe(catchError(err => of(handleFieldError( asErrorInstance(err), fieldNodes, path, returnType, exeContext, )))) } catch (error) { return of(handleFieldError( asErrorInstance(error), fieldNodes, path, returnType, exeContext, )) } } /** * Note: copy-paste of `graphql-js`'s `handleFieldError`. */ function handleFieldError( rawError: Error, fieldNodes: ReadonlyArray<FieldNode>, path: ResponsePath, returnType: GraphQLOutputType, exeContext: ExecutionContext, ): null { const error = locatedError( asErrorInstance(rawError), fieldNodes, responsePathAsArray(path), ); // If the field type is non-nullable, then it is resolved without any // protection from errors, however it still properly locates the error. if (isNonNullType(returnType)) { throw error; } // Otherwise, error protection is applied, logging the error and resolving // a null value for this field if one is encountered. exeContext.errors.push(error); return null; } /** * Implements the instructions for completeValue as defined in the * "Field entries" section of the spec. * * Note: reactive equivalent of `graphql-js`'s `completeValue`. The difference lies * in the fact that, here, we deal with RxJS's `Observable` and an `Observable` is returned. */ function completeValue( exeContext: ExecutionContext, returnType: GraphQLOutputType, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, path: ResponsePath, result: unknown, ): Observable<unknown> { // If result is an Error, throw a located error. if (result instanceof Error) { throw result; } // If field type is NonNull, complete for inner type, and throw field error // if result is null. if (isNonNullType(returnType)) { const completed = completeValue( exeContext, returnType.ofType, fieldNodes, info, path, result, ); if (completed === null) { throw new Error( `Cannot return null for non-nullable field ${info.parentType.name}.${ info.fieldName }.`, ); } return completed; } // If result value is null-ish (null, undefined, or NaN) then return null. if (isNullish(result)) { return of(null); } // If field type is List, complete each item in the list with the inner type if (isListType(returnType)) { return completeListValue( exeContext, returnType, fieldNodes, info, path, result, ); } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, // returning null if serialization is not possible. if (isLeafType(returnType)) { return completeLeafValue(returnType, result); } // If field type is an abstract type, Interface or Union, determine the // runtime Object type and complete for that type. if (isAbstractType(returnType)) { return completeAbstractValue( exeContext, returnType, fieldNodes, info, path, result, ); } // If field type is Object, execute and complete all sub-selections. if (isObjectType(returnType)) { return completeObjectValue( exeContext, returnType, fieldNodes, info, path, result, ); } // Not reachable. All possible output types have been considered. /* istanbul ignore next */ throw new Error( `Cannot complete value of unexpected type "${inspect( (returnType), )}".`, ); }; /** * Complete a list value by completing each item in the list with the * inner type * * Note: reactive equivalent of `graphql-js`'s `completeListValue`. The difference lies * in the fact that, here, we deal with RxJS's `Observable` and an `Observable` is returned. */ function completeListValue( exeContext: ExecutionContext, returnType: GraphQLList<GraphQLOutputType>, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, path: ResponsePath, result: unknown, ): Observable<ReadonlyArray<unknown>> { invariant( isIterable(result), `Expected Iterable, but did not find one for field ${ info.parentType.name }.${info.fieldName}.`, ); // for typescript only: asserts `result` type if (!isIterable(result)) throw new Error('Expected Iterable'); const itemType = returnType.ofType; const completedResults: Observable<unknown>[] = []; forEach(result, (item, index) => { const fieldPath = addPath(path, index); const completedItem = completeValueCatchingError( exeContext, itemType, fieldNodes, info, fieldPath, of(item), ); completedResults.push(completedItem); }); // avoid blocking in switchMap with empty arrays if (completedResults.length === 0) return of([]); return combineLatest(completedResults); } /** * Complete a Scalar or Enum by serializing to a valid value, returning * null if serialization is not possible. * * Note: reactive equivalent of `graphql-js`'s `completeLeafValue`. The difference lies * in the fact that, here, an `Observable` is returned. */ function completeLeafValue(returnType: GraphQLLeafType, result: unknown): Observable<unknown> { invariant(returnType.serialize, 'Missing serialize method on type'); const serializedResult = returnType.serialize(result); if (isInvalid(serializedResult)) { throw new Error( `Expected a value of type "${inspect(returnType)}" but ` + `received: ${inspect(result)}`, ); } return of(serializedResult); } /** * Complete a value of an abstract type by determining the runtime object type * of that value, then complete the value for that type. * * Note: reactive equivalent of `graphql-js`'s `completeAbstractValue`. The difference lies * in the fact that, here, we deal with asychronisity in a Observable fashion and that * an `Observable` is returned. */ function completeAbstractValue( exeContext: ExecutionContext, returnType: GraphQLAbstractType, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, path: ResponsePath, result: unknown, ): Observable<{ [key: string]: unknown }> { const runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); return mapPromiseToObservale( Promise.resolve(runtimeType), resolvedRuntimeType => completeObjectValue( exeContext, ensureValidRuntimeType( resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result, ), fieldNodes, info, path, result, ) ) } /** * Note: copy-pasted from `graphql-js`'s `ensureValidRuntimeType`. */ function ensureValidRuntimeType( runtimeTypeOrName: Maybe<GraphQLObjectType> | string, exeContext: ExecutionContext, returnType: GraphQLAbstractType, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, result: unknown, ): GraphQLObjectType { const runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; if (!isObjectType(runtimeType)) { throw new GraphQLError( `Abstract type ${returnType.name} must resolve to an Object type at ` + `runtime for field ${info.parentType.name}.${info.fieldName} with ` + `value ${inspect(result)}, received "${inspect(runtimeType)}". ` + `Either the ${returnType.name} type should provide a "resolveType" ` + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes, ); } if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { throw new GraphQLError( `Runtime Object type "${runtimeType.name}" is not a possible type ` + `for "${returnType.name}".`, fieldNodes, ); } return runtimeType; } /** * Complete an Object value by executing all sub-selections. * * Note: reactive equivalent of `graphql-js`'s `completeObjectValue`. The difference lies * in the fact that, here, we deal with asychronisity in a Observable fashion and that * an `Observable` is returned. */ function completeObjectValue( exeContext: ExecutionContext, returnType: GraphQLObjectType, fieldNodes: ReadonlyArray<FieldNode>, info: GraphQLResolveInfo, path: ResponsePath, result: unknown, ): Observable<{ [key: string]: unknown }> { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if (returnType.isTypeOf) { const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); if (isTypeOf instanceof Promise) { return mapPromiseToObservale( isTypeOf, resolvedIsTypeOf => { if (!resolvedIsTypeOf) { throw invalidReturnTypeError(returnType, result, fieldNodes); } return collectAndExecuteSubfields( exeContext, returnType, fieldNodes, path, result, ); }) } if (!isTypeOf) { throw invalidReturnTypeError(returnType, result, fieldNodes); } } return collectAndExecuteSubfields( exeContext, returnType, fieldNodes, path, result, ); } /** * * Note: copy-pasted from `graphql-js`. */ function invalidReturnTypeError( returnType: GraphQLObjectType, result: unknown, fieldNodes: ReadonlyArray<FieldNode>, ): GraphQLError { return new GraphQLError( `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, fieldNodes, ); } /** * * Note: reactive equivalent of `graphql-js`'s `collectAndExecuteSubfields`. The difference lies * in the fact that, here, an `Observable` is returned. */ function collectAndExecuteSubfields( exeContext: ExecutionContext, returnType: GraphQLObjectType, fieldNodes: ReadonlyArray<FieldNode>, path: ResponsePath, result: unknown, ): Observable<{ [key: string]: unknown }> { // Collect sub-fields to execute to complete this value. const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); return executeFields(exeContext, returnType, result, path, subFieldNodes); } /** * A memoized collection of relevant subfields with regard to the return * type. Memoizing ensures the subfields are not repeatedly calculated, which * saves overhead when resolving lists of values. * * Note: copy-pasted from `graphql-js`. The difference lies in the fact that * `graphql-js` implements its own memoization, while we use `memoizee` package. */ const collectSubfields = memoize(_collectSubfields); function _collectSubfields( exeContext: ExecutionContext, returnType: GraphQLObjectType, fieldNodes: ReadonlyArray<FieldNode>, ): { [key: string]: FieldNode[] } { let subFieldNodes = Object.create(null); const visitedFragmentNames = Object.create(null); for (let i = 0; i < fieldNodes.length; i++) { const selectionSet = fieldNodes[i].selectionSet; if (selectionSet) { subFieldNodes = collectFields( exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames, ); } } return subFieldNodes; } type MaybePromise<T> = T | Promise<T>; /** * If a resolveType function is not given, then a default resolve behavior is * used which attempts two strategies: * * First, See if the provided value has a `__typename` field defined, if so, use * that value as name of the resolved type. * * Otherwise, test each possible type for the abstract type by calling * isTypeOf for the object being coerced, returning the first type that matches. * Note: copy-pasted from `graphql-js` */ function defaultResolveTypeFn( value: unknown, contextValue: unknown, info: GraphQLResolveInfo, abstractType: GraphQLAbstractType, ): MaybePromise<Maybe<GraphQLObjectType> | string> { // First, look for `__typename`. if ( typeof value === 'object' && value !== null && typeof value['__typename'] === 'string' ) { return value['__typename']; } // Otherwise, test each possible type. const possibleTypes = info.schema.getPossibleTypes(abstractType); const promisedIsTypeOfResults: Promise<boolean>[] = []; for (let i = 0; i < possibleTypes.length; i++) { const type = possibleTypes[i]; if (type.isTypeOf) { const isTypeOfResult = type.isTypeOf(value, contextValue, info); if (isTypeOfResult instanceof Promise) { promisedIsTypeOfResults[i] = isTypeOfResult; } else if (isTypeOfResult) { return type; } } } if (promisedIsTypeOfResults.length) { return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { for (let i = 0; i < isTypeOfResults.length; i++) { if (isTypeOfResults[i]) { return possibleTypes[i]; } } }); } }
the_stack
import { Map } from 'immutable' import { connect } from 'react-redux' import { getTranslate, getActiveLanguage } from 'react-localize-redux' import { withStyles } from '@material-ui/core/styles' import Button from '@material-ui/core/Button' import Dialog from '@material-ui/core/Dialog' import DialogActions from '@material-ui/core/DialogActions' import DialogContent from '@material-ui/core/DialogContent' import DialogTitle from '@material-ui/core/DialogTitle' import EventListener from 'react-event-listener' import FormControl from '@material-ui/core/FormControl' import FormHelperText from '@material-ui/core/FormHelperText' import Input from '@material-ui/core/Input' import InputLabel from '@material-ui/core/InputLabel' import MenuItem from '@material-ui/core/MenuItem' import Paper from '@material-ui/core/Paper' import PropTypes from 'prop-types' import React, { Component } from 'react' import Select from '@material-ui/core/Select' import moment from 'moment/moment' import { ShippingAddress } from 'core/domain/shippings' import AppDialogTitle from 'layouts/dialogTitle' import ImageGallery from 'components/imageGallery' import ImgCover from 'components/imgCover' import UserAvatarComponent from 'components/userAvatar' import * as shippingsActions from 'store/actions/shippingsActions' import * as userActions from 'store/actions/userActions' import { IEditProfileComponentProps } from './IEditProfileComponentProps' import { IEditProfileComponentState } from './IEditProfileComponentState' const styles = (theme: any) => ({ dialogTitle: { padding: 0 }, dialogContentRoot: { maxHeight: 400, minWidth: 330, [theme.breakpoints.down('xs')]: { maxHeight: '100%' } }, fullPageXs: { [theme.breakpoints.down('xs')]: { width: '100%', height: '100%', margin: 0 } }, fixedDownStickyXS: { [theme.breakpoints.down('xs')]: { position: 'fixed', bottom: 0, right: 0, background: 'white', width: '100%' } }, bottomPaperSpace: { height: 16, [theme.breakpoints.down('xs')]: { height: 90 } }, box: { padding: '0px 24px 0px', display: 'flex' }, bottomTextSpace: { marginBottom: 15 }, dayPicker: { width: '100%', padding: '13px 0px 8px' }, formHelperText: { color: '#f62f5e' } }) /** * Create component class */ export class EditProfileComponent extends Component< IEditProfileComponentProps, IEditProfileComponentState > { static propTypes = { /** * User full name */ fullName: PropTypes.string.isRequired } styles = { avatar: { border: '2px solid rgb(255, 255, 255)' }, paper: { width: '90%', height: '100%', margin: '0 auto', display: 'block' }, title: { padding: '24px 24px 20px 24px', font: '500 20px Roboto,RobotoDraft,Helvetica,Arial,sans-serif', display: 'flex', wordWrap: 'break-word', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden', flexGrow: 1 }, actions: { display: 'flex', justifyContent: 'flex-end', padding: '24px 24px 20px' }, updateButton: { marginLeft: '10px' }, dialogGallery: { width: '', maxWidth: '530px', borderRadius: '4px' }, iconButtonSmall: {}, iconButton: {} } /** * Component constructor * @param {object} props is an object properties of component */ constructor(props: IEditProfileComponentProps) { super(props) // Defaul state this.state = { /** * If it's true the winow is in small size */ isSmall: false, /** * User tag line input value */ tagLineInput: '', /** * User full name input value */ fullNameInput: '', /** * Error message of full name input */ fullNameInputError: '', /** * User banner address */ banner: 'https://firebasestorage.googleapis.com/v0/b/open-social-33d92.appspot.com/o/images%2F751145a1-9488-46fd-a97e-04018665a6d3.JPG?alt=media&token=1a1d5e21-5101-450e-9054-ea4a20e06c57', /** * User avatar address */ avatar: '', /** * It's true if the image galley for banner is open */ openBanner: false, /** * It's true if the image gallery for avatar is open */ openAvatar: false, /** * Default birth day */ defaultBirthday: props.info && props.info.birthday ? moment.unix(props.info!.birthday!).toDate() : '', /** * Seleted birth day */ selectedBirthday: 0, /** * Web URL */ webUrl: props.info && props.info.webUrl ? props.info.webUrl : '', /** * User company name */ companyName: props.info && props.info.companyName ? props.info.companyName : '', /** * User twitter id */ twitterId: props.info && props.info.twitterId ? props.info.twitterId : '', activeStep: 0, addressInputError: '', cityInputError: '', stateInputError: '', zipInputError: '', regionSelectError: '', region: 1, address: this.props.shippingAddress ? this.props.shippingAddress.address1 : '', city: this.props.shippingAddress ? this.props.shippingAddress.city : '', state: this.props.shippingAddress ? this.props.shippingAddress.country : '', zip: this.props.shippingAddress ? this.props.shippingAddress.postalCode : '', } // Binding functions to `this` this.handleUpdate = this.handleUpdate.bind(this) this.handleRequestSetAvatar = this.handleRequestSetAvatar.bind(this) this.handleRequestSetBanner = this.handleRequestSetBanner.bind(this) } /** * Close image gallery of banner */ handleCloseBannerGallery = () => { this.setState({ openBanner: false }) } /** * Open image gallery of banner */ handleOpenBannerGallery = () => { this.setState({ openBanner: true }) } /** * Close image gallery of avatar */ handleCloseAvatarGallery = () => { this.setState({ openAvatar: false }) } /** * Open image gallery of avatar */ handleOpenAvatarGallery = () => { this.setState({ openAvatar: true }) } /** * Set banner image url */ handleRequestSetBanner = (url: string) => { this.setState({ banner: url }) } /** * Set avatar image url */ handleRequestSetAvatar = (fileName: string) => { this.setState({ avatar: fileName }) } /** * Update profile on the server * * * @memberof EditProfile */ handleUpdate = () => { const { address, city, state, zip, } = this.state const { update, translate, uid } = this.props let error = false if (this.state.address === undefined || (this.state.address.trim() === '' || this.state.address.trim().length === 0)) { this.setState({ addressInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.city === undefined || (this.state.city.trim() === '' || this.state.city.trim().length === 0)) { this.setState({ cityInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.state === undefined || (this.state.state.trim() === '' || this.state.state.trim().length === 0)) { this.setState({ stateInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.zip === undefined || (this.state.zip.trim() === '' || this.state.zip.trim().length === 0)) { this.setState({ zipInputError: translate!('login.emailRequiredError') }) error = true } if (this.state.region === 1 || this.state.region === undefined) { this.setState({ regionSelectError: translate!('login.emailRequiredError') }) error = true } if (!error) { update!({ address: address, city: city, state: state, postalCode: zip, region: 3, regionValue: 'US / Canada', shippingCost: '10', shippingId: '2', shippingType: '3-4 Days ($10)', customerId: uid, }) this.props.onRequestClose!() // } } } /** * Handle data on input change * @param {event} evt is an event of inputs of element on change */ handleInputChange = (event: any) => { const target = event.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name if (name === 'region') { this.setState({ region: target.key }) } this.setState({ [name]: value }) } /** * Handle resize event for window to change sidebar status * @param {any} event is the event is passed by winodw resize event */ handleResize = (event: any) => { // Set initial state let width = window.innerWidth if (width > 900) { this.setState({ isSmall: false }) } else { this.setState({ isSmall: true }) } } /** * Handle birthday date changed */ handleBirthdayDateChange = (date: any) => { this.setState({ selectedBirthday: moment(date).unix() }) } componentDidMount() { this.handleResize(null) } /** * Handle close request of select */ handleClose = () => { this.setState({ open: false }) } /** * Handle open request of select */ handleOpen = () => { this.setState({ open: true }) } shippingList = () => { const allShippingRegions = this.props.shippingRegions const shippingRegionsList: any[] = [] if (allShippingRegions) { allShippingRegions.forEach( (shippingRegion: Map<string, any>, key: string) => { const shippingRegionId = shippingRegion.get('shippingRegionId') let shippingRegionValue = shippingRegion.get('shippingRegion') shippingRegionsList.push( <MenuItem key={key} value={shippingRegionId}> {shippingRegionValue} </MenuItem> ) } ) } return shippingRegionsList } /** * Reneder component DOM * @return {react element} return the DOM which rendered by component */ render() { const { classes, translate, shippingAddress } = this.props return ( <div> {/* Edit profile dialog */} <Dialog PaperProps={{ className: classes.fullPageXs }} key='Edit-Profile' open={this.props.open!} onClose={this.props.onRequestClose} maxWidth='sm' > <DialogContent className={classes.dialogContentRoot}> {/* Banner */} <div style={{ position: 'relative' }}> <ImgCover width='100%' height='250px' borderRadius='2px' fileName={this.state.banner} /> {/* <div className='g__circle-black' onClick={this.handleOpenBannerGallery} style={{ position: 'absolute', right: '10px', top: '10px' }} > <SvgCamera style={{ fill: 'rgba(255, 255, 255, 0.88)', transform: 'translate(6px, 6px)' }} /> </div> */} </div> <div className='profile__edit'> <EventListener target='window' onResize={this.handleResize} /> <div className='left'> <div style={{ display: 'flex', justifyContent: 'center' }}> {/* Avatar */} {/* <div className='g__circle-black' onClick={this.handleOpenAvatarGallery} style={{ zIndex: 1, position: 'absolute', left: '50%', display: 'inline-block', top: '52px', margin: '-18px' }} > <SvgCamera style={{ fill: 'rgba(255, 255, 255, 0.88)', transform: 'translate(6px, 6px)' }} /> </div> */} <UserAvatarComponent fullName={this.props.fullName} fileName={this.state.avatar} size={90} style={this.styles.avatar} /> </div> <div className='info'> <div className='fullName'>{this.props.fullName}</div> </div> </div> </div> {/* Edit user information box*/} <Paper style={this.styles.paper} elevation={1}> <div style={this.styles.title as any}> {translate!('profile.personalInformationLabel')} </div> {/* <div className={classes.box}> <FormControl fullWidth aria-describedby='fullNameInputError'> <InputLabel htmlFor='fullNameInput'> {translate!('profile.fullName')} </InputLabel> <Input id='fullNameInput' onChange={this.handleInputChange} name='fullNameInput' value={this.state.fullNameInput} /> <FormHelperText id='fullNameInputError'>{this.state.fullNameInputError}</FormHelperText> </FormControl> </div> */} <div className={classes.box}> <FormControl fullWidth> <InputLabel htmlFor='address'>Address</InputLabel> <Input id='address' name='address' value={this.state.address ? this.state.address : shippingAddress ? shippingAddress.address1 : ''} onChange={this.handleInputChange} required /> <FormHelperText id='component-helper-text' className={classes.formHelperText}> {this.state.addressInputError} </FormHelperText> </FormControl> </div> <div className={classes.box}> <FormControl fullWidth> <InputLabel htmlFor='city'>City</InputLabel> <Input id='city' name='city' value={this.state.city ? this.state.city : shippingAddress ? shippingAddress.city : ''} onChange={this.handleInputChange} required /> <FormHelperText id='component-helper-text' className={classes.formHelperText}> {this.state.cityInputError} </FormHelperText> </FormControl> </div> <div className={classes.box}> <FormControl fullWidth> <InputLabel htmlFor='state'>Country</InputLabel> <Input id='state' name='state' value={this.state.state ? this.state.state : shippingAddress ? shippingAddress.country : ''} onChange={this.handleInputChange} required /> <FormHelperText id='component-helper-text' className={classes.formHelperText}> {this.state.stateInputError} </FormHelperText> </FormControl> </div> <div className={classes.box}> <FormControl fullWidth> <InputLabel htmlFor='zip'>Zip code</InputLabel> <Input id='zip' name='zip' value={this.state.zip ? this.state.zip : shippingAddress ? shippingAddress.postalCode : ''} onChange={this.handleInputChange} required /> <FormHelperText id='component-helper-text' className={classes.formHelperText}> {this.state.zipInputError} </FormHelperText> </FormControl> </div> <div className={classes.box}> <FormControl fullWidth> <InputLabel htmlFor='region'>Region</InputLabel> <Select id='zip' value={this.state.region ? this.state.region : shippingAddress ? shippingAddress.shippingRegionId : ''} input={<Input name='region' id='rigion' required/>} onClose={this.handleClose} onOpen={this.handleOpen} onChange={this.handleInputChange} > {this.shippingList()} </Select> <FormHelperText id='component-helper-text' className={classes.formHelperText}> {this.state.regionSelectError} </FormHelperText> </FormControl> </div> <br /> </Paper> <div className={classes.bottomPaperSpace} /> </DialogContent> <DialogActions className={classes.fixedDownStickyXS}> <Button onClick={this.props.onRequestClose}> {' '} {translate!('profile.cancelButton')}{' '} </Button> <Button variant='contained' color='secondary' onClick={this.handleUpdate} style={this.styles.updateButton} > {' '} {translate!('profile.updateButton')}{' '} </Button> </DialogActions> </Dialog> {/* Image gallery for banner*/} <Dialog PaperProps={{ className: classes.fullPageXs }} open={this.state.openBanner} onClose={this.handleCloseBannerGallery} > <DialogTitle className={classes.dialogTitle}> <AppDialogTitle title={translate!('profile.chooseBanerDialogTitle')} onRequestClose={this.handleCloseBannerGallery} /> </DialogTitle> <ImageGallery set={this.handleRequestSetBanner} close={this.handleCloseBannerGallery} /> </Dialog> {/* Image gallery for avatar */} <Dialog PaperProps={{ className: classes.fullPageXs }} open={this.state.openAvatar} onClose={this.handleCloseAvatarGallery} > <DialogTitle className={classes.dialogTitle}> <AppDialogTitle title={translate!('profile.chooseAvatarDialogTitle')} onRequestClose={this.handleCloseAvatarGallery} /> </DialogTitle> <ImageGallery set={this.handleRequestSetAvatar} close={this.handleCloseAvatarGallery} /> </Dialog> </div> ) } } /** * Map dispatch to props * @param {func} dispatch is the function to dispatch action to reducers * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapDispatchToProps = ( dispatch: any, ownProps: IEditProfileComponentProps ) => { return { update: (shippingAddress: ShippingAddress) => { dispatch(shippingsActions.dbAddShippingAddress(shippingAddress)) }, onRequestClose: () => dispatch(userActions.closeEditProfile()) } } /** * Map state to props * @param {object} state is the obeject from redux store * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapStateToProps = ( state: Map<string, any>, ownProps: IEditProfileComponentProps ) => { const uid = state.getIn(['authorize', 'uid']) const shippingRegions = state.getIn(['shippings', 'shippingRegions']) const shippingAddress = state.getIn(['shippings', 'shippingAddress']) return { currentLanguage: getActiveLanguage(state.get('locale')).code, translate: getTranslate(state.get('locale')), open: state.getIn(['user', 'openEditProfile'], false), info: state.getIn(['user', 'info', uid]), avatarURL: state.getIn(['imageGallery', 'imageURLList']), shippingRegions, activeStep: state.getIn(['checkout', 'activeState'], 0), fullName: state.getIn(['authorize', 'displayName']), uid, shippingAddress, } } // - Connect component to redux store export default connect( mapStateToProps, mapDispatchToProps )(withStyles(styles as any)(EditProfileComponent as any) as any)
the_stack
'use strict'; import * as Github from '@octokit/rest'; import { GraphQLClient } from 'graphql-request'; import { Variables } from 'graphql-request/dist/src/types'; import { CancellationToken, ConfigurationChangeEvent, Disposable, Range, Uri, workspace } from 'vscode'; import { configuration } from './configuration'; import { Logger } from './logger'; import { debug, Iterables } from './system'; import { fromRemoteHubUri } from './uris'; const repositoryRegex = /^(?:https:\/\/github.com\/)?(.+?)\/(.+?)(?:\/|$)/i; export interface SearchQueryMatch { path: string; ranges: Range[]; preview: string; matches: Range[]; } export interface SearchQueryResults { matches: SearchQueryMatch[]; limitHit: boolean; } export class GitHubApi implements Disposable { private readonly _disposable: Disposable; private readonly _revisionForUriMap = new Map<string, string>(); constructor() { this._disposable = Disposable.from(configuration.onDidChange(this.onConfigurationChanged, this)); void this.onConfigurationChanged(configuration.initializingChangeEvent); } dispose() { this._disposable && this._disposable.dispose(); } private onConfigurationChanged(e: ConfigurationChangeEvent) { if (configuration.changed(e, configuration.name('githubToken').value)) { this._client = undefined; } } private _token: string | undefined; get token() { if (this._token === undefined) { this._token = workspace.getConfiguration('github').get<string>('accessToken') || configuration.get<string>(configuration.name('githubToken').value); } return this._token; } private _client: GraphQLClient | undefined; private get client(): GraphQLClient { if (this._client === undefined) { if (!this.token) { throw new Error('No GitHub personal access token could be found'); } this._client = new GraphQLClient('https://api.github.com/graphql', { headers: { Authorization: `Bearer ${this.token}` } }); } return this._client; } @debug() async filesQuery(uri: Uri) { const cc = Logger.getCorrelationContext(); const [owner, repo] = fromRemoteHubUri(uri); try { const resp = await new Github({ auth: `token ${this.token}` }).git.getTree({ owner: owner, repo: repo, recursive: 1, // eslint-disable-next-line @typescript-eslint/camelcase tree_sha: 'HEAD' }); return Iterables.filterMap(resp.data.tree as { type: 'blob' | 'tree'; path: string }[], p => p.type === 'blob' ? p.path : undefined ); } catch (ex) { Logger.error(ex, cc); return []; } } @debug({ args: { 3: () => false } }) async searchQuery( query: string, uri: Uri, options: { maxResults?: number; context?: { before?: number; after?: number } }, token: CancellationToken ): Promise<SearchQueryResults> { const cc = Logger.getCorrelationContext(); const [owner, repo] = fromRemoteHubUri(uri); try { const resp = (await new Github({ auth: `token ${this.token}`, headers: { accept: 'application/vnd.github.v3.text-match+json' } }).search.code({ q: `${query} repo:${owner}/${repo}` })) as Github.Response<GitHubSearchResponse>; // Since GitHub doesn't return ANY line numbers just fake it at the top of the file 😢 const range = new Range(0, 0, 0, 0); const matches: SearchQueryMatch[] = []; let counter = 0; let match: SearchQueryMatch; for (const item of resp.data.items) { for (const m of item.text_matches) { counter++; if (options.maxResults !== undefined && counter > options.maxResults) { return { matches: matches, limitHit: true }; } match = { path: item.path, ranges: [], preview: m.fragment, matches: [] }; for (const lm of m.matches) { let line = 0; let shartChar = 0; let endChar = 0; for (let i = 0; i < lm.indices[1]; i++) { if (i === lm.indices[0]) { shartChar = endChar; } if (m.fragment[i] === '\n') { line++; endChar = 0; } else { endChar++; } } match.ranges.push(range); match.matches.push(new Range(line, shartChar, line, endChar)); } matches.push(match); } } return { matches: matches, limitHit: false }; } catch (ex) { Logger.error(ex, cc); return { matches: [], limitHit: true }; } } getRevisionForUri(uri: Uri) { return this._revisionForUriMap.get(uri.toString()); } setRevisionForUri(uri: Uri, fileRevision: string) { this._revisionForUriMap.set(uri.toString(), fileRevision); } @debug({ args: { 1: () => false } }) async fsQuery<T>(uri: Uri, innerQuery: string): Promise<T | undefined> { const cc = Logger.getCorrelationContext(); try { const query = `query fs($owner: String!, $repo: String!, $path: String) { repository(owner: $owner, name: $repo) { object(expression: $path) { ${innerQuery} } } }`; const variables = GitHubApi.extractFSQueryVariables(uri); Logger.debug(cc, `variables: ${JSON.stringify(variables)}`); const rsp = await this.client.request<{ repository: { object: T }; }>(query, variables); return rsp.repository.object; } catch (ex) { Logger.error(ex, cc); return undefined; } } @debug() async repositoryRevisionQuery(owner: string, repo: string): Promise<string | undefined> { const cc = Logger.getCorrelationContext(); try { const query = `query repo($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { defaultBranchRef { target { oid } } } }`; const variables = { owner: owner, repo: repo }; Logger.debug(cc, `variables: ${JSON.stringify(variables)}`); const rsp = await this.client.request<{ repository: { defaultBranchRef: { target: { oid: string } } }; }>(query, variables); if (rsp.repository == null) return undefined; return rsp.repository.defaultBranchRef.target.oid; } catch (ex) { Logger.error(ex, cc); return undefined; } } @debug() async repositoriesQuery(rawQuery: string): Promise<Repository[]> { const cc = Logger.getCorrelationContext(); let searchQuery; const match = repositoryRegex.exec(rawQuery); if (match != null) { const [, owner, repo] = match; searchQuery = `${repo} in:name user:${owner} sort:stars-desc`; } else { const [ownerOrRepo, repo] = rawQuery.split('/'); if (ownerOrRepo && repo) { searchQuery = `${repo} in:name user:${ownerOrRepo} sort:stars-desc`; } else if (ownerOrRepo && repo !== undefined) { searchQuery = `user:${ownerOrRepo} sort:stars-desc`; } else { searchQuery = `${ownerOrRepo} in:name sort:stars-desc`; } } try { const query = `query repos($query: String!) { search(type: REPOSITORY, query: $query, first: 25 ) { edges { node { ... on Repository { name description url nameWithOwner } } } } }`; const variables = { query: searchQuery }; Logger.debug(cc, `variables: ${JSON.stringify(variables)}`); const rsp = await this.client.request<{ search: { edges: { node: Repository }[] }; }>(query, variables); if (rsp.search == null) return []; return rsp.search.edges.map(e => e.node); } catch (ex) { Logger.error(ex, cc); return []; } } private static extractFSQueryVariables(uri: Uri): Variables { const [owner, repo, path] = fromRemoteHubUri(uri); return { owner: owner, repo: repo, path: `HEAD:${path}` }; } } export interface Repository { name: string; description: string; url: string; nameWithOwner: string; } export interface GitHubSearchResponse { total_count: number; incomplete_results: boolean; items: GitHubSearchItem[]; } export interface GitHubSearchItem { name: string; path: string; sha: string; url: string; git_url: string; html_url: string; score: number; text_matches: GitHubSearchTextMatch[]; } export interface GitHubSearchTextMatch { object_url: string; object_type: string; property: string; fragment: string; matches: GitHubSearchMatch[]; } export interface GitHubSearchMatch { text: string; indices: number[]; }
the_stack
import { matMultiplyPoint, EndpointAddr, endpointAddrsMatch, endpointAddrToString, EVolumeContext, InitialInterfaceLock, InterfaceLockResult, Device, stringToEndpointAddr, EVolumeType } from '@aardvarkxr/aardvark-shared'; import { mat4, vec3 } from '@tlaukkan/tsm'; import { volumeMatchesContext, TransformedVolume, volumesIntersect } from './volume_intersection'; export interface InterfaceProcessorCallbacks { interfaceStarted( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string, transmitterFromReceiver: [mat4, vec3], params?: object, reason?: string ):void; interfaceEnded( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string, transmitterFromReceiver?: [mat4, vec3], reason?: string ):void; interfaceTransformUpdated( destination: EndpointAddr, peer: EndpointAddr, iface: string, destinationFromPeer: [mat4, vec3], reason?: string ): void; interfaceEvent( destination: EndpointAddr, peer: EndpointAddr, iface: string, event: object, destinationFromPeer: [mat4, vec3], reason?: string ): void; } export interface InterfaceEntity { readonly epa: EndpointAddr; readonly transmits: string[]; readonly receives: string[]; readonly universeFromEntity: mat4; readonly volumes: TransformedVolume[]; readonly originPath: string; readonly wantsTransforms: boolean; readonly initialLocks: InitialInterfaceLock[]; /** High numbers are selected before low numbers if multiple volumes match. */ readonly priority: number; } interface InterfaceInProgress { transmitter: EndpointAddr; receiver: EndpointAddr; iface: string; locked: boolean; transmitterWantsTransforms: boolean; receiverWantsTransforms: boolean; refreshTransforms: boolean; hasRealVolumes: boolean; emptyVolumeSource?: string; } export function findBestInterface( transmitter: InterfaceEntity, receiver: InterfaceEntity ): string | null { for( let transmitterInterface of transmitter.transmits ) { if( receiver.receives.includes( transmitterInterface ) ) { return transmitterInterface; } } return null; } function hasRealVolume( ep: InterfaceEntity, context: EVolumeContext ) : [ boolean, string ] { let bestSource: string = "gadget"; for( let v of ep.volumes ) { if( !volumeMatchesContext( v, context ) ) continue; if( v.type != EVolumeType.Empty ) return [ true, undefined ]; if( v.source ) { bestSource = v.source } } return [ false, bestSource ]; } function pairHasRealVolume( transmitter: InterfaceEntity, receiver: InterfaceEntity, context: EVolumeContext ) : [ boolean, string ] { const [ tr, ts ] = hasRealVolume( transmitter, context ); const [ rr, rs ] = hasRealVolume( receiver, context ); if( tr && rr ) { return [ true, undefined ]; } if( tr && !rr ) { return [ false, "receiver." + rs ]; } else if( rr ) // && !tr { return [ false, "transmitter." + ts ]; } else // neither { return [ false, "transmitter." + ts + " + receiver." + rs ]; } } function entitiesIntersect( transmitter: InterfaceEntity, receiver: InterfaceEntity, context: EVolumeContext ): [ boolean, null | vec3 ] { for( let tv of transmitter.volumes ) { for( let rv of receiver.volumes ) { const [ i, pt ] = volumesIntersect( tv, rv, context ); if( i ) return [i, pt ]; } } return [ false, null ]; } class InterfaceEntityMap { private entities: { [ epa: string ] : InterfaceEntity } = {}; constructor( entities: InterfaceEntity[] ) { for( let entity of entities ) { this.set( entity ); } } public find( epa: EndpointAddr ) { return this.entities[ endpointAddrToString( epa ) ]; } public set( entity: InterfaceEntity ) { this.entities[ endpointAddrToString( entity.epa ) ] = entity; } public has( epa: EndpointAddr ) { return this.entities.hasOwnProperty( endpointAddrToString( epa ) ); } } class TransmitterInUseMap { private iipMap: { [key: string ]: InterfaceInProgress| boolean } = {}; private makeKey( transmitterEpa: EndpointAddr, iface: string ) { return `${ endpointAddrToString( transmitterEpa ) }/${ iface }`; } public set( transmitterEpa: EndpointAddr, iface: string, iip: InterfaceInProgress| boolean ) { this.iipMap[ this.makeKey( transmitterEpa, iface )] = iip; } public find( transmitterEpa: EndpointAddr, iface: string ) { return this.iipMap[ this.makeKey( transmitterEpa, iface ) ]; } public has( transmitterEpa: EndpointAddr, iface: string ) { return this.iipMap.hasOwnProperty( this.makeKey( transmitterEpa, iface ) ); } } export interface InterfaceProcessorOptions { verboseLogging: boolean; } export class CInterfaceProcessor { private interfacesInProgress: InterfaceInProgress[] = []; private lostLockedInterfaces = new Map<string, InterfaceInProgress>(); private callbacks: InterfaceProcessorCallbacks; private lastEntityMap: InterfaceEntityMap; private options: InterfaceProcessorOptions; constructor( callbacks: InterfaceProcessorCallbacks, options?: InterfaceProcessorOptions ) { this.callbacks = callbacks; this.options = options ?? { verboseLogging: false, }; } private log( msg: string, ...args: any[] ) { if( this.options.verboseLogging ) { console.log( msg, ...args ); } } public processFrame( entities: InterfaceEntity[] ) { let entityMap = new InterfaceEntityMap( entities ); // Start interfaces from the initial interface list of new entities for( let transmitter of entities ) { // we only do this the very first frame we see an entity if( this.lastEntityMap?.has( transmitter.epa ) ) { continue; } for( let initialLock of transmitter.initialLocks ) { let receiver = entityMap.find( initialLock.receiver ); let transmitterFromReceiver = this.computeEntityTransform( transmitter, receiver ); this.callbacks.interfaceStarted( transmitter.epa, initialLock.receiver, initialLock.iface, transmitterFromReceiver, initialLock.params, "Initial lock" ); const [ hasRealVolumes, emptyVolumeSource ] = pairHasRealVolume( transmitter, receiver, EVolumeContext.StartOnly ); let iip: InterfaceInProgress = { transmitter: transmitter.epa, receiver: initialLock.receiver, iface: initialLock.iface, locked: true, transmitterWantsTransforms: transmitter.wantsTransforms, receiverWantsTransforms: receiver?.wantsTransforms ?? false, refreshTransforms: false, hasRealVolumes, emptyVolumeSource, }; if( receiver && receiver.receives.includes( initialLock.iface ) ) { // we actually know this receiver, so this new forced interface/lock goes on the // active list this.interfacesInProgress.push( iip ); } else { // There is no such receiver, so the interface is immediately lost. Because of // the implied lock, it goes into our lost lock list this.callbacks.interfaceEnded( transmitter.epa, initialLock.receiver, initialLock.iface, undefined, "No such receiver (initial lock)" ); this.lostLockedInterfaces.set( endpointAddrToString( transmitter.epa ), iip ); } } } // end interfaces where one end or the other is gone let transmittersInUse = new TransmitterInUseMap(); let newInterfacesInProgress: InterfaceInProgress[] = [] for( let iip of this.interfacesInProgress ) { // if a transmitter goes away, the interface goes away let transmitter = entityMap.find( iip.transmitter ); if( !transmitter || !transmitter.transmits.includes( iip.iface ) ) { this.callbacks.interfaceEnded(iip.transmitter, iip.receiver, iip.iface, undefined, "Lost transmitter" ); continue; } // if a receiver goes away we will also report that // the interface has ended, but if the interface was // locked, we need to keep the transmitter from starting // any new interfaces until it's unlocked let receiver = entityMap.find( iip.receiver ); if( !receiver || !receiver.receives.includes( iip.iface ) ) { // console.log( "receiver no longer exists or lost iface", receiver ); this.callbacks.interfaceEnded(iip.transmitter, iip.receiver, iip.iface, undefined, "Lost receiver" + ( iip.locked ? " (locked)" : "" ) ); this.log( `interface end (no receiver/iface) ${ endpointAddrToString( transmitter.epa ) } ` +` to ${ endpointAddrToString( iip.receiver ) } for ${ iip.iface }` ); if( iip.locked ) { //this.log( "adding lost lock to list for " + endpointAddrToString( iip.transmitter ) ); this.lostLockedInterfaces.set( endpointAddrToString( iip.transmitter ), iip ); } continue; } // if the iip isn't locked, we need to check that the volumes still exist and still // intersect if( !iip.locked ) { const [ int, pt ] = entitiesIntersect( transmitter, receiver, EVolumeContext.ContinueOnly ); if ( !int ) { this.log( `interface end (no intersect) ${ endpointAddrToString( transmitter.epa ) } ` +` to ${ endpointAddrToString( receiver.epa ) } for ${ iip.iface }` ); this.callbacks.interfaceEnded( iip.transmitter, iip.receiver, iip.iface, this.computeEntityTransform( transmitter, receiver ), "no intersect" ); continue; } if( !shouldAllowMatch( transmitter, receiver ) ) { this.log( `interface end (matching origins) ${ endpointAddrToString( transmitter.epa ) } ` +` to ${ endpointAddrToString( receiver.epa ) } for ${ iip.iface }` ); this.callbacks.interfaceEnded( iip.transmitter, iip.receiver, iip.iface, this.computeEntityTransform( transmitter, receiver ), "match disallowed" ); continue; } } iip.transmitterWantsTransforms = transmitter.wantsTransforms; iip.receiverWantsTransforms = receiver.wantsTransforms; const [ hasRealVolumes, emptyVolumeSource ] = pairHasRealVolume( transmitter, receiver, EVolumeContext.StartOnly ); iip.hasRealVolumes = hasRealVolumes; iip.emptyVolumeSource = emptyVolumeSource; transmittersInUse.set( iip.transmitter, iip.iface, iip ); newInterfacesInProgress.push( iip ); } // lost locks count as "in use" so they won't trigger new interfaces for( let transmitterEpaString of this.lostLockedInterfaces.keys() ) { let iip = this.lostLockedInterfaces.get( transmitterEpaString ); transmittersInUse.set( iip.transmitter, iip.iface, false ); } // Look for new interfaces for ( let transmitter of entities ) { if( transmitter.transmits.length == 0 ) { // this entity isn't transmitting anything continue; } for( let iface of transmitter.transmits ) { let currentIip = transmittersInUse.find( transmitter.epa, iface ); //console.log( "current iip", currentIip ); if( typeof currentIip == "boolean" || ( currentIip && currentIip.locked ) ) { // This interface was locked. Wait for the unlock before changing anything continue; } let bestReceiver: InterfaceEntity; let bestPt: vec3; for( let receiver of entities ) { if( transmitter == receiver ) { // you can't interface with yourself continue; } if( !shouldAllowMatch( transmitter, receiver ) ) { // right hand can't interface with stuff that's also // on the right hand, etc. // This rule does not apply to entities that originate on the stage because they aren't // moving around the way that hands and the head are. continue; } if( !receiver.receives.includes( iface ) ) { // if the receiver doesn't implement this of the interfaces // from the transmitter, they just don't care about each other continue; } const [ int, pt ] = entitiesIntersect( transmitter, receiver, EVolumeContext.StartOnly ); if( !int ) { continue; } if( !bestReceiver || bestReceiver.priority < receiver.priority ) { bestReceiver = receiver; bestPt = pt; } } if( bestReceiver ) { if( currentIip ) { // make sure the new one is higher priority let oldReceiver = entityMap.find( currentIip.receiver ); if( oldReceiver.priority >= bestReceiver.priority ) { continue; } // end the old interface before starting the new one this.callbacks.interfaceEnded( transmitter.epa, oldReceiver.epa, iface, this.computeEntityTransform( transmitter, oldReceiver ), `higher priority receiver ` + `${ bestReceiver.priority } > ${ oldReceiver.priority }` ); let oldIndex = newInterfacesInProgress.findIndex( ( iip: InterfaceInProgress ) => ( iip == currentIip ) ); if( oldIndex != -1 ) { newInterfacesInProgress.splice( oldIndex, 1 ); } } this.log( `interface started ${ endpointAddrToString( transmitter.epa ) } ` +` to ${ endpointAddrToString( bestReceiver.epa ) } for ${ iface }` ); // we found a transmitter and receiver that are touching and share an interface. this.callbacks.interfaceStarted( transmitter.epa, bestReceiver.epa, iface, this.computeEntityTransform( transmitter, bestReceiver ), undefined, "intersection" ); newInterfacesInProgress.push( { transmitter: transmitter.epa, receiver: bestReceiver.epa, iface: iface, locked: false, transmitterWantsTransforms: transmitter.wantsTransforms, receiverWantsTransforms: bestReceiver.wantsTransforms, refreshTransforms: false, hasRealVolumes: true, } ); } } } // Now that we've sorted out the new InterfaceInProgress list, sent transforms // to whomever wants them this.interfacesInProgress = newInterfacesInProgress; for( let iip of this.interfacesInProgress ) { if( !iip.receiverWantsTransforms && !iip.transmitterWantsTransforms && !iip.refreshTransforms ) { continue; } let transmitter = entityMap.find( iip.transmitter ); let receiver = entityMap.find( iip.receiver ); if( iip.transmitterWantsTransforms || iip.refreshTransforms ) { this.callbacks.interfaceTransformUpdated(iip.transmitter, iip.receiver, iip.iface, this.computeEntityTransform( transmitter, receiver ), "transmitterWantsTransforms" ); } if( iip.receiverWantsTransforms || iip.refreshTransforms ) { this.callbacks.interfaceTransformUpdated( iip.receiver, iip.transmitter, iip.iface, this.computeEntityTransform( receiver, transmitter ), "receiverWantsTransforms" ); } iip.refreshTransforms = false; } this.lastEntityMap = entityMap; } computeEntityTransform( to: InterfaceEntity, from: InterfaceEntity ) : [ mat4, vec3 | null ] { if( !to || !from ) { return undefined; } let toFromUniverse = to.universeFromEntity.copy().inverse(); let transform = mat4.product( toFromUniverse, from.universeFromEntity, new mat4() ); const [ int, pt ] = entitiesIntersect(to, from, EVolumeContext.Always ); let ptInTo: vec3; if( pt ) { // transform the point to be in "to" space ptInTo = matMultiplyPoint( toFromUniverse, pt ); } return [transform, ptInTo ]; } public interfaceEvent( destEpa: EndpointAddr, peerEpa: EndpointAddr, iface: string, event: object ): void { let foundIip = false; for( let iip of this.interfacesInProgress ) { // look for an iip where the destination is the transmitter and the peer is the receiver // or vice versa if( endpointAddrsMatch( destEpa, iip.transmitter ) && endpointAddrsMatch( peerEpa, iip.receiver ) || endpointAddrsMatch( destEpa, iip.receiver ) && endpointAddrsMatch( peerEpa, iip.transmitter ) ) { foundIip = true; if( iip.iface != iface ) { this.log( `Discarding interface event from ${ endpointAddrToString( peerEpa ) } ` +` to ${ endpointAddrToString( destEpa ) } for ${ iface }` +` because the interface between those two is ${ iip.iface }`, event ); break; } let destination = this.lastEntityMap?.find( destEpa ); let peer = this.lastEntityMap?.find( peerEpa ); let destinationFromPeer = this.computeEntityTransform( destination, peer ); this.log( `Reflecting interface event from ${ endpointAddrToString( peerEpa ) } ` +` to ${ endpointAddrToString( destEpa ) } for ${ iface }`, event, destinationFromPeer ); this.callbacks.interfaceEvent( destEpa, peerEpa, iface, event, destinationFromPeer, `sent by ${ endpointAddrToString( peerEpa ) }` ); iip.refreshTransforms = true; // we should only have one iip for this transmitter break; } } if( !foundIip ) { this.log( `Discarding interface event from ${ endpointAddrToString( peerEpa ) } ` +` to ${ endpointAddrToString( destEpa ) } for ${ iface }` +` because the interface was not found`, event ); } } private findIip( transmitter: EndpointAddr, receiver: EndpointAddr ): InterfaceInProgress { for( let iip of this.interfacesInProgress ) { if( endpointAddrsMatch( transmitter, iip.transmitter ) && endpointAddrsMatch( receiver, iip.receiver ) ) { return iip; } } return null; } public lockInterface( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string ): InterfaceLockResult { let iip = this.findIip( transmitter, receiver ); if( !iip ) { this.log( `Failed to lock interface ${ endpointAddrToString( transmitter ) } ` +` to ${ endpointAddrToString( receiver ) } for ${ iface }: ` + `no interface in progress` ); return InterfaceLockResult.InterfaceNotFound; } if( iip.locked ) { this.log( `Failed to lock interface ${ endpointAddrToString( transmitter ) } ` +` to ${ endpointAddrToString( receiver ) } for ${ iface }: ` + `already locked` ); return InterfaceLockResult.AlreadyLocked; } if( iip.iface != iface ) { this.log( `Failed to lock interface ${ endpointAddrToString( transmitter ) } ` +` to ${ endpointAddrToString( receiver ) } for ${ iface }: ` + `mismatched interface (${ iip.iface })` ); return InterfaceLockResult.InterfaceNameMismatch; } this.log( `Locking interface ${ endpointAddrToString( transmitter ) } ` +` to ${ endpointAddrToString( receiver ) } for ${ iface }` ); iip.locked = true; iip.refreshTransforms = true; return InterfaceLockResult.Success; } public unlockInterface( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string ): [ InterfaceLockResult, () => void ] { let iip = this.findIip( transmitter, receiver ); if( !iip ) { if( this.lostLockedInterfaces.has( endpointAddrToString( transmitter ) ) ) { iip = this.lostLockedInterfaces.get( endpointAddrToString( transmitter ) ); if( iip.iface != iface ) { return [ InterfaceLockResult.InterfaceNameMismatch, null ]; } // we lost the other end of the lock and told the transmitter about that already. this.lostLockedInterfaces.delete( endpointAddrToString( transmitter ) ); return [ InterfaceLockResult.Success, null ]; } else { return [ InterfaceLockResult.InterfaceNotFound, null ]; } } if( !iip.locked ) { return [ InterfaceLockResult.NotLocked, null ]; } if( iip.iface != iface ) { return [ InterfaceLockResult.InterfaceNameMismatch, null ]; } if( !endpointAddrsMatch( iip.receiver, receiver ) ) { return [ InterfaceLockResult.InterfaceReceiverMismatch, null ]; } this.log( `Unlocking interface ${ endpointAddrToString( transmitter ) } ` +` to ${ endpointAddrToString( receiver ) } for ${ iface }` ); iip.locked = false; iip.refreshTransforms = true; let fn: () => void; if( !iip.hasRealVolumes ) { // This interface is guaranteed to edit on the next frame... unless somebody sneaks in // with a new lock. End this interface immediately so there's no risk of that happening // and the behavior from the gadget side is deterministic // we this with a callback so that the unlock result always shows up before the interface // end fn = () => { this.callbacks.interfaceEnded(iip.transmitter, iip.receiver, iip.iface, undefined, "unlock without real volumes " + iip.emptyVolumeSource ); this.interfacesInProgress.filter( ( testIip ) => testIip != iip ); } } return [ InterfaceLockResult.Success, fn ]; } public relockInterface( transmitterEpa: EndpointAddr, oldReceiverEpa: EndpointAddr, newReceiverEpa: EndpointAddr, iface: string ): InterfaceLockResult { let iip = this.findIip( transmitterEpa, oldReceiverEpa ); if( !iip ) { return InterfaceLockResult.InterfaceNotFound; } if( !iip.locked ) { return InterfaceLockResult.NotLocked; } if( iip.iface != iface ) { return InterfaceLockResult.InterfaceNameMismatch; } if( !endpointAddrsMatch( iip.receiver, oldReceiverEpa ) ) { return InterfaceLockResult.InterfaceReceiverMismatch; } let newReceiver = this.lastEntityMap.find( newReceiverEpa ); if( !newReceiver ) { return InterfaceLockResult.NewReceiverNotFound; } let transmitter = this.lastEntityMap.find( transmitterEpa ) let oldReceiver = this.lastEntityMap.find( oldReceiverEpa ) let transmitterFromOldReceiver = this.computeEntityTransform( transmitter, oldReceiver ); let transmitterFromNewReceiver = this.computeEntityTransform( transmitter, newReceiver ); this.callbacks.interfaceEnded( transmitterEpa, oldReceiverEpa, iface, transmitterFromOldReceiver, "relock" ); this.callbacks.interfaceStarted( transmitterEpa, newReceiverEpa, iface, transmitterFromNewReceiver, undefined, "relock" ); this.log( `Relocking interface ${ endpointAddrToString( transmitterEpa ) } ` + ` from ${ endpointAddrToString( oldReceiverEpa ) }` +` to ${ endpointAddrToString( newReceiverEpa ) } for ${ iface }` ); iip.receiver = newReceiverEpa; iip.receiverWantsTransforms = newReceiver.wantsTransforms; return InterfaceLockResult.Success; } } function shouldAllowMatch( transmitter: InterfaceEntity, receiver: InterfaceEntity ): boolean { if( transmitter.originPath == "/space/stage" || !transmitter.originPath || !receiver.originPath ) return true; if( transmitter.originPath == receiver.originPath ) return false; let to = transmitter.originPath.split( '/' ); let ro = receiver.originPath.split( '/' ); if( to.length > 3 && ro.length > 3 ) { if( to[1] == ro[1] && to[2] == ro[2] && to[3] == ro[3] ) return false; } return true; }
the_stack
import { CmsContext, CmsModel, CmsModelContext, CmsModelManager, CmsModelPermission, HeadlessCmsStorageOperations, BeforeModelCreateTopicParams, AfterModelCreateTopicParams, BeforeModelUpdateTopicParams, AfterModelUpdateTopicParams, BeforeModelDeleteTopicParams, AfterModelDeleteTopicParams, BeforeModelCreateFromTopicParams, AfterModelCreateFromTopicParams, CmsModelCreateInput, CmsModelUpdateInput, CmsModelCreateFromInput } from "~/types"; import * as utils from "~/utils"; import DataLoader from "dataloader"; import { NotFoundError } from "@webiny/handler-graphql"; import { contentModelManagerFactory } from "./contentModel/contentModelManagerFactory"; import { CreateContentModelModel, CreateContentModelModelFrom, UpdateContentModelModel } from "./contentModel/models"; import { createFieldModels } from "./contentModel/createFieldModels"; import { validateLayout } from "./contentModel/validateLayout"; import WebinyError from "@webiny/error"; import { CmsModelPlugin } from "~/content/plugins/CmsModelPlugin"; import { Tenant } from "@webiny/api-tenancy/types"; import { I18NLocale } from "@webiny/api-i18n/types"; import { SecurityIdentity } from "@webiny/api-security/types"; import { createTopic } from "@webiny/pubsub"; import { assignBeforeModelCreate } from "./contentModel/beforeCreate"; import { assignBeforeModelUpdate } from "./contentModel/beforeUpdate"; import { assignBeforeModelDelete } from "./contentModel/beforeDelete"; import { assignAfterModelCreate } from "./contentModel/afterCreate"; import { assignAfterModelUpdate } from "./contentModel/afterUpdate"; import { assignAfterModelDelete } from "./contentModel/afterDelete"; import { assignAfterModelCreateFrom } from "~/content/plugins/crud/contentModel/afterCreateFrom"; export interface CreateModelsCrudParams { getTenant: () => Tenant; getLocale: () => I18NLocale; storageOperations: HeadlessCmsStorageOperations; context: CmsContext; getIdentity: () => SecurityIdentity; } export const createModelsCrud = (params: CreateModelsCrudParams): CmsModelContext => { const { getTenant, getIdentity, getLocale, storageOperations, context } = params; const loaders = { listModels: new DataLoader(async () => { const models = await storageOperations.models.list({ where: { tenant: getTenant().id, locale: getLocale().code } }); return [ models.map(model => { return { ...model, tenant: model.tenant || getTenant().id, locale: model.locale || getLocale().code }; }) ]; }) }; const clearModelsCache = (): void => { for (const loader of Object.values(loaders)) { loader.clearAll(); } }; const managers = new Map<string, CmsModelManager>(); const updateManager = async ( context: CmsContext, model: CmsModel ): Promise<CmsModelManager> => { const manager = await contentModelManagerFactory(context, model); managers.set(model.modelId, manager); return manager; }; const checkModelPermissions = (check: string): Promise<CmsModelPermission> => { return utils.checkPermissions(context, "cms.contentModel", { rwd: check }); }; const getModelsAsPlugins = (): CmsModel[] => { const tenant = getTenant().id; const locale = getLocale().code; return ( context.plugins .byType<CmsModelPlugin>(CmsModelPlugin.type) /** * We need to filter out models that are not for this tenant or locale. * If it does not have tenant or locale define, it is for every locale and tenant */ .filter(plugin => { const { tenant: t, locale: l } = plugin.contentModel; if (t && t !== tenant) { return false; } else if (l && l !== locale) { return false; } return true; }) .map<CmsModel>(plugin => { return { ...plugin.contentModel, tenant, locale, webinyVersion: context.WEBINY_VERSION }; }) ); }; const modelsGet = async (modelId: string): Promise<CmsModel> => { const pluginModel = getModelsAsPlugins().find(model => model.modelId === modelId); if (pluginModel) { return pluginModel; } const model = await storageOperations.models.get({ tenant: getTenant().id, locale: getLocale().code, modelId }); if (!model) { throw new NotFoundError(`Content model "${modelId}" was not found!`); } return { ...model, tenant: model.tenant || getTenant().id, locale: model.locale || getLocale().code }; }; const modelsList = async (): Promise<CmsModel[]> => { const databaseModels = await loaders.listModels.load("listModels"); const pluginsModels = getModelsAsPlugins(); return databaseModels.concat(pluginsModels); }; const listModels = async () => { const permission = await checkModelPermissions("r"); const models = await modelsList(); return utils.filterAsync(models, async model => { if (!utils.validateOwnership(context, permission, model)) { return false; } return utils.validateModelAccess(context, model); }); }; const getModel = async (modelId: string): Promise<CmsModel> => { const permission = await checkModelPermissions("r"); const model = await modelsGet(modelId); utils.checkOwnership(context, permission, model); await utils.checkModelAccess(context, model); return model; }; const getModelManager: CmsModelContext["getModelManager"] = async ( target ): Promise<CmsModelManager> => { const modelId = typeof target === "string" ? target : target.modelId; if (managers.has(modelId)) { return managers.get(modelId) as CmsModelManager; } const models = await modelsList(); const model = models.find(m => m.modelId === modelId); if (!model) { throw new NotFoundError(`There is no content model "${modelId}".`); } return await updateManager(context, model); }; const onBeforeModelCreate = createTopic<BeforeModelCreateTopicParams>(); const onAfterModelCreate = createTopic<AfterModelCreateTopicParams>(); const onBeforeModelCreateFrom = createTopic<BeforeModelCreateFromTopicParams>(); const onAfterModelCreateFrom = createTopic<AfterModelCreateFromTopicParams>(); const onBeforeModelUpdate = createTopic<BeforeModelUpdateTopicParams>(); const onAfterModelUpdate = createTopic<AfterModelUpdateTopicParams>(); const onBeforeModelDelete = createTopic<BeforeModelDeleteTopicParams>(); const onAfterModelDelete = createTopic<AfterModelDeleteTopicParams>(); /** * We need to assign some default behaviors. */ assignBeforeModelCreate({ onBeforeModelCreate, onBeforeModelCreateFrom, plugins: context.plugins, storageOperations }); assignAfterModelCreate({ context, onAfterModelCreate }); assignBeforeModelUpdate({ onBeforeModelUpdate, plugins: context.plugins, storageOperations }); assignAfterModelUpdate({ context, onAfterModelUpdate }); assignAfterModelCreateFrom({ context, onAfterModelCreateFrom }); assignBeforeModelDelete({ onBeforeModelDelete, plugins: context.plugins, storageOperations }); assignAfterModelDelete({ context, onAfterModelDelete }); return { onBeforeModelCreate, onAfterModelCreate, onBeforeModelCreateFrom, onAfterModelCreateFrom, onBeforeModelUpdate, onAfterModelUpdate, onBeforeModelDelete, onAfterModelDelete, clearModelsCache, getModel, listModels, async createModel(inputData) { await checkModelPermissions("w"); const createdData = new CreateContentModelModel().populate(inputData); await createdData.validate(); const input: CmsModelCreateInput = await createdData.toJSON(); context.security.disableAuthorization(); const group = await context.cms.getGroup(input.group); context.security.enableAuthorization(); if (!group) { throw new NotFoundError(`There is no group "${input.group}".`); } const fields = await createFieldModels(input.fields); const identity = getIdentity(); const model: CmsModel = { name: input.name, description: input.description || "", modelId: input.modelId || "", titleFieldId: "id", locale: getLocale().code, tenant: getTenant().id, group: { id: group.id, name: group.name }, createdBy: { id: identity.id, displayName: identity.displayName, type: identity.type }, createdOn: new Date().toISOString(), savedOn: new Date().toISOString(), fields, lockedFields: [], layout: input.layout || [], webinyVersion: context.WEBINY_VERSION }; validateLayout(model, fields); await onBeforeModelCreate.publish({ input, model }); const createdModel = await storageOperations.models.create({ model }); loaders.listModels.clearAll(); await updateManager(context, model); await onAfterModelCreate.publish({ input, model: createdModel }); return createdModel; }, /** * Method does not check for permissions or ownership. * @internal */ async updateModelDirect(params) { const { model: initialModel, original } = params; const model: CmsModel = { ...initialModel, tenant: initialModel.tenant || getTenant().id, locale: initialModel.locale || getLocale().code, webinyVersion: context.WEBINY_VERSION }; await onBeforeModelUpdate.publish({ input: {} as CmsModelUpdateInput, original, model }); const resultModel = await storageOperations.models.update({ model }); await updateManager(context, resultModel); loaders.listModels.clearAll(); await onAfterModelUpdate.publish({ input: {} as CmsModelUpdateInput, original, model: resultModel }); return resultModel; }, async createModelFrom(modelId, data) { await checkModelPermissions("w"); /** * Get a model record; this will also perform ownership validation. */ const original = await getModel(modelId); const createdData = new CreateContentModelModelFrom().populate({ name: data.name, modelId: data.modelId, description: data.description || original.description, group: data.group, locale: data.locale }); await createdData.validate(); const input: CmsModelCreateFromInput = await createdData.toJSON(); const locale = await context.i18n.getLocale(input.locale || original.locale); if (!locale) { throw new NotFoundError(`There is no locale "${input.locale}".`); } /** * Use storage operations directly because we cannot get group from different locale via context methods. */ const group = await context.cms.storageOperations.groups.get({ id: input.group, tenant: original.tenant, locale: locale.code }); if (!group) { throw new NotFoundError(`There is no group "${input.group}".`); } const identity = getIdentity(); const model: CmsModel = { ...original, locale: locale.code, group: { id: group.id, name: group.name }, name: input.name, modelId: input.modelId || "", description: input.description || "", createdBy: { id: identity.id, displayName: identity.displayName, type: identity.type }, createdOn: new Date().toISOString(), savedOn: new Date().toISOString(), lockedFields: [], webinyVersion: context.WEBINY_VERSION }; await onBeforeModelCreateFrom.publish({ input, model, original }); const createdModel = await storageOperations.models.create({ model }); loaders.listModels.clearAll(); await updateManager(context, model); await onAfterModelCreateFrom.publish({ input, original, model: createdModel }); return createdModel; }, async updateModel(modelId, inputData) { await checkModelPermissions("w"); // Get a model record; this will also perform ownership validation. const original = await getModel(modelId); const updatedData = new UpdateContentModelModel().populate(inputData); await updatedData.validate(); const input: CmsModelUpdateInput = await updatedData.toJSON({ onlyDirty: true }); if (Object.keys(input).length === 0) { /** * We need to return the original if nothing is to be updated. */ return original; } let group: CmsModel["group"] = { id: original.group.id, name: original.group.name }; if (input.group) { context.security.disableAuthorization(); const groupData = await context.cms.getGroup(input.group); context.security.enableAuthorization(); if (!groupData) { throw new NotFoundError(`There is no group "${input.group}".`); } group = { id: groupData.id, name: groupData.name }; } const fields = await createFieldModels(inputData.fields); const model: CmsModel = { ...original, ...input, group, tenant: original.tenant || getTenant().id, locale: original.locale || getLocale().code, webinyVersion: context.WEBINY_VERSION, fields, savedOn: new Date().toISOString() }; validateLayout(model, fields); await onBeforeModelUpdate.publish({ input, original, model }); const resultModel = await storageOperations.models.update({ model }); await updateManager(context, resultModel); await onAfterModelUpdate.publish({ input, original, model: resultModel }); return resultModel; }, async deleteModel(modelId) { await checkModelPermissions("d"); const model = await getModel(modelId); await onBeforeModelDelete.publish({ model }); try { await storageOperations.models.delete({ model }); } catch (ex) { throw new WebinyError( ex.message || "Could not delete the content model", ex.code || "CONTENT_MODEL_DELETE_ERROR", { error: ex, modelId: model.modelId } ); } await onAfterModelDelete.publish({ model }); managers.delete(model.modelId); }, getModelManager, getEntryManager: async model => { return getModelManager(model); }, getManagers: () => managers, getEntryManagers: () => managers }; };
the_stack
import * as React from 'react' import { Link as InternalLink } from 'react-router-dom' import { mountWithStore, BaseModal, Flex, Icon } from '@opentrons/components' import * as Shell from '../../../redux/shell' import { ErrorModal } from '../../../molecules/modals' import { ReleaseNotes } from '../../../molecules/ReleaseNotes' import { UpdateAppModal } from '..' import type { State, Action } from '../../../redux/types' import type { ShellUpdateState } from '../../../redux/shell/types' import type { UpdateAppModalProps } from '..' import type { HTMLAttributes, ReactWrapper } from 'enzyme' // TODO(mc, 2020-10-06): this is a partial mock because shell/update // needs some reorg to split actions and selectors jest.mock('../../../redux/shell/update', () => ({ ...jest.requireActual<{}>('../../../redux/shell/update'), getShellUpdateState: jest.fn(), })) jest.mock('react-router-dom', () => ({ Link: () => <></> })) const getShellUpdateState = Shell.getShellUpdateState as jest.MockedFunction< typeof Shell.getShellUpdateState > const MOCK_STATE: State = { mockState: true } as any describe('UpdateAppModal', () => { const closeModal = jest.fn() const dismissAlert = jest.fn() const render = (props: UpdateAppModalProps) => { return mountWithStore<UpdateAppModalProps, State, Action>( <UpdateAppModal {...props} />, { initialState: MOCK_STATE, } ) } beforeEach(() => { getShellUpdateState.mockImplementation((state: State) => { expect(state).toBe(MOCK_STATE) return { info: { version: '1.2.3', releaseNotes: 'this is a release', }, } as ShellUpdateState }) }) afterEach(() => { jest.resetAllMocks() }) it('should render an BaseModal using available version from state', () => { const { wrapper } = render({ closeModal }) const modal = wrapper.find(BaseModal) const title = modal.find('h2') const titleIcon = title.closest(Flex).find(Icon) expect(title.text()).toBe('App Version 1.2.3 Available') expect(titleIcon.prop('name')).toBe('alert') }) it('should render a <ReleaseNotes> component with the release notes', () => { const { wrapper } = render({ closeModal }) const releaseNotes = wrapper.find(ReleaseNotes) expect(releaseNotes.prop('source')).toBe('this is a release') }) it('should render a "Not Now" button that closes the modal', () => { const { wrapper } = render({ closeModal }) const notNowButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /not now/i.test(b.text()) ) expect(closeModal).not.toHaveBeenCalled() notNowButton.invoke('onClick')?.({} as React.MouseEvent) expect(closeModal).toHaveBeenCalled() }) it('should render a "Download" button that starts the update', () => { const { wrapper, store } = render({ closeModal }) const downloadButton = wrapper .find('button') .filterWhere((b: ReactWrapper) => /download/i.test(b.text())) downloadButton.invoke('onClick')?.({} as React.MouseEvent) expect(store.dispatch).toHaveBeenCalledWith(Shell.downloadShellUpdate()) }) it('should render a spinner if update is downloading', () => { getShellUpdateState.mockReturnValue({ downloading: true, } as ShellUpdateState) const { wrapper } = render({ closeModal }) const spinner = wrapper .find(Icon) .filterWhere( (i: ReactWrapper<React.ComponentProps<typeof Icon>>) => i.prop('name') === 'ot-spinner' ) const spinnerParent = spinner.closest(Flex) expect(spinnerParent.text()).toMatch(/download in progress/i) }) it('should render a instructional copy instead of release notes if update is downloaded', () => { getShellUpdateState.mockReturnValue({ downloaded: true, info: { version: '1.2.3', releaseNotes: 'this is a release', }, } as ShellUpdateState) const { wrapper } = render({ closeModal }) const title = wrapper.find('h2') expect(title.text()).toBe('App Version 1.2.3 Downloaded') expect(wrapper.exists(ReleaseNotes)).toBe(false) expect(wrapper.text()).toMatch(/Restart your app to complete the update/i) }) it('should render a "Restart App" button if update is downloaded', () => { getShellUpdateState.mockReturnValue({ downloaded: true, } as ShellUpdateState) const { wrapper, store } = render({ closeModal }) const restartButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /restart/i.test(b.text()) ) restartButton.invoke('onClick')?.({} as React.MouseEvent) expect(store.dispatch).toHaveBeenCalledWith(Shell.applyShellUpdate()) }) it('should render a "Not Now" button if update is downloaded', () => { getShellUpdateState.mockReturnValue({ downloaded: true, } as ShellUpdateState) const { wrapper } = render({ closeModal }) const notNowButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /not now/i.test(b.text()) ) notNowButton.invoke('onClick')?.({} as React.MouseEvent) expect(closeModal).toHaveBeenCalled() }) it('should render an ErrorModal if the update errors', () => { getShellUpdateState.mockReturnValue({ error: { message: 'Could not get code signature for running application', name: 'Error', }, } as ShellUpdateState) const { wrapper } = render({ closeModal }) const errorModal = wrapper.find(ErrorModal) expect(errorModal.prop('heading')).toBe('Update Error') expect(errorModal.prop('description')).toBe( 'Something went wrong while updating your app' ) expect(errorModal.prop('error')).toEqual({ message: 'Could not get code signature for running application', name: 'Error', }) errorModal.invoke('close')?.() expect(closeModal).toHaveBeenCalled() }) it('should call props.dismissAlert via the "Not Now" button', () => { const { wrapper } = render({ dismissAlert }) const notNowButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /not now/i.test(b.text()) ) expect(dismissAlert).not.toHaveBeenCalled() notNowButton.invoke('onClick')?.({} as React.MouseEvent) expect(dismissAlert).toHaveBeenCalledWith(false) }) it('should call props.dismissAlert via the Error modal "close" button', () => { getShellUpdateState.mockReturnValue({ error: { message: 'Could not get code signature for running application', name: 'Error', }, } as ShellUpdateState) const { wrapper } = render({ dismissAlert }) const errorModal = wrapper.find(ErrorModal) errorModal.invoke('close')?.() expect(dismissAlert).toHaveBeenCalledWith(false) }) it('should have a button to allow the user to dismiss alerts permanently', () => { const { wrapper } = render({ dismissAlert }) const ignoreButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) ignoreButton.invoke('onClick')?.({} as React.MouseEvent) const title = wrapper.find('h2') expect(wrapper.exists(ReleaseNotes)).toBe(false) expect(title.text()).toMatch(/turned off update notifications/i) expect(wrapper.text()).toMatch( /You've chosen to not be notified when an app update is available/ ) }) it('should not show the "ignore" button if modal was not alert triggered', () => { const { wrapper } = render({ closeModal }) const ignoreButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) expect(ignoreButton.exists()).toBe(false) }) it('should not show the "ignore" button if the user has proceeded with the update', () => { getShellUpdateState.mockReturnValue({ downloaded: true, } as ShellUpdateState) const { wrapper } = render({ dismissAlert }) const ignoreButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) expect(ignoreButton.exists()).toBe(false) }) it('should dismiss the alert permanently once the user clicks "OK"', () => { const { wrapper } = render({ dismissAlert }) wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) .invoke('onClick')?.({} as React.MouseEvent) wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /ok/i.test(b.text())) .invoke('onClick')?.({} as React.MouseEvent) expect(dismissAlert).toHaveBeenCalledWith(true) }) it('should dismiss the alert permanently if the component unmounts, for safety', () => { const { wrapper } = render({ dismissAlert }) wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) .invoke('onClick')?.({} as React.MouseEvent) wrapper.unmount() expect(dismissAlert).toHaveBeenCalledWith(true) }) it('should have a link to /more/app that also dismisses alert permanently', () => { const { wrapper } = render({ dismissAlert }) wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /turn off update notifications/i.test(b.text()) ) .invoke('onClick')?.({} as React.MouseEvent) wrapper .find(InternalLink) .filterWhere( (b: ReactWrapper<React.ComponentProps<typeof InternalLink>>) => b.prop('to') === '/more/app' ) .invoke('onClick')?.({} as React.MouseEvent<HTMLAnchorElement>) expect(dismissAlert).toHaveBeenCalledWith(true) }) it('should not send dismissal via unmount if button is close button clicked', () => { const { wrapper } = render({ dismissAlert }) const notNowButton = wrapper .find('button') .filterWhere((b: ReactWrapper<HTMLAttributes>) => /not now/i.test(b.text()) ) notNowButton.invoke('onClick')?.({} as React.MouseEvent) wrapper.unmount() expect(dismissAlert).toHaveBeenCalledTimes(1) expect(dismissAlert).toHaveBeenCalledWith(false) }) })
the_stack
* This module implements the odata server functionality * At the moment it is implemented as local loopback component * See here for more details on creating and registering loopback components * https://docs.strongloop.com/display/public/LB/Creating+components * */ // OData V4 import constants = require('./constants/odata_constants'); import common = require('./common/odata_common'); import ODataGetV4 = require('./v4/get/odata_get'); import ODataPostV4 = require('./v4/post/odata_post'); import ODataPutV4 = require('./v4/put/odata_put'); import ODataDeleteV4 = require('./v4/delete/odata_delete'); // OData V2 import ODataGetV2 = require('./v2/get/odata_get'); import ODataPostV2 = require('./v2/post/odata_post'); import ODataDeleteV2 = require('./v2/delete/odata_delete'); import ODataPutV2 = require('./v2/put/odata_put'); import fs = require( 'fs' ); import * as express from "express"; // Configure logging // TODO: make logging more flexible, e.g. let user configure the name and location of the log file via component configuration import log4js = require('log4js'); import {ODataServerConfig, RequestModelClass} from "./types/n_odata_types"; import {BaseRequestHandler} from "./base/BaseRequestHandler"; import {GetRequestHandler} from "./base/BaseRequestHandler"; import {PostRequestHandler} from "./base/BaseRequestHandler"; import {DeleteRequestHandler} from "./base/BaseRequestHandler"; import {PutRequestHandler} from "./base/BaseRequestHandler"; import {LoopbackApp, LoopbackRequest} from "./types/loopbacktypes"; import {HttpMethod} from "./constants/odata_enums"; fs.stat('n_odata_server_log.json', function (err, stat) { var fileName = __dirname + '/log4js.json'; if (!err) { fileName = 'n_odata_server_log.json'; } log4js.configure(fileName); }); var logger = log4js.getLogger("odata"); /** * This is the main entry class for the n-odata-server. There is only one instance of * this class. It implements the singleton pattern */ export class OData { private static singletonInstance: OData; private oLoopbackApp: LoopbackApp; private _oDataServerConfig:ODataServerConfig; private oDataGet: GetRequestHandler; private oDataPost: PostRequestHandler; private oDataDelete: DeleteRequestHandler; private oDataPut: PutRequestHandler; /* private variable that holds the status of initialization */ private initProceeded: boolean = false; constructor() { if(!OData.singletonInstance) { OData.singletonInstance = this; } return OData.singletonInstance; } /** * Getter for oDataServerConfig * @returns {ODataServerConfig} */ public getODataServerConfig():ODataServerConfig { return this._oDataServerConfig; } public init(loopbackApplication, options) { if(!this.initProceeded) { // run init only once options = options || {}; // ensure that options not undefined this.oLoopbackApp = loopbackApplication; // save the options defined in a local variable this._oDataServerConfig = this._oDataServerConfig || options || {}; // if not defined set a default value for server-side paging if (!this._oDataServerConfig.maxpagesize) { this._oDataServerConfig.maxpagesize = constants.ODATA_MAXPAGESIZE; } // retrieve odata prefix from path let _pathArr = (options && options.path && options.path.split('/')); if (_pathArr) { this._oDataServerConfig.odataPrefix = _pathArr[1]; } if (!this._oDataServerConfig.odataversion) { this._oDataServerConfig.odataversion = "4"; } common.setConfig(this._oDataServerConfig); if (this._oDataServerConfig.odataversion === "4") { this.oDataGet = new ODataGetV4.ODataGet(); this.oDataDelete = new ODataDeleteV4.ODataDelete(); this.oDataPost = new ODataPostV4.ODataPost(); this.oDataPut = new ODataPutV4.ODataPut(); this.oDataGet.setConfig(this._oDataServerConfig); } else { this.oDataGet = new ODataGetV2.ODataGet(); this.oDataPost = new ODataPostV2.ODataPost(); this.oDataDelete = new ODataDeleteV2.ODataDelete(); this.oDataPut = new ODataPutV2.ODataPut(); this.oDataGet.setConfig(this._oDataServerConfig); } // If using application wants to start odata server not via the recommended // way middleware but via component-config.json we start the server here. Otherwise // we do nothing more here. The server will then be started in /middleware/odata.ts if (!options.useViaMiddleware) { if (this._oDataServerConfig.odataversion === "4") { this._handleODataVersion4(loopbackApplication, options); } else if (this._oDataServerConfig.odataversion === "2") { this._handleODataVersion2(loopbackApplication, options); } else { logger.trace("odata version " + this._oDataServerConfig.odataversion + " not supported yet"); } } this.initProceeded = true; // ensure that init is only run once } }; /** * handles OData V2 requests * * @param loopbackApplication * @param options * @private */ private _handleODataVersion2(loopbackApplication, options) { // define the express / loopback route for OData V2 loopbackApplication.use(options.path, function(req:express.Request, res:express.Response, next) { this.handleRequestV2(req, res, next) }.bind(this)); } /** * handles the OData V4 requests. * * @param loopbackApplication * @param options * @private */ private _handleODataVersion4(loopbackApplication, options) { loopbackApplication.use(options.path, function (req:express.Request, res:express.Response, next) { this.handleRequestV4(req, res, next); }.bind(this)); } /** * handle the request that was sent by Express * @param req HTTP request * @param res HTTP response * @param next next phase in phase chain */ public handleRequestV2(req:LoopbackRequest, res:express.Response, next) { try { logger.info("processing OData V2 request of type " + req.method); logger.debug("baseUrl = " + req.baseUrl); this.checkAccess(req, res).then(() => { logger.debug("checkAccess passed successfully") let method:HttpMethod = this.getRequestMethod(req); switch (method) { case HttpMethod.GET: this._handleGet(req, res); break; case HttpMethod.POST: this._handlePost(req, res); break; // PUT is used to update an entity and to overwrite all property values with its default // values if they are not submitted with the request. In other words it resets an entity and // only sets the submitted properties case HttpMethod.PUT: this._handlePut(req, res); var i = 2; break; //// PATCH should be the preferred method to update an entity case HttpMethod.PATCH: this._handlePatch(req, res); break; //// MERGE is used in OData V2.0 to update an entity. This has been changed in //// in V4.0 to PATCH case HttpMethod.MERGE: this._handleMerge(req, res); break; case HttpMethod.DELETE: this._handleDelete(req, res); break; default: res.sendStatus(404); break; } }).catch((err) => { let statusCode = (err && err.statusCode) || 500; res.status(statusCode).send(err); }); } catch (e) { logger.error(e); res.status(500).send(e); } } /** * handle the V4 request that was sent by Express * @param req HTTP request * @param res HTTP response * @param next next phase in phase chain */ public handleRequestV4(req:LoopbackRequest, res:express.Response, next) { try { this.checkAccess(req, res).then(() => { let method = this.getRequestMethod(req); switch (method) { case HttpMethod.GET: this._handleGet(req, res); break; case HttpMethod.POST: this._handlePost(req, res); break; // PUT is used to update an entity and to overwrite all property values with its default // values if they are not submitted with the request. In other words it resets an entity and // only sets the submitted properties case HttpMethod.PUT: this._handlePut(req, res); break; // PATCH should be the preferred method to update an entity case HttpMethod.PATCH: this._handlePatch(req, res); break; // MERGE is used in OData V2.0 to update an entity. This has been changed in // in V4.0 to PATCH case HttpMethod.MERGE: this._handlePatch(req, res); break; case HttpMethod.DELETE: this._handleDelete(req, res); break; default: res.sendStatus(404); break; } }).catch((err) => { let statusCode = (err && err.statusCode) || 500; res.status(statusCode).send(err); }); } catch (e) { logger.error(e); res.status(500).send(e); } } /** * handles the GET request to the OData server * e.g. http://0.0.0.0:3000/odata/people * Here `people` is the pluralModelName of the Model to search * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ private _handleGet(req: LoopbackRequest, res: express.Response) { // delegate to version dependend module this.oDataGet.handleGet(req, res); } /** * handles the POST request to the OData server. * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ private _handlePost(req:LoopbackRequest, res:express.Response) { // delegate to version dependend module this.oDataPost.handlePost(req, res); } /** * handles the PUT request to the OData server. The PUT request is used to update an entity where * only the submitted properties are set. All other properties are reset to their default values. * Be aware that this could lead to data loss. If you only want to change the submitted properties * and keep all other properties values use PATCH or MERGE (only OData V2.0). * @param req * @param res * @private */ private _handlePut(req:LoopbackRequest, res:express.Response) { // delegate to put module this.oDataPut.handlePut(req, res); } /** * handles the PATCH request to the OData server. The PATCH request is used to update an entity where * only the submitted properties are set. The other properties of the entity will not be changed. * @param req * @param res * @private */ private _handlePatch(req:express.Request, res:express.Response) { // delegate to put module this.oDataPut.handlePatch(req, res); } /** * handles the MERGE request to the OData server. The MERGE request is used to update an entity where * only the submitted properties are set. The other properties of the entity will not be changed. * This is only available with OData V2 * @param req * @param res * @private */ private _handleMerge(req:express.Request, res:express.Response) { // delegate to put module this.oDataPut.handleMerge(req, res); } /** * handles the DELETE request of the OData server * @param req * @param res * @private */ private _handleDelete(req:express.Request, res:express.Response) { // delegate to delete module this.oDataDelete.handleDelete(req, res); } /** * Check access to a function / OData service. * If the user has access (Promise resolves) the handle... Method to handle the request can be called * @param req HttpRequest that was sent by the client * @param res HttpResponse that is sent back to the client * @returns {Promise<any>|Promise} */ checkAccess(req: LoopbackRequest, res: express.Response) { return new Promise<any>((resolve, reject) => { // $metadata and service requests are allways allowed if(req.params[0] === "$metadata" || req.params[0] === "") { logger.debug(`call to ${req.params[0]}. Doesn't need checkAccess`); resolve(); } else { // get the http verb from the request let method:HttpMethod = this.getRequestMethod(req); let remotes: any = this.oLoopbackApp.remotes(); // get the ModelClass from the request common.getRequestModelClass(this.oLoopbackApp.models, req.params[0]).then((modelClassResult: RequestModelClass) => { let ctx; // some requests do not return a modelClass if (modelClassResult && modelClassResult.modelClass) { for (let lbClass of remotes.classes()) { if (lbClass.name === modelClassResult.modelClass.modelName) { if (method === HttpMethod.GET) { ctx = this.getGETCheckAccessContext(req, lbClass); break; } else if (method === HttpMethod.POST) { ctx = this.getPOSTCheckAccessContext(req, lbClass); break; } else if (method === HttpMethod.PUT || method === HttpMethod.PATCH || method === HttpMethod.MERGE) { ctx = this.getPUTCheckAccessContext(req, lbClass); break; } else if (method === HttpMethod.DELETE) { ctx = this.getDELETECheckAccessContext(req, lbClass); break; } } } } // ctx must contain at least a method and an instance object if (ctx && ctx.method && ctx.instance) { // call the authorization method of the remotes object if (ctx.method.ctor.checkAccess) { ctx.method.ctor.checkAccess(req.accessToken, ctx.instance.id, ctx.method, ctx, (err, allowed) => { if (err) { logger.error(err); reject(err); } else if (allowed) { // delegate to get module resolve(); } else { let messages = { 403: { message: 'Access Denied', code: 'ACCESS_DENIED' }, 404: { message: ('could not find ' + ctx.method + ' with id ' + ctx.instance.id), code: 'MODEL_NOT_FOUND' }, 401: { message: 'Authorization Required', code: 'AUTHORIZATION_REQUIRED' } }; let errStatusCode = 401; let e = new Error(messages[errStatusCode].message || messages[403].message) as any; e.statusCode = errStatusCode; e.code = messages[errStatusCode].code || messages[403].code; reject(e); //res.sendStatus(e.statusCode); //.send(e.message); } }); } } else { logger.error(`Something went wrong with retrieving requestModelClass for request ${req.params[0]}`); let err = new Error(`You don't have access to request ${req.params[0]}.`) as any; err.statusCode = 401; reject(err); } }).catch(err => { logger.error(err); reject(err); }); } }); } /** * returns the http method (verb) from the request * @param req the http request * @returns {HttpMethod} the verb/method of the http request, e.g. GET, POST, PUT, ... */ private getRequestMethod(req: express.Request) { let method = req.method; if( method === HttpMethod[HttpMethod.POST]) { // check if http post tunneling is used (SAPUI5 uses it) let x_http_method: string = req.get('x-http-method'); if (x_http_method) { method = x_http_method; } } return HttpMethod[method]; } /** * Create context for checkAccess Method for a GET request * @param req * @param lbClass * @returns {{method: any, req: LoopbackRequest, instance: {id: any}}} */ private getGETCheckAccessContext(req: LoopbackRequest, lbClass: any) { // find "find", "findById" or "findOne" method in sharedMethods --> thats our wanted sharedMethod let re = /^\w*[(]([a-zA-Z0-9']*)[)]/g, match = re.exec(req.params[0]), _id, lbMethod; if (match) { lbMethod = lbClass.find("findById", true); _id = match[1]; } else { lbMethod = lbClass.find("find", true); } return { method: lbMethod, req: req, instance: { id: _id } }; } /** * Create context for checkAccess Method for a POST request * @param req * @param lbClass * @returns {{method: any, req: LoopbackRequest, instance: {id: any}}} */ private getPOSTCheckAccessContext(req: LoopbackRequest, lbClass: any) { // find "create" method in sharedMethods --> this method has to be secured via a POST request let lbMethod; lbMethod = lbClass.find("create", true); return { method: lbMethod, req: req, instance: { id: null } }; } /** * Create context for checkAccess Method for a PUT request * @param req * @param lbClass * @returns {{method: any, req: LoopbackRequest, instance: {id: any}}} */ private getPUTCheckAccessContext(req: LoopbackRequest, lbClass: any) { // find "updateAttributes" method in sharedMethods --> this method has to be secured via a POST request let re = /^\w*[(]([a-zA-Z0-9']*)[)]/g, match = re.exec(req.params[0]), _id, lbMethod; if (match) { lbMethod = lbClass.find("updateAttributes", false); _id = match[1]; } return { method: lbMethod, req: req, instance: { id: _id } }; } /** * Create context for checkAccess Method for a DELETE request * @param req * @param lbClass * @returns {{method: any, req: LoopbackRequest, instance: {id: any}}} */ private getDELETECheckAccessContext(req: LoopbackRequest, lbClass: any) { // find "updateAttributes" method in sharedMethods --> this method has to be secured via a POST request let re = /^\w*[(]([a-zA-Z0-9']*)[)]/g, match = re.exec(req.params[0]), _id, lbMethod; if (match) { lbMethod = lbClass.find("destroyById", true); _id = match[1]; } return { method: lbMethod, req: req, instance: { id: _id } }; } } /** * Exposes the main function of the n-odata-server */ export function init(loopbackApplication, options) { var oData = new OData(); oData.init(loopbackApplication, options) };
the_stack
import { systemPackages, TCromwellaConfig, TFrontendDependency, TPackageJson } from '@cromwell/core'; import { getNodeModuleDir, readCmsModules } from '@cromwell/core-backend'; import { each as asyncEach } from 'async'; import colorsdef from 'colors/safe'; import fs from 'fs-extra'; import glob from 'glob'; import importFrom from 'import-from'; import path, { resolve } from 'path'; import { TDependency, TGetDeps, THoistedDeps, TLocalSymlink, TModuleInfo, TNonHoisted, TPackage } from './types'; const colors: any = colorsdef; export const getNodeModuleVersion = (moduleName: string, importFromPath?: string): string | undefined => { const pckgImportName = `${moduleName}/package.json`; let modulePackageJson: TPackageJson | undefined; try { modulePackageJson = importFromPath ? importFrom(importFromPath, pckgImportName) as any : require(pckgImportName); } catch (e) { console.log(`Cromwell bundler: Failed to require package ${pckgImportName} ${importFromPath ? 'from ' + importFromPath : ''}. You may need to reconfigure your frontendDependencies`) } return modulePackageJson?.version; } export const getNodeModuleNameWithVersion = (moduleName: string): string | undefined => { const ver = getNodeModuleVersion(moduleName); if (ver) return `${moduleName}@${ver}`; } export const getDepVersion = (pckg: TPackageJson | TPackage, depName: string): string | undefined => { let ver = pckg?.dependencies?.[depName] ?? pckg?.devDependencies?.[depName] ?? pckg?.peerDependencies?.[depName]; if (ver) return ver; const frontDeps: (string | TFrontendDependency)[] | undefined = pckg?.cromwell?.frontendDependencies; if (frontDeps) { frontDeps.forEach(dep => { if (typeof dep === 'object' && dep.version) ver = dep.version; }) } return ver; } export const getDepNameWithVersion = (pckg: TPackageJson, depName: string): string | undefined => { const ver = getDepVersion(pckg, depName); if (ver) return `${depName}@${ver}`; } // Stores export keys of modules that have been requested const modulesExportKeys: Record<string, TModuleInfo> = {}; export const getModuleInfo = (moduleName: string, moduleVer?: string, from?: string): TModuleInfo => { let exportKeys: string[] | undefined; let exactVersion: string | undefined; if (!modulesExportKeys[moduleName]) { try { const imported: any = from ? importFrom(from, moduleName) : require(moduleName); const keys = Object.keys(imported); if (!keys.includes('default')) keys.unshift('default'); if (keys) exportKeys = keys; if (!exportKeys) throw new Error('!exportKeys') } catch (e) { try { const imported: any = require(moduleName); const keys = Object.keys(imported); if (keys && !keys.includes('default')) keys.unshift('default'); if (keys) exportKeys = keys; } catch (e) { console.log(colors.brightYellow(`Cromwell: Failed to require() module: ${moduleName}`)); } } try { const modulePackageJson: TPackageJson | undefined = from ? importFrom(from, `${moduleName}/package.json`) as any : require(`${moduleName}/package.json`); exactVersion = modulePackageJson?.version; if (!exactVersion) throw new Error('!exactVersion') } catch (e) { console.log(colors.brightYellow(`Cromwell: Failed to require() package.json of module: ${moduleName}`)); } const info: TModuleInfo = { exportKeys, exactVersion } modulesExportKeys[moduleName] = info; return info; } else { return modulesExportKeys[moduleName]; } } /** * Collect dependencies and devDependencies from all packages into provided @param store * Will calc usage number if package is already in the store and write different versions * @param packageDeps dependencies or devDependencies from package.json * @param packagePath absolute path to package.json * @param store store where to push or edit dependencies info */ const collectDeps = (packageDeps: Record<string, string>, packagePath: string, store: TDependency[]): TDependency[] => { // console.log('packagePath', packagePath); // console.log('store', store); for (const [moduleName, moduleVer] of Object.entries(packageDeps)) { let index: number | null = null; store.forEach((dep, i) => { if (dep.name === moduleName) { index = i; } }); if (index != null) { store[index].versions[moduleVer] = (store[index].versions[moduleVer] || 0) + 1; store[index].packages[packagePath] = moduleVer; } else { store.push({ name: moduleName, versions: { [moduleVer]: 1 }, packages: { [packagePath]: moduleVer } }) } } return store; } /** * Hoists provided dependencies. Creates one object with hoisted deps and array of ojects for each package where modules * cannot be hoisted (has different versions). * Also will find local packages that depends on other local packages * @param store collected dependencies from all package.json's by collectDeps function * @param packages info about all package.json files */ const hoistDeps = (store: TDependency[], packages: TPackage[], isProduction: boolean, forceInstall: boolean): THoistedDeps => { // Out main package.json with hoisted modules. Will be temporary placed in root of the project to install all modules // { [packageName]: version } const hoisted: Record<string, string> = {}; // Other local packages with different versions of modules from hoisted ones. Packages includes only those types of modules const nonHoisted: TNonHoisted = {}; const localSymlinks: TLocalSymlink[] = []; for (const module of store) { // Sort to set most frequently used version as first and then use it as hoisted one const versions = Object.entries(module.versions).sort((a, b) => b[1] - a[1]) .map(entry => entry[0]); const hoistedVersion = versions[0]; // Exclude modules that are local packages from being inclued in main package let localPckIndex: number | null = null; packages.forEach((pkg, i) => { if (pkg.name == module.name) localPckIndex = i }); if (localPckIndex != null) { // Module is a local package. It will be symlinked into other local packages that depends on it Object.keys(module.packages).forEach(dependentPckg => { if (localPckIndex == null) return; // console.log('dependentPckg: ', path.dirname(dependentPckg), 'module.name', module.name); const includeInPath = resolve(path.dirname(dependentPckg), 'node_modules', module.name); const includeToPath = path.dirname(packages[localPckIndex].path || ''); localSymlinks.push({ linkPath: includeInPath, referredDir: includeToPath }) }) } else { hoisted[module.name] = hoistedVersion; } // Handle different versions. if (versions.length > 1 && localPckIndex == null) { for (let i = 1; i < versions.length; i++) { const ver = versions[i]; Object.entries(module.packages).forEach(([packagePath, packageVer]) => { if (packageVer === ver) { const packageName = packages?.find(p => p.path === packagePath)?.name; console.log(colors.brightYellow(`\nCromwell:: Local package ${packageName} at ${packagePath} dependent on different version of hoisted package ${module.name}. \nHoisted (commonly used) ${module.name} is "${hoistedVersion}", but dependent is "${ver}".\n`)); if (!forceInstall) { console.log(colors.brightRed(`Cromwell:: Error. Abort operation. Please fix "${module.name}": "${ver}" or run command in force mode (add -f flag).\n`)); process.exit(); } // if (isProduction || (!isProduction && forceInstall)) { // console.log(colors.brightYellow(`Cromwell:: Installing ${module.name}: "${ver}" locally...\n`)); // } if (!nonHoisted[path.dirname(packagePath)]) { nonHoisted[path.dirname(packagePath)] = { name: packageName || '', modules: { [module.name]: ver } } } else { nonHoisted[path.dirname(packagePath)].modules[module.name] = ver; } } }) } } } return { hoisted, nonHoisted, localSymlinks } } export const getCromwellaConfigSync = (projectRootDir: string, canLog?: boolean): TCromwellaConfig | undefined => { const cromwellaConfigPath = resolve(projectRootDir, 'cromwella.json'); let cromwellaConfig: TCromwellaConfig | undefined = undefined; try { cromwellaConfig = JSON.parse(fs.readFileSync(cromwellaConfigPath).toString()); } catch (e) { if (canLog) console.log(e); } if (!cromwellaConfig || !cromwellaConfig.packages) { if (canLog) console.log(colors.brightRed(`\nCromwella:: Error. Failed to read config in ${cromwellaConfigPath}\n`)) } return cromwellaConfig; } export const globPackages = async (projectRootDir: string): Promise<string[]> => { // console.log(colors.cyan(`Cromwella:: Start. Scannig for local packages from ./cromwella.json...\n`)); const globOptions = {}; // From Cromwella config const cromwellaConfig = getCromwellaConfigSync(projectRootDir); const packageGlobs = cromwellaConfig?.packages ?? ['']; const packagePaths: string[] = []; await new Promise(done => { asyncEach(packageGlobs, function (pkgPath: string, callback: () => void) { const globPath = resolve(projectRootDir, pkgPath, 'package.json'); glob(globPath, globOptions, function (er: any, files: string[]) { files.forEach(f => packagePaths.push(resolve(projectRootDir, f))); callback(); }) }, () => done(true)); }); // From main package.json as cms modules const cmsModules = await readCmsModules(); const addDir = async (mod) => { const dir = await getNodeModuleDir(mod); if (dir) { packagePaths.push(resolve(dir, 'package.json')) } } for (const p of cmsModules.plugins) { await addDir(p); } for (const p of cmsModules.themes) { await addDir(p); } for (const p of systemPackages) { await addDir(p); } return packagePaths; } export const collectPackagesInfo = (packagePaths: string[]): TPackage[] => { packagePaths = Array.from(new Set(packagePaths)); if (packagePaths.length === 0) { console.log(colors.brightYellow(`\nCromwell:: No local packages found\n`)) return []; } // console.log(colors.cyan(`Cromwell:: Bootstraping local packages:`)); // packagePaths.forEach(path => { // console.log(colors.blue(path)); // }); // Collect info about package.json files const packages: TPackage[] = []; for (const pkgPath of packagePaths) { try { const pkgJson: TPackageJson = JSON.parse(fs.readFileSync(pkgPath).toString()); const pckg: TPackage = { name: pkgJson.name, path: pkgPath, dependencies: pkgJson.dependencies, devDependencies: pkgJson.devDependencies, peerDependencies: pkgJson.peerDependencies, cromwell: { frontendDependencies: pkgJson?.cromwell?.frontendDependencies } }; packages.push(pckg); } catch (e) { console.log(e); } } return packages; } export const hoistDependencies = (packages: TPackage[], isProduction, forceInstall): TGetDeps => { // Collect dependencies and devDependencies from all packages const dependencies: TDependency[] = []; const devDependencies: TDependency[] = []; for (const pkg of packages) { if (pkg.dependencies && pkg.path) { collectDeps(pkg.dependencies, pkg.path, dependencies); } } for (const pkg of packages) { if (pkg.devDependencies && pkg.path) { collectDeps(pkg.devDependencies, pkg.path, devDependencies); } } // Merge all dependencies into one object and create symlinks for local packages refs // There proccess can be exited if found same modules with diff versions in dev mode. const hoistedDependencies: THoistedDeps = JSON.parse(JSON.stringify(hoistDeps(dependencies, packages, isProduction, forceInstall))); const hoistedDevDependencies: THoistedDeps = JSON.parse(JSON.stringify(hoistDeps(devDependencies, packages, isProduction, forceInstall))); // All ok -> can start installation. return { packages, hoistedDependencies, hoistedDevDependencies }; } export const parseFrontendDeps = async (dependencies: (string | TFrontendDependency)[]): Promise<TFrontendDependency[]> => { const packagePaths = await globPackages(process.cwd()); const packages = collectPackagesInfo(packagePaths); let allDeps: Record<string, string> = {}; packages.forEach(p => { allDeps = { ...allDeps, ...(p.dependencies ?? {}), ...(p.devDependencies ?? {}), ...(p.peerDependencies ?? {}), } }) return dependencies.map(dep => { if (typeof dep === 'object') { if (!dep.version) dep.version = allDeps[dep.name]; return dep; } return { name: dep, version: allDeps[dep], } }); } export const collectFrontendDependencies = async (packages: TPackage[], forceInstall?: boolean): Promise<TFrontendDependency[]> => { const frontendDependencies = await parseFrontendDeps(defaultFrontendDeps); packages.forEach(pckg => { const pckheDeps = pckg?.cromwell?.frontendDependencies; if (pckheDeps && Array.isArray(pckheDeps)) { pckheDeps.forEach(dep => { const depName = typeof dep === 'object' ? dep.name : dep; const depVersion = getDepVersion(pckg, depName); if (!depVersion) return; const frontendDep: TFrontendDependency = typeof dep === 'object' ? dep : { name: dep, version: depVersion }; if (!frontendDep.version) frontendDep.version = depVersion; // if (!frontendDependencies.includes(dep)) let index: number | undefined = undefined; frontendDependencies.every((mainDep, i) => { if (mainDep.name === frontendDep.name) { if (mainDep.version !== frontendDep.version) { console.log(colors.brightYellow(`\nCromwell:: Local package ${pckg.name} at ${pckg.path} dependent on different version of used frontend module ${frontendDep.name}. \nAlready used ${frontendDep.name} is "${mainDep.version}", but dependent is "${frontendDep.version}".\n`)); if (!forceInstall) { console.log(colors.brightRed(`Cromwell:: Error. Please fix "${frontendDep.name}": "${frontendDep.version}"\n`)); } } else { index = i; } return false; } return true; }); if (index !== undefined) { if (typeof dep === 'object') { frontendDependencies[index] = frontendDep; } } else { frontendDependencies.push(frontendDep); } }) } }); return frontendDependencies; } export const interopDefaultContent = ` const interopDefault = (lib, importName) => { if (lib && typeof lib === 'object' && 'default' in lib) { if (importName !== 'default') { return lib.default; } if (typeof lib.default === 'object' || typeof lib.default === 'function') { if (Object.keys(lib).length === 1) { return lib.default; } else if ('default' in lib.default && Object.keys(lib).length === Object.keys(lib.default).length) { return lib.default; } else if (Object.keys(lib).length === Object.keys(lib.default).length + 1) { return lib.default; } } } return lib; } `; export const jsOperators = ['let', 'var', 'const', 'function', 'class', 'new', 'delete', 'import', 'export', 'default', 'typeof', 'in', 'of', 'instanceof', 'void', 'return', 'try', 'catch', 'throw', 'if', 'else', 'switch', 'case', 'continue', 'do', 'while']; export const cromwellStoreModulesPath = 'CromwellStore.nodeModules.modules'; export const cromwellStoreStatusesPath = 'CromwellStore.nodeModules.importStatuses'; export const cromwellStoreImportsPath = 'CromwellStore.nodeModules.imports'; export const getGlobalModuleStr = (moduleName: string) => `${cromwellStoreModulesPath}['${moduleName}']`; export const getGlobalModuleStatusStr = (moduleName: string) => `${cromwellStoreStatusesPath}['${moduleName}']`; export const tempPckgName = '@cromwell/temp-bundler'; export const defaultFrontendDeps: (string | TFrontendDependency)[] = [ "@apollo/client", "@cromwell/core", "@cromwell/admin-panel", { "name": "@cromwell/core-frontend", "externals": [ { "usedName": "next/head" }, { "usedName": "next/router" }, { "usedName": "next/link" }, { "usedName": "next/dynamic" }, { "usedName": "next/document" } ] }, "@loadable/component", "clsx", "throttle-debounce", "query-string", "react", "react-dom", "react-is", "react-number-format", "react-router-dom", "react-toastify", "tslib", "react-resize-detector", { name: "pure-react-carousel", bundledCss: [ 'pure-react-carousel/dist/react-carousel.es.css', ] }, { name: "react-image-lightbox", bundledCss: [ 'react-image-lightbox/style.css', ] }, ];
the_stack
import {Node} from './tree'; const CSS_PREFIX = 'webtreemap-'; const NODE_CSS_CLASS = CSS_PREFIX + 'node'; const DEFAULT_CSS = ` .webtreemap-node { cursor: pointer; position: absolute; border: solid 1px #666; box-sizing: border-box; overflow: hidden; background: white; transition: left .15s, top .15s, width .15s, height .15s; } .webtreemap-node:hover { background: #ddd; } .webtreemap-caption { font-size: 10px; text-align: center; } `; function addCSS(parent: HTMLElement) { const style = document.createElement('style'); style.innerText = DEFAULT_CSS; parent.appendChild(style); } export function isDOMNode(e: Element): boolean { return e.classList.contains(NODE_CSS_CLASS); } /** * Options is the set of user-provided webtreemap configuration. */ export interface Options { padding: [number, number, number, number]; lowerBound: number; applyMutations(node: Node): void, caption(node: Node): string; showNode(node: Node, width: number, height: number): boolean; showChildren(node: Node, width: number, height: number): boolean; } /** * get the index of this node in its parent's children list. * O(n) but we expect n to be small. */ function getNodeIndex(target: Element): number { let index = 0; let node: Element | null = target; while ((node = node.previousElementSibling)) { if (isDOMNode(node)) index++; } return index; } /** * Given a DOM node, compute its address: an array of indexes * into the Node tree. An address [a1,a2,...] refers to * tree.chldren[a1].children[a2].children[...]. */ export function getAddress(el: Element): number[] { let address: number[] = []; let n: Element | null = el; while (n && isDOMNode(n)) { address.unshift(getNodeIndex(n)); n = n.parentElement; } address.shift(); // The first element will be the root, index 0. return address; } /** * Converts a number to a CSS pixel string. */ function px(x: number): string { // Rounding when computing pixel coordinates makes the box edges touch // better than letting the browser do it, because the browser has lots of // heuristics around handling non-integer pixel coordinates. return Math.round(x) + 'px'; } function defaultOptions(options: Partial<Options>): Options { const opts = { padding: options.padding || [14, 3, 3, 3], lowerBound: options.lowerBound === undefined ? 0.1 : options.lowerBound, applyMutations: options.applyMutations || (() => null), caption: options.caption || ((node: Node) => node.id || ''), showNode: options.showNode || ((node: Node, width: number, height: number): boolean => { return width > 20 && height >= opts.padding[0]; }), showChildren: options.showChildren || ((node: Node, width: number, height: number): boolean => { return width > 40 && height > 40; }), }; return opts; } export class TreeMap { readonly options: Options; constructor(public node: Node, options: Partial<Options>) { this.options = defaultOptions(options); } /** Creates the DOM for a single node if it doesn't have one already. */ ensureDOM(node: Node): HTMLElement { if (node.dom) return node.dom; const dom = document.createElement('div'); dom.className = NODE_CSS_CLASS; if (this.options.caption) { const caption = document.createElement('div'); caption.className = CSS_PREFIX + 'caption'; caption.innerText = this.options.caption(node); dom.appendChild(caption); } node.dom = dom; this.options.applyMutations(node); return dom; } /** * Given a list of sizes, the 1-d space available * |space|, and a starting rectangle index |start|, compute a span of * rectangles that optimizes a pleasant aspect ratio. * * Returns [end, sum], where end is one past the last rectangle and sum is the * 2-d sum of the rectangles' areas. */ private selectSpan( children: Node[], space: number, start: number ): {end: number; sum: number} { // Add rectangles one by one, stopping when aspect ratios begin to go // bad. Result is [start,end) covering the best run for this span. // http://scholar.google.com/scholar?cluster=5972512107845615474 let smin = children[start].size; // Smallest seen child so far. let smax = smin; // Largest child. let sum = 0; // Sum of children in this span. let lastScore = 0; // Best score yet found. let end = start; for (; end < children.length; end++) { const size = children[end].size; if (size < smin) smin = size; if (size > smax) smax = size; // Compute the relative squariness of the rectangles with this // additional rectangle included. const nextSum = sum + size; // Suppose you're laying out along the x axis, so "space"" is the // available width. Then the height of the span of rectangles is // height = sum/space // // The largest rectangle potentially will be too wide. // Its width and width/height ratio is: // width = smax / height // width/height = (smax / (sum/space)) / (sum/space) // = (smax * space * space) / (sum * sum) // // The smallest rectangle potentially will be too narrow. // Its width and height/width ratio is: // width = smin / height // height/width = (sum/space) / (smin / (sum/space)) // = (sum * sum) / (smin * space * space) // // Take the larger of these two ratios as the measure of the // worst non-squarenesss. const score = Math.max( (smax * space * space) / (nextSum * nextSum), (nextSum * nextSum) / (smin * space * space) ); if (lastScore && score > lastScore) { // Including this additional rectangle produces worse squareness than // without it. We're done. break; } lastScore = score; sum = nextSum; } return {end, sum}; } /** Creates and positions child DOM for a node. */ private layoutChildren( node: Node, level: number, width: number, height: number ) { const total: number = node.size; const children = node.children; if (!children) return; // We use box-sizing: border-box so CSS 'width' etc include the border. // With 0 padding we want children to perfectly overlap their parent, // so we start with offsets of -1 (to start at the same point as the // parent) and create each box 1px larger than necessary (to make // adjoining borders overlap). let x1 = -1, y1 = -1, x2 = width - 1, y2 = height - 1; const spacing = 0; // TODO: this.options.spacing; const padding = this.options.padding; y1 += padding[0]; if (padding[1]) { // If there's any right-padding, subtract an extra pixel to allow for the // boxes being one pixel wider than necessary. x2 -= padding[1] + 1; } y2 -= padding[2]; x1 += padding[3]; let i: number = 0; if (this.options.showChildren(node, x2 - x1, y2 - y1)) { const scale = Math.sqrt(total / ((x2 - x1) * (y2 - y1))); var x = x1, y = y1; children: for (let start = 0; start < children.length; ) { x = x1; const space = scale * (x2 - x1); const {end, sum} = this.selectSpan(children, space, start); if (sum / total < this.options.lowerBound) break; const height = sum / space; const heightPx = Math.round(height / scale) + 1; for (i = start; i < end; i++) { const child = children[i]; const size = child.size; const width = size / height; const widthPx = Math.round(width / scale) + 1; if ( !this.options.showNode(child, widthPx - spacing, heightPx - spacing) ) { break children; } const needsAppend = child.dom == null; const dom = this.ensureDOM(child); const style = dom.style; style.left = px(x); style.width = px(widthPx - spacing); style.top = px(y); style.height = px(heightPx - spacing); if (needsAppend) { node.dom!.appendChild(dom); } this.layoutChildren(child, level + 1, widthPx, heightPx); // -1 so inner borders overlap. x += widthPx - 1; } // -1 so inner borders overlap. y += heightPx - 1; start = end; } } // Remove the DOM for any children we didn't visit. // These can be created if we zoomed in then out. for (; i < children.length; i++) { if (!children[i].dom) break; children[i].dom!.parentNode!.removeChild(children[i].dom!); children[i].dom = undefined; } } /** * Creates the full treemap in a container element. * The treemap is sized to the size of the container. */ render(container: HTMLElement) { addCSS(container); const dom = this.ensureDOM(this.node); const width = container.offsetWidth; const height = container.offsetHeight; dom.onclick = e => { let node: Element | null = e.target as Element; while (!isDOMNode(node)) { node = node.parentElement; if (!node) return; } let address = getAddress(node); this.zoom(address); }; dom.style.width = width + 'px'; dom.style.height = height + 'px'; container.appendChild(dom); this.layoutChildren(this.node, 0, width, height); } /** * Zooms the treemap to display a specific node. * See getAddress() for a discussion of what address means. */ zoom(address: number[]) { let node = this.node; const [padTop, padRight, padBottom, padLeft] = this.options.padding; let width = node.dom!.offsetWidth; let height = node.dom!.offsetHeight; for (const index of address) { width -= padLeft + padRight; height -= padTop + padBottom; if (!node.children) throw new Error('bad address'); for (const c of node.children) { if (c.dom) c.dom.style.zIndex = '0'; } node = node.children[index]; const style = node.dom!.style; style.zIndex = '1'; // See discussion in layout() about positioning. style.left = px(padLeft - 1); style.width = px(width); style.top = px(padTop - 1); style.height = px(height); } this.layoutChildren(node, 0, width, height); } } /** Main entry point; renders a tree into an HTML container. */ export function render( container: HTMLElement, node: Node, options: Partial<Options> ) { new TreeMap(node, options).render(container); }
the_stack
import {cls} from '../../src/cls'; import {Constants} from '../../src/constants'; import {TraceLabels} from '../../src/trace-labels'; import * as TracingPolicy from '../../src/tracing-policy'; import * as util from '../../src/util'; import * as assert from 'assert'; import {it, before, after, afterEach} from 'mocha'; import { asRootSpanData, describeInterop, DEFAULT_SPAN_DURATION, assertSpanDuration, } from '../utils'; import {Span} from '../../src/plugin-types'; import {FORCE_NEW} from '../../src/util'; import * as shimmer from 'shimmer'; // eslint-disable-next-line @typescript-eslint/no-var-requires const common = require('./common' /*.js*/); const protoFile = __dirname + '/../fixtures/test-grpc.proto'; const grpcPort = 50051; // When received in the 'n' field, the server should perform the appropriate action // (For client streaming methods, this would be the total sum of all requests) const SEND_METADATA = 131; const EMIT_ERROR = 13412; // Regular expression matching client-side metadata labels const metadataRegExp = /"a":"b"/; // Whether asserts in checkServerMetadata should be run // Turned on only for the test that checks propagated trace context let checkMetadata; // When trace IDs are checked in checkServerMetadata, they should have this // exact value. This only applies in the test "should support distributed // context". const COMMON_TRACE_ID = 'ffeeddccbbaa99887766554433221100'; function checkServerMetadata(metadata) { if (checkMetadata) { const traceContext = metadata.getMap()[Constants.TRACE_CONTEXT_GRPC_METADATA_NAME]; const parsedContext = util.deserializeTraceContext(traceContext); assert.ok(parsedContext); const root = asRootSpanData(cls.get().getContext() as Span); // Check that we were able to propagate trace context. assert.strictEqual(parsedContext!.traceId, COMMON_TRACE_ID); assert.strictEqual(root.trace.traceId, COMMON_TRACE_ID); // Check that we correctly assigned the parent ID of the current span to // that of the incoming span ID. assert.strictEqual(root.span.parentSpanId, parsedContext!.spanId); } } function startServer(proto, grpc, agent, metadata, trailing_metadata) { const _server = new grpc.Server(); _server.addProtoService(proto.Tester.service, { testUnary: function (call, cb) { checkServerMetadata(call.metadata); if (call.request.n === EMIT_ERROR) { common.createChildSpan(() => { cb(new Error('test')); }, DEFAULT_SPAN_DURATION); } else if (call.request.n === SEND_METADATA) { call.sendMetadata(metadata); setTimeout(() => { cb(null, {n: call.request.n}, trailing_metadata); }, DEFAULT_SPAN_DURATION); } else { common.createChildSpan(() => { cb(null, {n: call.request.n}); }, DEFAULT_SPAN_DURATION); } }, testClientStream: function (call, cb) { checkServerMetadata(call.metadata); let sum = 0; let triggerCb = function () { cb(null, {n: sum}); }; let stopChildSpan; call.on('data', data => { // Creating child span in stream event handler to ensure that // context is propagated correctly if (!stopChildSpan) { stopChildSpan = common.createChildSpan(() => { triggerCb(); }, DEFAULT_SPAN_DURATION); } sum += data.n; }); call.on('end', () => { if (sum === EMIT_ERROR) { triggerCb = function () { if (stopChildSpan) { stopChildSpan(); } cb(new Error('test')); }; } else if (sum === SEND_METADATA) { call.sendMetadata(metadata); triggerCb = function () { cb(null, {n: sum}, trailing_metadata); }; } }); }, testServerStream: function (stream) { checkServerMetadata(stream.metadata); if (stream.request.n === EMIT_ERROR) { common.createChildSpan(() => { stream.emit('error', new Error('test')); }, DEFAULT_SPAN_DURATION); } else { if (stream.request.n === SEND_METADATA) { stream.sendMetadata(metadata); } for (let i = 0; i < 10; ++i) { stream.write({n: i}); } common.createChildSpan(() => { stream.end(); }, DEFAULT_SPAN_DURATION); } }, testBidiStream: function (stream) { checkServerMetadata(stream.metadata); let sum = 0; let stopChildSpan; const t = setTimeout(() => { stream.end(); }, DEFAULT_SPAN_DURATION); stream.on('data', data => { // Creating child span in stream event handler to ensure that // context is propagated correctly if (!stopChildSpan) { stopChildSpan = common.createChildSpan(null, DEFAULT_SPAN_DURATION); } sum += data.n; stream.write({n: data.n}); }); stream.on('end', () => { stopChildSpan(); if (sum === EMIT_ERROR) { clearTimeout(t); setTimeout(() => { if (stopChildSpan) { stopChildSpan(); } stream.emit('error', new Error('test')); }, DEFAULT_SPAN_DURATION); } else if (sum === SEND_METADATA) { stream.sendMetadata(metadata); } }); }, }); _server.bind( 'localhost:' + grpcPort, grpc.ServerCredentials.createInsecure() ); _server.start(); return _server; } function createClient(proto, grpc) { return new proto.Tester( 'localhost:' + grpcPort, grpc.credentials.createInsecure() ); } function callUnary(client, grpc, metadata, cb) { const args = [ {n: 42}, function (err, result) { assert.ifError(err); assert.strictEqual(result.n, 42); cb(); }, ]; if (Object.keys(metadata).length > 0) { const m = new grpc.Metadata(); for (const key in metadata) { m.add(key, metadata[key]); } args.splice(1, 0, m); } // eslint-disable-next-line prefer-spread client.testUnary.apply(client, args); } function callClientStream(client, grpc, metadata, cb) { const args = [ function (err, result) { assert.ifError(err); assert.strictEqual(result.n, 45); cb(); }, ]; if (Object.keys(metadata).length > 0) { const m = new grpc.Metadata(); for (const key in metadata) { m.add(key, metadata[key]); } args.unshift(m); } // eslint-disable-next-line prefer-spread const stream = client.testClientStream.apply(client, args); for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); } function callServerStream(client, grpc, metadata, cb) { const args = [{n: 42}]; if (Object.keys(metadata).length > 0) { const m = new grpc.Metadata(); for (const key in metadata) { m.add(key, metadata[key]); } args.push(m); } // eslint-disable-next-line prefer-spread const stream = client.testServerStream.apply(client, args); let sum = 0; stream.on('data', data => { sum += data.n; }); stream.on('status', status => { assert.strictEqual(status.code, grpc.status.OK); assert.strictEqual(sum, 45); cb(); }); } function callBidi(client, grpc, metadata, cb) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const args: any[] = []; if (Object.keys(metadata).length > 0) { const m = new grpc.Metadata(); for (const key in metadata) { m.add(key, metadata[key]); } args.push(m); } // eslint-disable-next-line prefer-spread const stream = client.testBidiStream.apply(client, args); let sum = 0; stream.on('data', data => { sum += data.n; }); for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); stream.on('status', status => { assert.strictEqual(status.code, grpc.status.OK); assert.strictEqual(sum, 45); cb(); }); } describeInterop('grpc', fixture => { let agent; let grpc; let metadata; let server; let client; // eslint-disable-next-line @typescript-eslint/no-explicit-any let shouldTraceArgs: any[] = []; before(() => { // Set up to record invocations of shouldTrace shimmer.wrap( TracingPolicy.BuiltinTracePolicy.prototype, 'shouldTrace', original => { return function (options) { shouldTraceArgs.push(options); // eslint-disable-next-line prefer-rest-params return original.apply(this, arguments); }; } ); // It is necessary for the samplingRate to be 0 for the tests to succeed agent = require('../../..').start({ projectId: '0', samplingRate: 0, enhancedDatabaseReporting: true, [FORCE_NEW]: true, }); grpc = fixture.require(); const oldRegister = grpc.Server.prototype.register; grpc.Server.prototype.register = function register(n, h, s, d, m) { const result = oldRegister.call(this, n, h, s, d, m); const oldFunc = this.handlers[n].func; this.handlers[n].func = function () { // eslint-disable-next-line prefer-rest-params return oldFunc.apply(this, arguments); }; return result; }; // This metadata can be used by all test methods. metadata = new grpc.Metadata(); metadata.set('a', 'b'); // Trailing metadata can be sent by unary and client stream requests. const trailing_metadata = new grpc.Metadata(); trailing_metadata.set('c', 'd'); const proto = grpc.load(protoFile).nodetest; server = startServer(proto, grpc, agent, metadata, trailing_metadata); client = createClient(proto, grpc); }); after(() => { server.forceShutdown(); }); afterEach(() => { shouldTraceArgs = []; common.cleanTraces(); checkMetadata = false; }); it('should accurately measure time for unary requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { callUnary(client, grpc, {}, () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); assert.strictEqual(trace.labels.argument, '{"n":42}'); assert.strictEqual(trace.labels.result, '{"n":42}'); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should accurately measure time for client streaming requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { callClientStream(client, grpc, {}, () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); assert.strictEqual(trace.labels.result, '{"n":45}'); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should accurately measure time for server streaming requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { callServerStream(client, grpc, {}, () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); assert.strictEqual(trace.labels.argument, '{"n":42}'); return trace; }; const clientTrace = assertTraceProperties(grpcClientPredicate); assert.strictEqual( clientTrace.labels.status, '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}' ); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should accurately measure time for bidi streaming requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { callBidi(client, grpc, {}, () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); return trace; }; const clientTrace = assertTraceProperties(grpcClientPredicate); assert.strictEqual( clientTrace.labels.status, '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}' ); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); // Older versions of gRPC (<1.7) do not add original names. fixture.skip(it, '1.6')( 'should trace client requests using the original method name', done => { common.runInTransaction(endTransaction => { // The original method name is TestUnary. client.TestUnary({n: 10}, (err, result) => { assert.ifError(err); assert.strictEqual(result.n, 10); endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.strictEqual(trace.labels.argument, '{"n":10}'); assert.strictEqual(trace.labels.result, '{"n":10}'); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert.ok(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); } ); it('should propagate context', done => { common.runInTransaction(endTransaction => { callUnary(client, grpc, {}, () => { assert.ok(common.hasContext()); endTransaction(); done(); }); }); }); it('should not break if no parent transaction', done => { callUnary(client, grpc, {}, () => { assert.strictEqual( common.getMatchingSpans(grpcClientPredicate).length, 0 ); done(); }); }); it('should respect the tracing policy', done => { let next = function () { assert.strictEqual( shouldTraceArgs.length, 4, 'expected one call for each of four gRPC method types but got ' + shouldTraceArgs.length + ' instead' ); const prefix = 'grpc:/nodetest.Tester/Test'; // calls to shouldTrace should be in the order which the client method // of each type was called. assert.strictEqual(shouldTraceArgs[3].url, prefix + 'Unary'); assert.strictEqual(shouldTraceArgs[2].url, prefix + 'ClientStream'); assert.strictEqual(shouldTraceArgs[1].url, prefix + 'ServerStream'); assert.strictEqual(shouldTraceArgs[0].url, prefix + 'BidiStream'); done(); }; next = callUnary.bind(null, client, grpc, {}, next); next = callClientStream.bind(null, client, grpc, {}, next); next = callServerStream.bind(null, client, grpc, {}, next); next = callBidi.bind(null, client, grpc, {}, next); next(); }); it('should support distributed trace context', done => { function makeLink(fn, meta, next) { return function () { agent.runInRootSpan( { name: '', traceContext: { traceId: COMMON_TRACE_ID, spanId: '0', options: 1, }, }, span => { assert.strictEqual(span.type, agent.spanTypes.ROOT); fn(client, grpc, meta, () => { span.endSpan(); next(); }); } ); }; } // Enable asserting properties of the metdata on the grpc server. checkMetadata = true; let next; const metadata = {a: 'b'}; next = function () { checkMetadata = false; done(); }; // Try without supplying metadata (call* will not supply metadata to // the grpc client methods at all if no fields are present). // The plugin should automatically create a new Metadata object and // populate it with trace context data accordingly. next = makeLink(callUnary, {}, next); next = makeLink(callClientStream, {}, next); next = makeLink(callServerStream, {}, next); next = makeLink(callBidi, {}, next); // Try with metadata. The plugin should simply add trace context data // to it. next = makeLink(callUnary, metadata, next); next = makeLink(callClientStream, metadata, next); next = makeLink(callServerStream, metadata, next); next = makeLink(callBidi, metadata, next); next(); }); it('should not let root spans interfere with one another', function (done) { this.timeout(8000); let next = done; // Calling queueCallTogether builds a call chain, with each link // testing interference between two gRPC calls spaced apart by half // of DEFAULT_SPAN_DURATION (to interleave them). // This chain is kicked off with an initial call to next(). const queueCallTogether = function (first, second) { const prevNext = next; next = function () { let startFirst, startSecond, endFirst; common.runInTransaction(endTransaction => { let num = 0; common.cleanTraces(); const callback = function () { if (num === 0) { endFirst = Date.now(); } if (++num === 2) { endTransaction(); const spans = common.getMatchingSpans(grpcServerOuterPredicate); assert(spans.length === 2); assert(spans[0].spanId !== spans[1].spanId); assert(spans[0].startTime !== spans[1].startTime); assertSpanDuration(spans[0], [ DEFAULT_SPAN_DURATION, endFirst - startFirst, ]); assertSpanDuration(spans[1], [ DEFAULT_SPAN_DURATION, Date.now() - startSecond, ]); setImmediate(prevNext); } }; startFirst = Date.now(); first(callback); setTimeout(() => { startSecond = Date.now(); second(callback); }, DEFAULT_SPAN_DURATION / 2); }); }; }; // Call queueCallTogether with every possible pair of gRPC calls. const methods = [ callUnary.bind(null, client, grpc, {}), callClientStream.bind(null, client, grpc, {}), callServerStream.bind(null, client, grpc, {}), callBidi.bind(null, client, grpc, {}), ]; for (const m of methods) { for (const n of methods) { queueCallTogether(m, n); } } // Kick off call chain. next(); }); it('should remove trace frames from stack', done => { common.runInTransaction(endTransaction => { client.testUnary({n: 42}, (err, result) => { endTransaction(); assert.ifError(err); assert.strictEqual(result.n, 42); function getMethodName(predicate) { const trace = common.getMatchingSpan(predicate); const labels = trace.labels; const stack = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); return stack.stack_frame[0].method_name; } assert.notStrictEqual( -1, getMethodName(grpcClientPredicate).indexOf('clientMethodTrace') ); assert.notStrictEqual( -1, getMethodName(grpcServerOuterPredicate).indexOf('serverMethodTrace') ); done(); }); }); }); it('should trace errors for unary requests', done => { common.runInTransaction(endTransaction => { client.testUnary({n: EMIT_ERROR}, err => { endTransaction(); assert(err); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.strictEqual(trace.labels.argument, '{"n":' + EMIT_ERROR + '}'); assert.ok(trace.labels.error.indexOf('test') !== -1); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should trace errors for client streaming requests', done => { common.runInTransaction(endTransaction => { const stream = client.testClientStream(err => { endTransaction(); assert(err); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); stream.write({n: EMIT_ERROR}); stream.end(); }); }); it('should trace errors for server streaming requests', done => { common.runInTransaction(endTransaction => { const stream = client.testServerStream({n: EMIT_ERROR}, metadata); stream.on('data', () => {}); stream.on('error', () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should trace errors for bidi streaming requests', done => { common.runInTransaction(endTransaction => { const stream = client.testBidiStream(metadata); stream.on('data', () => {}); stream.write({n: EMIT_ERROR}); stream.end(); stream.on('error', () => { endTransaction(); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); done(); }); }); }); it('should trace metadata for server streaming requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { const stream = client.testServerStream({n: SEND_METADATA}, metadata); stream.on('data', () => {}); stream.on('status', status => { endTransaction(); assert.strictEqual(status.code, grpc.status.OK); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); assert.ok(metadataRegExp.test(trace.labels.metadata)); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); done(); }); }); }); it('should trace metadata for bidi streaming requests', done => { const start = Date.now(); common.runInTransaction(endTransaction => { const stream = client.testBidiStream(metadata); stream.on('data', () => {}); stream.write({n: SEND_METADATA}); stream.end(); stream.on('status', status => { endTransaction(); assert.strictEqual(status.code, grpc.status.OK); const assertTraceProperties = function (predicate) { const trace = common.getMatchingSpan(predicate); assert(trace); assertSpanDuration(common.getMatchingSpan(predicate), [ DEFAULT_SPAN_DURATION, Date.now() - start, ]); assert.ok(metadataRegExp.test(trace.labels.metadata)); }; assertTraceProperties(grpcClientPredicate); assertTraceProperties(grpcServerOuterPredicate); done(); }); }); }); }); function grpcClientPredicate(span) { return span.kind === 'RPC_CLIENT' && span.name.indexOf('grpc:') === 0; } function grpcServerOuterPredicate(span) { return span.kind === 'RPC_SERVER' && span.name.indexOf('grpc:') === 0; } function grpcServerInnerPredicate(span) { return span.kind === 'RPC_CLIENT' && span.name === 'inner'; } export default {};
the_stack
import { Byte, Int32, UInt16, UInt32, UInt64 } from "node-opcua-basic-types"; import { AttributeIds } from "node-opcua-data-model"; import { NodeId, resolveNodeId } from "node-opcua-nodeid"; import { IBasicSession } from "node-opcua-pseudo-session"; import { ReadValueIdOptions } from "node-opcua-service-read"; import { BrowsePath, makeBrowsePath } from "node-opcua-service-translate-browse-path"; import { StatusCodes } from "node-opcua-status-code"; import { DataType, VariantArrayType } from "node-opcua-variant"; import { MethodIds } from "node-opcua-constants"; import { checkDebugFlag, make_debugLog, make_errorLog } from "node-opcua-debug"; const debugLog = make_debugLog("FileType"); const errorLog = make_errorLog("FileType"); const doDebug = checkDebugFlag("FileType"); import { OpenFileMode } from "../open_mode"; export { OpenFileMode } from "../open_mode"; /** * * */ export class ClientFile { public static useGlobalMethod = false; public fileHandle = 0; protected session: IBasicSession; protected readonly fileNodeId: NodeId; private openMethodNodeId?: NodeId; private closeMethodNodeId?: NodeId; private setPositionNodeId?: NodeId; private getPositionNodeId?: NodeId; private readNodeId?: NodeId; private writeNodeId?: NodeId; private openCountNodeId?: NodeId; private sizeNodeId?: NodeId; constructor(session: IBasicSession, nodeId: NodeId) { this.session = session; this.fileNodeId = nodeId; } public async open(mode: OpenFileMode): Promise<number> { if (mode === null || mode === undefined) { throw new Error("expecting a validMode " + OpenFileMode[mode]); } if (this.fileHandle) { throw new Error("File has already be opened"); } await this.ensureInitialized(); const result = await this.session.call({ inputArguments: [ { dataType: DataType.Byte, value: mode as Byte } ], methodId: this.openMethodNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { debugLog("Cannot open file : "); throw new Error("cannot open file statusCode = " + result.statusCode.toString() + " mode = " + OpenFileMode[mode]); } this.fileHandle = result.outputArguments![0].value; return this.fileHandle; } public async close(): Promise<void> { if (!this.fileHandle) { throw new Error("File has not been opened yet"); } await this.ensureInitialized(); const result = await this.session.call({ inputArguments: [ { dataType: DataType.UInt32, value: this.fileHandle } ], methodId: this.closeMethodNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { debugLog("Cannot close file : "); throw new Error("cannot close file statusCode = " + result.statusCode.toString()); } this.fileHandle = 0; } public async getPosition(): Promise<UInt64> { await this.ensureInitialized(); if (!this.fileHandle) { throw new Error("File has not been opened yet"); } const result = await this.session.call({ inputArguments: [ { dataType: DataType.UInt32, value: this.fileHandle } ], methodId: this.getPositionNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { throw new Error("Error " + result.statusCode.toString()); } return result.outputArguments![0].value as UInt64; } public async setPosition(position: UInt64 | UInt32): Promise<void> { await this.ensureInitialized(); if (!this.fileHandle) { throw new Error("File has not been opened yet"); } if (typeof position === "number") { position = [0, position]; } const result = await this.session.call({ inputArguments: [ { dataType: DataType.UInt32, value: this.fileHandle }, { arrayType: VariantArrayType.Scalar, dataType: DataType.UInt64, value: position } ], methodId: this.setPositionNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { throw new Error("Error " + result.statusCode.toString()); } return; } public async read(bytesToRead: Int32): Promise<Buffer> { await this.ensureInitialized(); if (!this.fileHandle) { throw new Error("File has not been opened yet"); } const result = await this.session.call({ inputArguments: [ { dataType: DataType.UInt32, value: this.fileHandle }, { arrayType: VariantArrayType.Scalar, dataType: DataType.Int32, value: bytesToRead } ], methodId: this.readNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { throw new Error("Error " + result.statusCode.toString()); } if (!result.outputArguments || result.outputArguments[0].dataType !== DataType.ByteString) { throw new Error("Error invalid output"); } return result.outputArguments![0].value as Buffer; } public async write(data: Buffer): Promise<void> { await this.ensureInitialized(); if (!this.fileHandle) { throw new Error("File has not been opened yet"); } const result = await this.session.call({ inputArguments: [ { dataType: DataType.UInt32, value: this.fileHandle }, { arrayType: VariantArrayType.Scalar, dataType: DataType.ByteString, value: data } ], methodId: this.writeNodeId, objectId: this.fileNodeId }); if (result.statusCode !== StatusCodes.Good) { throw new Error("Error " + result.statusCode.toString()); } return; } public async openCount(): Promise<UInt16> { await this.ensureInitialized(); const nodeToRead: ReadValueIdOptions = { nodeId: this.openCountNodeId!, attributeId: AttributeIds.Value }; const dataValue = await this.session.read(nodeToRead); if (doDebug) { debugLog(" OpenCount ", nodeToRead.nodeId!.toString(), dataValue.toString()); } return dataValue.value.value; } public async size(): Promise<UInt64> { await this.ensureInitialized(); const nodeToRead = { nodeId: this.sizeNodeId, attributeId: AttributeIds.Value }; const dataValue = await this.session.read(nodeToRead); return dataValue.value.value; } // eslint-disable-next-line max-statements protected async extractMethodsIds(): Promise<void> { if (ClientFile.useGlobalMethod) { debugLog("Using GlobalMethodId"); this.openMethodNodeId = resolveNodeId(MethodIds.FileType_Open); this.closeMethodNodeId = resolveNodeId(MethodIds.FileType_Close); this.setPositionNodeId = resolveNodeId(MethodIds.FileType_SetPosition); this.getPositionNodeId = resolveNodeId(MethodIds.FileType_GetPosition); this.writeNodeId = resolveNodeId(MethodIds.FileType_Write); this.readNodeId = resolveNodeId(MethodIds.FileType_Read); const browsePaths: BrowsePath[] = [ makeBrowsePath(this.fileNodeId, "/OpenCount"), makeBrowsePath(this.fileNodeId, "/Size") ]; const results = await this.session.translateBrowsePath(browsePaths); if (results[0].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory OpenCount Property"); } if (results[1].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Size Property"); } this.openCountNodeId = results[0].targets![0].targetId; this.sizeNodeId = results[1].targets![0].targetId; return; } const browsePaths: BrowsePath[] = [ makeBrowsePath(this.fileNodeId, "/Open"), makeBrowsePath(this.fileNodeId, "/Close"), makeBrowsePath(this.fileNodeId, "/SetPosition"), makeBrowsePath(this.fileNodeId, "/GetPosition"), makeBrowsePath(this.fileNodeId, "/Write"), makeBrowsePath(this.fileNodeId, "/Read"), makeBrowsePath(this.fileNodeId, "/OpenCount"), makeBrowsePath(this.fileNodeId, "/Size") ]; const results = await this.session.translateBrowsePath(browsePaths); if (results[0].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Open Method"); } if (results[1].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Close Method"); } if (results[2].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory SetPosition Method"); } if (results[3].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory GetPosition Method"); } if (results[4].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Write Method"); } if (results[5].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Read Method"); } if (results[6].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory OpenCount Variable"); } if (results[7].statusCode !== StatusCodes.Good) { throw new Error("fileType object does not expose mandatory Size Variable"); } if (false && doDebug) { results.map((x: any) => debugLog(x.toString())); } this.openMethodNodeId = results[0].targets![0].targetId; this.closeMethodNodeId = results[1].targets![0].targetId; this.setPositionNodeId = results[2].targets![0].targetId; this.getPositionNodeId = results[3].targets![0].targetId; this.writeNodeId = results[4].targets![0].targetId; this.readNodeId = results[5].targets![0].targetId; this.openCountNodeId = results[6].targets![0].targetId; this.sizeNodeId = results[7].targets![0].targetId; } protected async ensureInitialized(): Promise<void> { if (!this.openMethodNodeId) { await this.extractMethodsIds(); } } } /** * 5.2.10 UserRolePermissions * * The optional UserRolePermissions Attribute specifies the Permissions that apply to a Node for * all Roles granted to current Session. The value of the Attribute is an array of * RolePermissionType Structures (see Table 8). * Clients may determine their effective Permissions by logically ORing the Permissions for each * Role in the array. * The value of this Attribute is derived from the rules used by the Server to map Sessions to * Roles. This mapping may be vendor specific or it may use the standard Role model defined in 4.8. * This Attribute shall not be writeable. * If not specified, the value of DefaultUserRolePermissions Property from the Namespace * Metadata Object associated with the Node is used instead. If the NamespaceMetadata Object * does not define the Property or does not exist, then the Server does not publish any information * about Roles mapped to the current Session. * * * 5.2.11 AccessRestrictions * The optional AccessRestrictions Attribute specifies the AccessRestrictions that apply to a Node. * Its data type is defined in 8.56. If a Server supports AccessRestrictions for a particular * Namespace it adds the DefaultAccessRestrictions Property to the NamespaceMetadata Object * for that Namespace (see Figure 8). If a particular Node in the Namespace needs to override * the default value the Server adds the AccessRestrictions Attribute to the Node. * If a Server implements a vendor specific access restriction model for a Namespace, it does not * add the DefaultAccessRestrictions Property to the NamespaceMetadata Object. * * * DefaultAccessRestrictions * */
the_stack
/// <reference path="../core/UIComponent.ts" /> /// <reference path="../utils/registerProperty.ts" /> namespace eui.sys { /** * @private */ export const enum ComponentKeys { hostComponentKey, skinName, explicitState, enabled, stateIsDirty, skinNameExplicitlySet, explicitTouchChildren, explicitTouchEnabled, skin } } namespace eui { /** * The Component class defines the base class for skinnable components. * The skins used by a Component class are typically child classes of * the Skin class.<p/> * * Associate a skin class with a component class by setting the <code>skinName</code> property of the * component class. * @event egret.Event.COMPLETE Dispatch when <code>skinName</code> property is set the path of external EXML file and the EXML file is resolved. * * @includeExample extension/eui/components/ComponentExample.ts * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * Component 类定义可设置外观的组件的基类。Component 类所使用的外观通常是 Skin 类的子类。<p/> * 通过设置 component 类的 skinName 属性,将 skin 类与 component 类相关联。 * @event egret.Event.COMPLETE 当设置skinName为外部exml文件路径时,加载并完成EXML解析后调度。 * * @includeExample extension/eui/components/ComponentExample.ts * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ export class Component extends egret.DisplayObjectContainer implements UIComponent { /** * Constructor. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 构造函数。 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public constructor() { super(); this.initializeUIValues(); this.$Component = { 0: null, //hostComponentKey, 1: null, //skinName, 2: "", //explicitState, 3: true, //enabled, 4: false, //stateIsDirty, 5: false, //skinNameExplicitlySet, 6: true, //explicitTouchChildren, 7: true, //explicitTouchEnabled 8: null //skin }; //if egret this.$touchEnabled = true; //endif*/ } $Component: Object; /** * A identifier of host component which can determine only one component names. * Usually used for quering a default skin name in theme. * @default null * @see eui.Theme#getSkinName() * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 主机组件标识符。用于唯一确定一个组件的名称。通常用于在主题中查询默认皮肤名。 * * @default null * @see eui.Theme#getSkinName() * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get hostComponentKey(): string { return this.$Component[sys.ComponentKeys.hostComponentKey]; } public set hostComponentKey(value: string) { this.$Component[sys.ComponentKeys.hostComponentKey] = value; } /** * Identifier of skin. Valid values: class definition of skin, * class name of skin, instance of skin, EXML or external EXML file path. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 皮肤标识符。有效值可为:皮肤类定义,皮肤类名,皮肤实例,EXML文件内容,或外部EXML文件路径, * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get skinName(): any { return this.$Component[sys.ComponentKeys.skinName]; } public set skinName(value: any) { let values = this.$Component; values[sys.ComponentKeys.skinNameExplicitlySet] = true; if (values[sys.ComponentKeys.skinName] == value) return; if (value) { values[sys.ComponentKeys.skinName] = value; } else { let theme = egret.getImplementation("eui.Theme"); if (theme) { let skinName = theme.getSkinName(this); if (skinName) { values[sys.ComponentKeys.skinName] = skinName; } } } this.$parseSkinName(); } /** * @private * 解析skinName */ $parseSkinName(): void { let skinName = this.skinName; let skin: any; if (skinName) { if (skinName.prototype) { skin = new skinName(); } else if (typeof (skinName) == "string") { let clazz: any; let text: string = skinName.trim(); if (text.charAt(0) == "<") { clazz = EXML.parse(text); } else { clazz = egret.getDefinitionByName(skinName); if (!clazz && text.toLowerCase().indexOf(".exml") != -1) { EXML.load(skinName, this.onExmlLoaded, this, true); return; } } if (clazz) { skin = new clazz(); } } else { skin = skinName; } } this.setSkin(skin); } /** * @private * @param clazz * @param url */ private onExmlLoaded(clazz: any, url: string): void { if (this.skinName != url) { return; } let skin = new clazz(); this.setSkin(skin) } /** * The instance of the skin class for this component instance. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 皮肤对象实例。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get skin(): Skin { return this.$Component[sys.ComponentKeys.skin]; } /** * Setter for the skin instance. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 设置皮肤实例 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected setSkin(skin: Skin): void { if (skin && !(skin instanceof eui.Skin)) { skin = null; DEBUG && egret.$error(2202); } let values = this.$Component; let oldSkin: Skin = values[sys.ComponentKeys.skin]; if (oldSkin) { let skinParts: string[] = oldSkin.skinParts; let length = skinParts.length; for (let i = 0; i < length; i++) { let partName = skinParts[i]; if (this[partName]) { this.setSkinPart(partName, null); } } let children = oldSkin.$elementsContent; if (children) { length = children.length; for (let i = 0; i < length; i++) { let child = children[i]; if (child.$parent == this) { this.removeChild(child); } } } oldSkin.hostComponent = null; } values[sys.ComponentKeys.skin] = skin; if (skin) { let skinParts: string[] = skin.skinParts; let length = skinParts.length; for (let i = 0; i < length; i++) { let partName = skinParts[i]; let instance = skin[partName]; if (instance) { this.setSkinPart(partName, instance); } } let children = skin.$elementsContent; if (children) { for (let i = children.length - 1; i >= 0; i--) { this.addChildAt(children[i], 0); } } skin.hostComponent = this; } this.invalidateSize(); this.invalidateDisplayList(); this.dispatchEventWith(egret.Event.COMPLETE); } /** * Find the skin parts in the skin class and assign them to the properties of the component. * You do not call this method directly. This method will be invoked automatically when using a EXML as skin. * The ID for a tag in an EXML will be passed in as <code>partName</code>, and the instance of the tag will be * passed in as <code>instance</code>. * @param partName name of a skin part * @param instance instance of a skin part * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 关联一个对象到逻辑组件的指定皮肤部件上。通常您不需要手动调用此方法,当使用EXML文件作为组件皮肤,此方法将会被自动调用。 * 在运行时,EXML文件内声明的id名称将作为此方法的partName参数,而id所对应的节点对象,将作为此方法的instance参数被依次传入。 * @param partName 皮肤部件名称 * @param instance 皮肤部件实例 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public setSkinPart(partName: string, instance: any): void { let oldInstance = this[partName]; if (oldInstance) { this.partRemoved(partName, oldInstance); } this[partName] = instance; if (instance) { this.partAdded(partName, instance); } } /** * Called when a skin part is added. * You do not call this method directly. * EUI calls it automatically when it calls the <code>setSkinPart()</code> method.<p/> * * Override this function to attach behavior to the part, such as add event listener or * assign property values cached. * @param partName name of a skin part to add. * @param instance instance of a skin part to add. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 添加皮肤部件时调用。 * 您无需直接调用此方法。 * EUI 会在调用 setSkinPart()方法时自动调用此方法。<p/> * * 子类覆盖此方法,以在皮肤部件第一次附加时对其执行一些初始化操作,例如添加事件监听,赋值缓存的属性值等。 * @param partName 要附加的皮肤部件名称。 * @param instance 要附加的皮肤部件实例。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected partAdded(partName: string, instance: any): void { } /** * Called when an instance of a skin part is being removed. * You do not call this method directly. * EUI calls it automatically when it calls the <code>setSkinPart()</code> method.<p/> * * Override this function to clean behavior of the part, such as remove event listener or * disconnect the cache reference * @param partName name of a skin part to remove. * @param instance instance of a skin part to remove. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 正删除外观部件的实例时调用。 * 您无需直接调用此方法。 * EUI 会在调用 setSkinPart()方法时自动调用此方法。<p/> * * 子类覆盖此方法,以在皮肤部件从逻辑组件卸载时对其执行一些清理操作,例如移除事件监听,断开缓存的引用等。 * @param partName 要卸载的皮肤部件名称 * @param instance 要卸载的皮肤部件实例 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected partRemoved(partName: string, instance: any): void { } /** * @private * * @param value */ $setTouchChildren(value: boolean): boolean { value = !!value; let values = this.$Component; values[sys.ComponentKeys.explicitTouchChildren] = value; if (values[sys.ComponentKeys.enabled]) { values[sys.ComponentKeys.explicitTouchChildren] = value; return super.$setTouchChildren(value); } else { return true; } } /** * @private * * @param value */ $setTouchEnabled(value: boolean): void { value = !!value; let values = this.$Component; values[sys.ComponentKeys.explicitTouchEnabled] = value; if (values[sys.ComponentKeys.enabled]) { super.$setTouchEnabled(value); } } /** * Whether the component can accept user interaction. * After setting the <code>enabled</code> property to <code>false</code>, components will disabled touch event * (set <code>touchEnabled</code> and <code>touchChildren</code> to false) and set state of skin to "disabled". * * @default true * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 组件是否可以接受用户交互。 * 将 enabled 属性设置为 false 后, * 组件会自动禁用触摸事件(将 touchEnabled 和 touchChildren 同时设置为 false), * 部分组件可能还会将皮肤的视图状态设置为"disabled",使其所有子项的颜色变暗。 * * @default true * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get enabled(): boolean { return this.$Component[sys.ComponentKeys.enabled]; } public set enabled(value: boolean) { value = !!value; this.$setEnabled(value); } /** * @private * * @param value */ $setEnabled(value: boolean): boolean { let values = this.$Component; if (value === values[sys.ComponentKeys.enabled]) { return false; } values[sys.ComponentKeys.enabled] = value; if (value) { this.$touchEnabled = values[sys.ComponentKeys.explicitTouchEnabled]; this.$touchChildren = values[sys.ComponentKeys.explicitTouchChildren]; } else { this.$touchEnabled = false; this.$touchChildren = false; } this.invalidateState(); return true; } //========================皮肤视图状态=====================start======================= /** * The current view state of the component. When you use this property to set a component's state, * EUI will explicit update state of skin and ignore the return of <code>getCurrentState()</code>. * * Set to <code>""</code> or <code>null</code> to reset the component back to its base state. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 组件的当前视图状态。显式设置此属性, * 将采用显式设置的值去更新皮肤状态,而忽略组件内部 getCurrentState() 方法返回的值。 * * 将其设置为 "" 或 null 可将取消组件外部显式设置的视图状态名称,从而采用内部 getCurrentState() 方法返回的状态。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get currentState(): string { let values = this.$Component; return values[sys.ComponentKeys.explicitState] ? values[sys.ComponentKeys.explicitState] : this.getCurrentState(); } public set currentState(value: string) { let values = this.$Component; if (value == values[sys.ComponentKeys.explicitState]) { return; } values[sys.ComponentKeys.explicitState] = value; this.invalidateState(); } /** * Marks the component so that the new state of the skin is set during a later screen update. * A subclass of SkinnableComponent must override <code>getCurrentState()</code> to return a value. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 标记组件当前的视图状态失效,调用此方法后,子类应该覆盖 <code>getCurrentState()</code> 方法来返回当前的视图状态名称。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public invalidateState(): void { let values = this.$Component; if (values[sys.ComponentKeys.stateIsDirty]) return; values[sys.ComponentKeys.stateIsDirty] = true; this.invalidateProperties(); } /** * Returns the name of the state to be applied to the skin.<p/> * A subclass of SkinnableComponent must override this method to return a value. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 返回组件当前的皮肤状态名称,子类覆盖此方法定义各种状态名 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected getCurrentState(): string { return ""; } //========================皮肤视图状态===================end======================== //=======================UIComponent接口实现=========================== /** * @private * UIComponentImpl 定义的所有变量请不要添加任何初始值,必须统一在此处初始化。 */ private initializeUIValues: () => void; /** * Create child objects of the component. This is an advanced method that you might override * when creating a subclass of Component. This method will be called once it be added to stage. * You must invoke <code>super.createChildren()</code> to complete initialization of the parent class * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 子类覆盖此方法可以执行一些初始化子项操作。此方法仅在组件第一次添加到舞台时回调一次。 * 请务必调用super.createChildren()以完成父类组件的初始化 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected createChildren(): void { let values = this.$Component; if (!values[sys.ComponentKeys.skinName]) { let theme = egret.getImplementation("eui.Theme"); if (theme) { let skinName = theme.getSkinName(this); if (skinName) { values[sys.ComponentKeys.skinName] = skinName; this.$parseSkinName(); } } } } /** * Performs any final processing after child objects are created. * This is an advanced method that you might override * when creating a subclass of Component. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 创建子对象后执行任何最终处理。此方法在创建 Component 的子类时覆盖。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected childrenCreated(): void { } /** * Processes the properties set on the component. * You can override this method when creating a subclass of Component. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 提交属性,子类在调用完invalidateProperties()方法后,应覆盖此方法以应用属性 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected commitProperties(): void { sys.UIComponentImpl.prototype["commitProperties"].call(this); let values = this.$Component; if (values[sys.ComponentKeys.stateIsDirty]) { values[sys.ComponentKeys.stateIsDirty] = false; if (values[sys.ComponentKeys.skin]) { values[sys.ComponentKeys.skin].currentState = this.currentState; } } } /** * Calculates the default size. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 测量组件尺寸 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected measure(): void { sys.measure(this); let skin = this.$Component[sys.ComponentKeys.skin]; if (!skin) { return; } let values = this.$UIComponent; if (!isNaN(skin.width)) { values[sys.UIKeys.measuredWidth] = skin.width; } else { if (values[sys.UIKeys.measuredWidth] < skin.minWidth) { values[sys.UIKeys.measuredWidth] = skin.minWidth; } if (values[sys.UIKeys.measuredWidth] > skin.maxWidth) { values[sys.UIKeys.measuredWidth] = skin.maxWidth; } } if (!isNaN(skin.height)) { values[sys.UIKeys.measuredHeight] = skin.height; } else { if (values[sys.UIKeys.measuredHeight] < skin.minHeight) { values[sys.UIKeys.measuredHeight] = skin.minHeight; } if (values[sys.UIKeys.measuredHeight] > skin.maxHeight) { values[sys.UIKeys.measuredHeight] = skin.maxHeight; } } } /** * Draws the object and/or sizes and positions its children. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 更新显示列表 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected updateDisplayList(unscaledWidth: number, unscaledHeight: number): void { sys.updateDisplayList(this, unscaledWidth, unscaledHeight); } /** * Method to invalidate parent size and display list if * this object affects its layout (includeInLayout is true). * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 此对象影响其布局时(includeInLayout 为 true),使父代大小和显示列表失效的方法。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected invalidateParentLayout(): void { } /** * @private */ $UIComponent: Object; /** * @private */ $includeInLayout: boolean; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public includeInLayout: boolean; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public left: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public right: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public top: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public bottom: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public horizontalCenter: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public verticalCenter: any; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public percentWidth: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public percentHeight: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public explicitWidth: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public explicitHeight: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public minWidth: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public maxWidth: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public minHeight: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public maxHeight: number; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public setMeasuredSize(width: number, height: number): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public invalidateProperties(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public validateProperties(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public invalidateSize(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public validateSize(recursive?: boolean): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public invalidateDisplayList(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public validateDisplayList(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public validateNow(): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public setLayoutBoundsSize(layoutWidth: number, layoutHeight: number): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public setLayoutBoundsPosition(x: number, y: number): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public getLayoutBounds(bounds: egret.Rectangle): void { } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public getPreferredBounds(bounds: egret.Rectangle): void { } public unwatchAll() { if (this.skin && this.skin.unwatchAll) { this.skin.unwatchAll(); } } } registerProperty(Component, "skinName", "Class"); sys.implementUIComponent(Component, egret.DisplayObjectContainer, true); }
the_stack
/// <reference types="amap-js-api" /> declare namespace AMap { namespace PlaceSearch { interface EventMap { complete: Event<'complete', SearchResult>; error: Event<'error', { info: string }>; selectChanged: Event<'selectChanged', { selected: SelectChangeEventData | EventMap['markerClick'] | EventMap['listElementClick']; lastSelected: SelectChangeEventData | EventMap['markerClick'] | EventMap['listElementClick'] | null; }>; listElementClick: SelectChangeEvent<'listElementClick', MouseEvent>; markerClick: SelectChangeEvent<'markerClick', Marker.EventMap['click']>; // internal renderComplete: Event<'renderComplete', { result: SelectChangeEventData[]; markers: Marker[]; listElements: HTMLElement[]; }>; infoWindowClick: Event<'infoWindowClick', SelectChangeEventData & { event: MouseEvent; infoWindow: InfoWindow; infoWindowContentDom: HTMLDivElement; }>; willClear: Event<'willClear', { id: string; index: number; data: Poi[]; }>; markerDestoryed: Event<'markerDestoryed', SelectChangeEventData>; // typo in source code listElementDetroyed: Event<'listElementDetroyed', SelectChangeEventData>; // typo too } interface SelectChangeEventData { /** * 当前选中的POI的ID */ id: string; /** * 索引 */ index: number; /** * 当前选中的POI对应的在地图中的Marker对象 */ marker: Marker; /** * 当前选中的POI在结果面板中对应的列表项 */ listElement: HTMLLIElement; /** * 当前选中的POI的信息 */ data: Poi[]; } type SelectChangeEvent<N extends string, E> = Event<N, SelectChangeEventData & { event: E; }>; interface PoiPhoto { /** * 图片名称 */ title: string; /** * 图片url */ url: string; } interface PoiBase { /** * 全局唯一ID */ id: string; /** * 名称 */ name: string; /** * 兴趣点类型 */ type: string; /** * 兴趣点经纬度 */ location: LngLat | null; /** * 地址 */ address: string; /** * 离中心点距离 */ distance: number; /** * 电话 */ tel: string; shopinfo: string; children?: any[] | undefined; // TODO Array<{location: LngLat | null}> } interface Groupbuy { /** * 团购标题 */ title: string; /** * 团购分类代码 */ type_code: string; /** * 团购分类 */ type: string; /** * 团购详情 */ detail: string; /** * 团购开始时间 */ stime: string; /** * 团购结束时间 */ etime: string; /** * 团购总量 */ count: number; /** * 已卖出数量 */ sold_num: number; /** * 原价 */ original_price: number; /** * 折扣价 */ groupbuy_price: number; /** * 折扣 */ discount: number; /** * 取票地址 */ ticket_address: string; /** * 取票电话 */ ticket_tel: string; /** * 图片信息 */ photos: PoiPhoto[]; /** * 来源url */ url: string; /** * 来源标识 */ provider: string; } interface Discount { /** * 优惠标题 */ title: string; /** * 优惠详情 */ detail: string; /** * 开始时间 */ start_time: string; /** * 结束时间 */ end_time: string; /** * 已卖出数量 */ sold_num: number; /** * 图片信息列表 */ photos: PoiPhoto[]; /** * 来源url */ url: string; /** * 来源标识 */ provider: string; } interface Cinema { /** * 简介 */ intro: string; /** * 综合评分 */ rating: string; /** * 信息来源 */ deep_src: string; /** * 停车场设施 */ parking: string; /** * 规范格式的营业时间 */ opentime_GDF: string; /** * 非规范格式的营业时间 */ opentime: string; /** * 图片信息列表 */ photos: PoiPhoto[]; } interface Dining { /** * 菜系 */ cuisines: string; /** * 标签 */ tag: string; /** * 简介 */ intro: string; /** * 综合评分 */ rating: string; /** * 单数据源的评分 */ cp_rating: string; /** * 信息来源 */ deep_src: string; /** * 口味评分 */ taste_rating: string; /** * 环境评分 */ environment_rating: string; /** * 服务评分 */ service_rating: string; /** * 人均消费 */ cost: string; /** * 特色菜 */ recommend: string; /** * 氛围 */ atmosphere: string; /** * 订餐wap链接 */ ordering_wap_url: string; /** * 订餐web链接 */ ordering_web_url: string; /** * 订餐APP URL */ ordering_app_url: string; /** * 规范格式的营业时间 */ opentime_GDF: string; /** * 非规范格式的营业时间 */ opentime: string; /** * 餐厅特色 */ addition: string; /** * 图片信息列表 */ photos: PoiPhoto[]; } interface Scenic { /** * 简介 */ intro: string; /** * 综合评分 */ rating: string; /** * 信息来源 */ deep_src: string; /** * 景区国标级别 */ level: string; /** * 门票价格 */ price: string; /** * 适合游玩的季节 */ season: string; /** * 推荐景点 */ recommend: string; /** * 景区主题 */ theme: string; /** * wap购票链接 */ ordering_wap_url: string; /** * web购票链接 */ ordering_web_url: string; /** * 规范格式的营业时间 */ opentime_GDF: string; /** * 非规范格式的营业时间 */ opentime: string; /** * 图片信息列表 */ photos: PoiPhoto[]; } interface Hotel { /** * 综合评分 */ rating: string; /** * 星级 */ star: string; /** * 简介 */ intro: string; /** * 最低房价 */ lowest_price: string; /** * 设施评分 */ faci_rating: string; /** * 卫生评分 */ health_rating: string; /** * 环境评分 */ environment_rating: string; /** * 服务评分 */ service_rating: string; /** * 交通提示 */ traffic: string; /** * 特色服务 */ addition: string; /** * 信息来源 */ deep_src: string; /** * 图片信息列表 */ photos: PoiPhoto[]; } type PoiExt = PoiBase & { /** * 网址 */ website: string; /** * 所在省份编码 */ pcode: string; /** * 所在城市编码 */ citycode: string; /** * 所在区域编码 */ adcode: string; /** * 邮编 */ postcode: string; /** * 所在省份 */ pname: string; /** * 所在城市名称 */ cityname: string; /** * 所在行政区名称 */ adname: string; /** * 电子邮箱 */ email: string; /** * 照片 */ photos: PoiPhoto[]; /** * 入口经纬度 */ entr_location: LngLat | null; /** * 出口经纬度 */ exit_location: LngLat | null; /** * @deprecated 是否有团购信息 */ groupbuy: boolean; /** * @deprecated 是否有优惠信息 */ discount: boolean; } & ({ indoor_map: true; indoor_data: { cpid: string; floor: string; truefloor: string; }; } | { indoor_map: false; }) & { /** * @deprecated 团购信息 */ groupbuys?: Groupbuy[] | undefined; /** * @deprecated 优惠信息 */ discounts?: Discount[] | undefined; } & ({ deep_type: 'CINEMA'; /** * @deprecated 影院类深度信息 */ cinema: Cinema; } | { deep_type: 'DINING'; /** * @deprecated 餐饮类深度信息 */ dining: Dining; } | { deep_type: 'SCENIC'; /** * @deprecated 景点类深度信息 */ scenic: Scenic; } | { deep_type: 'HOTEL'; /** * @deprecated 酒店类深度信息 */ hotel: Hotel; }); interface Options { /** * 兴趣点城市 */ city?: string | undefined; /** * 是否强制限制在设置的城市内搜索 */ citylimit?: boolean | undefined; /** * 是否按照层级展示子POI数据 * children=1,展示子节点POI数据,children=0,不展示子节点数据 */ children?: number | undefined; /** * 兴趣点类别,多个类别用“|”分割 */ type?: string | undefined; /** * 检索语言类型 */ lang?: Lang | undefined; /** * 单页显示结果条数 */ pageSize?: number | undefined; /** * 页码 */ pageIndex?: number | undefined; /** * 是否返回详细信息 * base返回基本地址信息;all返回基本+详细信息 */ extensions?: 'base' | 'all' | undefined; /** * Map对象 */ map?: Map | undefined; /** * 结果列表的HTML容器id或容器元素 */ panel?: string | HTMLElement | undefined; /** * 是否在地图上显示周边搜索的圆或者范围搜索的多边形 */ showCover?: boolean | undefined; /** * 绘制的UI风格 */ renderStyle?: 'newpc' | 'default' | undefined; /** * 是否自动调整地图视野使绘制的Marker点都处于视口的可见范围 */ autoFitView?: boolean | undefined; // internal renderEngine?: string | undefined; rankBy?: string | undefined; } interface PoiList { /** * Poi列表 */ pois: Poi[]; // PlaceSearchPoiBase[] | PlaceSearchPoiExt[]; /** * 页码 */ pageIndex: number; /** * 单页结果数 */ pageSize: number; /** * 查询结果总数 */ count: number; } interface CityInfo { /** * 建议城市名称 */ name: string; /** * 城市编码 */ citycode: string; /** * 行政区编码 */ adcode: string; /** * 该城市的建议结果数目 */ count: number; } interface SearchResult { /** * 成功状态说明 */ info: string; /** * 兴趣点列表 */ poiList: PoiList; /** * 建议关键字列表 */ keywordList?: string[] | undefined; /** * 城市建议列表 */ cityList?: CityInfo[] | undefined; } type Poi = PoiBase | PoiExt; type SearchStatus = 'complete' | 'error' | 'no_data'; } class PlaceSearch extends EventEmitter { /** * 地点搜索服务 * @param options 选项 */ constructor(options?: PlaceSearch.Options); /** * 根据关键字搜索 * @param keyword 根据关键字搜索 * @param callback 回调 */ search( keyword: string, callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void ): void; /** * 周边查询 * @param keyword 关键字 * @param center 搜索中心 * @param radius 搜索半径 * @param callback 回调 */ searchNearBy( keyword: string, center: LocationValue, radius: number, callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void ): void; /** * 根据范围和关键词进行范围查询 * @param keyword 关键字 * @param bounds 搜索范围 * @param callback 回调 */ searchInBounds( keyword: string, bounds: Bounds | Polygon, callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void ): void; /** * 根据POIID 查询POI 详细信息 * @param POIID POIID * @param callback 搜索回调 */ getDetails( POIID: string, callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void ): void; /** * 设置查询类别 * @param type 查询类别 */ setType(type?: string): void; /** * 设置是否强制限制城市 * @param limit 是否强制限制城市 */ setCityLimit(limit?: boolean): void; /** * 设置查询结果特定页数 * @param pageIndex 页码 */ setPageIndex(pageIndex?: number): void; /** * 设置查询单页结果数 * @param pageSize 结果数 */ setPageSize(pageSize?: number): void; /** * 设置查询城市 * @param city 城市 */ setCity(city?: string): void; /** * 设置检索语言类型 * @param lang 语言类型 */ setLang(lang?: Lang): void; /** * 获取检索语言类型 */ getLang(): Lang | undefined; /** * 清除搜索结果 */ clear(): void; /** * 唤起高德地图客户端marker页 * @param obj 唤起参数 */ poiOnAMAP(obj: { location?: LocationValue | undefined; id: string; name?: string | undefined; }): void; /** * 唤起高德地图客户端POI详情页 * @param obj 唤起参数 */ detailOnAMAP(obj: { location?: LocationValue | undefined; id: string; name?: string | undefined; }): void; // internal open(): void; close(): void; } }
the_stack
import { AST_NODE_TYPES, TSESLint, TSESTree, } from '@typescript-eslint/experimental-utils'; import * as util from '../util'; /** * This rule is a replica of padding-line-between-statements. * * Ideally we would want to extend the rule support typescript specific support. * But since not all the state is exposed by the eslint and eslint has frozen stylistic rules, * (see - https://eslint.org/blog/2020/05/changes-to-rules-policies for details.) * we are forced to re-implement the rule here. * * We have tried to keep the implementation as close as possible to the eslint implementation, to make * patching easier for future contributors. * * Reference rule - https://github.com/eslint/eslint/blob/main/lib/rules/padding-line-between-statements.js */ type NodeTest = ( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ) => boolean; interface NodeTestObject { test: NodeTest; } interface PaddingOption { blankLine: keyof typeof PaddingTypes; prev: string | string[]; next: string | string[]; } type MessageIds = 'expectedBlankLine' | 'unexpectedBlankLine'; type Options = PaddingOption[]; const LT = `[${Array.from( new Set(['\r\n', '\r', '\n', '\u2028', '\u2029']), ).join('')}]`; const PADDING_LINE_SEQUENCE = new RegExp( String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`, 'u', ); /** * Creates tester which check if a node starts with specific keyword with the * appropriate AST_NODE_TYPES. * @param keyword The keyword to test. * @returns the created tester. * @private */ function newKeywordTester( type: AST_NODE_TYPES | AST_NODE_TYPES[], keyword: string, ): NodeTestObject { return { test(node, sourceCode): boolean { const isSameKeyword = sourceCode.getFirstToken(node)?.value === keyword; const isSameType = Array.isArray(type) ? type.some(val => val === node.type) : type === node.type; return isSameKeyword && isSameType; }, }; } /** * Creates tester which check if a node starts with specific keyword and spans a single line. * @param keyword The keyword to test. * @returns the created tester. * @private */ function newSinglelineKeywordTester(keyword: string): NodeTestObject { return { test(node, sourceCode): boolean { return ( node.loc.start.line === node.loc.end.line && sourceCode.getFirstToken(node)!.value === keyword ); }, }; } /** * Creates tester which check if a node starts with specific keyword and spans multiple lines. * @param keyword The keyword to test. * @returns the created tester. * @private */ function newMultilineKeywordTester(keyword: string): NodeTestObject { return { test(node, sourceCode): boolean { return ( node.loc.start.line !== node.loc.end.line && sourceCode.getFirstToken(node)!.value === keyword ); }, }; } /** * Creates tester which check if a node is specific type. * @param type The node type to test. * @returns the created tester. * @private */ function newNodeTypeTester(type: AST_NODE_TYPES): NodeTestObject { return { test: (node): boolean => node.type === type, }; } /** * Skips a chain expression node * @param node The node to test * @returnsA non-chain expression * @private */ function skipChainExpression(node: TSESTree.Node): TSESTree.Node { return node && node.type === AST_NODE_TYPES.ChainExpression ? node.expression : node; } /** * Checks the given node is an expression statement of IIFE. * @param node The node to check. * @returns `true` if the node is an expression statement of IIFE. * @private */ function isIIFEStatement(node: TSESTree.Node): boolean { if (node.type === AST_NODE_TYPES.ExpressionStatement) { let expression = skipChainExpression(node.expression); if (expression.type === AST_NODE_TYPES.UnaryExpression) { expression = skipChainExpression(expression.argument); } if (expression.type === AST_NODE_TYPES.CallExpression) { let node: TSESTree.Node = expression.callee; while (node.type === AST_NODE_TYPES.SequenceExpression) { node = node.expressions[node.expressions.length - 1]; } return util.isFunction(node); } } return false; } /** * Checks the given node is a CommonJS require statement * @param node The node to check. * @returns `true` if the node is a CommonJS require statement. * @private */ function isCJSRequire(node: TSESTree.Node): boolean { if (node.type === AST_NODE_TYPES.VariableDeclaration) { const declaration = node.declarations[0]; if (declaration?.init) { let call = declaration?.init; while (call.type === AST_NODE_TYPES.MemberExpression) { call = call.object; } if ( call.type === AST_NODE_TYPES.CallExpression && call.callee.type === AST_NODE_TYPES.Identifier ) { return call.callee.name === 'require'; } } } return false; } /** * Checks whether the given node is a block-like statement. * This checks the last token of the node is the closing brace of a block. * @param sourceCode The source code to get tokens. * @param node The node to check. * @returns `true` if the node is a block-like statement. * @private */ function isBlockLikeStatement( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ): boolean { // do-while with a block is a block-like statement. if ( node.type === AST_NODE_TYPES.DoWhileStatement && node.body.type === AST_NODE_TYPES.BlockStatement ) { return true; } /** * IIFE is a block-like statement specially from * JSCS#disallowPaddingNewLinesAfterBlocks. */ if (isIIFEStatement(node)) { return true; } // Checks the last token is a closing brace of blocks. const lastToken = sourceCode.getLastToken(node, util.isNotSemicolonToken); const belongingNode = lastToken && util.isClosingBraceToken(lastToken) ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) : null; return ( !!belongingNode && (belongingNode.type === AST_NODE_TYPES.BlockStatement || belongingNode.type === AST_NODE_TYPES.SwitchStatement) ); } /** * Check whether the given node is a directive or not. * @param node The node to check. * @param sourceCode The source code object to get tokens. * @returns `true` if the node is a directive. */ function isDirective( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ): boolean { return ( node.type === AST_NODE_TYPES.ExpressionStatement && (node.parent?.type === AST_NODE_TYPES.Program || (node.parent?.type === AST_NODE_TYPES.BlockStatement && util.isFunction(node.parent.parent))) && node.expression.type === AST_NODE_TYPES.Literal && typeof node.expression.value === 'string' && !util.isParenthesized(node.expression, sourceCode) ); } /** * Check whether the given node is a part of directive prologue or not. * @param node The node to check. * @param sourceCode The source code object to get tokens. * @returns `true` if the node is a part of directive prologue. */ function isDirectivePrologue( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ): boolean { if ( isDirective(node, sourceCode) && node.parent && 'body' in node.parent && Array.isArray(node.parent.body) ) { for (const sibling of node.parent.body) { if (sibling === node) { break; } if (!isDirective(sibling, sourceCode)) { return false; } } return true; } return false; } /** * Checks the given node is a CommonJS export statement * @param node The node to check. * @returns `true` if the node is a CommonJS export statement. * @private */ function isCJSExport(node: TSESTree.Node): boolean { if (node.type === AST_NODE_TYPES.ExpressionStatement) { const expression = node.expression; if (expression.type === AST_NODE_TYPES.AssignmentExpression) { let left = expression.left; if (left.type === AST_NODE_TYPES.MemberExpression) { while (left.object.type === AST_NODE_TYPES.MemberExpression) { left = left.object; } return ( left.object.type === AST_NODE_TYPES.Identifier && (left.object.name === 'exports' || (left.object.name === 'module' && left.property.type === AST_NODE_TYPES.Identifier && left.property.name === 'exports')) ); } } } return false; } /** * Check whether the given node is an expression * @param node The node to check. * @param sourceCode The source code object to get tokens. * @returns `true` if the node is an expression */ function isExpression( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ): boolean { return ( node.type === AST_NODE_TYPES.ExpressionStatement && !isDirectivePrologue(node, sourceCode) ); } /** * Gets the actual last token. * * If a semicolon is semicolon-less style's semicolon, this ignores it. * For example: * * foo() * ;[1, 2, 3].forEach(bar) * @param sourceCode The source code to get tokens. * @param node The node to get. * @returns The actual last token. * @private */ function getActualLastToken( node: TSESTree.Node, sourceCode: TSESLint.SourceCode, ): TSESTree.Token | null { const semiToken = sourceCode.getLastToken(node)!; const prevToken = sourceCode.getTokenBefore(semiToken); const nextToken = sourceCode.getTokenAfter(semiToken); const isSemicolonLessStyle = prevToken && nextToken && prevToken.range[0] >= node.range[0] && util.isSemicolonToken(semiToken) && semiToken.loc.start.line !== prevToken.loc.end.line && semiToken.loc.end.line === nextToken.loc.start.line; return isSemicolonLessStyle ? prevToken : semiToken; } /** * This returns the concatenation of the first 2 captured strings. * @param _ Unused. Whole matched string. * @param trailingSpaces The trailing spaces of the first line. * @param indentSpaces The indentation spaces of the last line. * @returns The concatenation of trailingSpaces and indentSpaces. * @private */ function replacerToRemovePaddingLines( _: string, trailingSpaces: string, indentSpaces: string, ): string { return trailingSpaces + indentSpaces; } /** * Check and report statements for `any` configuration. * It does nothing. * * @private */ function verifyForAny(): void { // Empty } /** * Check and report statements for `never` configuration. * This autofix removes blank lines between the given 2 statements. * However, if comments exist between 2 blank lines, it does not remove those * blank lines automatically. * @param context The rule context to report. * @param _ Unused. The previous node to check. * @param nextNode The next node to check. * @param paddingLines The array of token pairs that blank * lines exist between the pair. * * @private */ function verifyForNever( context: TSESLint.RuleContext<MessageIds, Options>, _: TSESTree.Node, nextNode: TSESTree.Node, paddingLines: [TSESTree.Token, TSESTree.Token][], ): void { if (paddingLines.length === 0) { return; } context.report({ node: nextNode, messageId: 'unexpectedBlankLine', fix(fixer) { if (paddingLines.length >= 2) { return null; } const prevToken = paddingLines[0][0]; const nextToken = paddingLines[0][1]; const start = prevToken.range[1]; const end = nextToken.range[0]; const text = context .getSourceCode() .text.slice(start, end) .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); return fixer.replaceTextRange([start, end], text); }, }); } /** * Check and report statements for `always` configuration. * This autofix inserts a blank line between the given 2 statements. * If the `prevNode` has trailing comments, it inserts a blank line after the * trailing comments. * @param context The rule context to report. * @param prevNode The previous node to check. * @param nextNode The next node to check. * @param paddingLines The array of token pairs that blank * lines exist between the pair. * * @private */ function verifyForAlways( context: TSESLint.RuleContext<MessageIds, Options>, prevNode: TSESTree.Node, nextNode: TSESTree.Node, paddingLines: [TSESTree.Token, TSESTree.Token][], ): void { if (paddingLines.length > 0) { return; } context.report({ node: nextNode, messageId: 'expectedBlankLine', fix(fixer) { const sourceCode = context.getSourceCode(); let prevToken = getActualLastToken( prevNode, sourceCode, ) as TSESTree.Token; const nextToken = (sourceCode.getFirstTokenBetween(prevToken, nextNode, { includeComments: true, /** * Skip the trailing comments of the previous node. * This inserts a blank line after the last trailing comment. * * For example: * * foo(); // trailing comment. * // comment. * bar(); * * Get fixed to: * * foo(); // trailing comment. * * // comment. * bar(); * @param token The token to check. * @returns `true` if the token is not a trailing comment. * @private */ filter(token) { if (util.isTokenOnSameLine(prevToken, token)) { prevToken = token; return false; } return true; }, }) as TSESTree.Token) || nextNode; const insertText = util.isTokenOnSameLine(prevToken, nextToken) ? '\n\n' : '\n'; return fixer.insertTextAfter(prevToken, insertText); }, }); } /** * Types of blank lines. * `any`, `never`, and `always` are defined. * Those have `verify` method to check and report statements. * @private */ const PaddingTypes = { any: { verify: verifyForAny }, never: { verify: verifyForNever }, always: { verify: verifyForAlways }, }; /** * Types of statements. * Those have `test` method to check it matches to the given statement. * @private */ const StatementTypes: Record<string, NodeTestObject> = { '*': { test: (): boolean => true }, 'block-like': { test: isBlockLikeStatement }, exports: { test: isCJSExport }, require: { test: isCJSRequire }, directive: { test: isDirectivePrologue }, expression: { test: isExpression }, iife: { test: isIIFEStatement }, 'multiline-block-like': { test: (node, sourceCode) => node.loc.start.line !== node.loc.end.line && isBlockLikeStatement(node, sourceCode), }, 'multiline-expression': { test: (node, sourceCode) => node.loc.start.line !== node.loc.end.line && node.type === AST_NODE_TYPES.ExpressionStatement && !isDirectivePrologue(node, sourceCode), }, 'multiline-const': newMultilineKeywordTester('const'), 'multiline-let': newMultilineKeywordTester('let'), 'multiline-var': newMultilineKeywordTester('var'), 'singleline-const': newSinglelineKeywordTester('const'), 'singleline-let': newSinglelineKeywordTester('let'), 'singleline-var': newSinglelineKeywordTester('var'), block: newNodeTypeTester(AST_NODE_TYPES.BlockStatement), empty: newNodeTypeTester(AST_NODE_TYPES.EmptyStatement), function: newNodeTypeTester(AST_NODE_TYPES.FunctionDeclaration), break: newKeywordTester(AST_NODE_TYPES.BreakStatement, 'break'), case: newKeywordTester(AST_NODE_TYPES.SwitchCase, 'case'), class: newKeywordTester(AST_NODE_TYPES.ClassDeclaration, 'class'), const: newKeywordTester(AST_NODE_TYPES.VariableDeclaration, 'const'), continue: newKeywordTester(AST_NODE_TYPES.ContinueStatement, 'continue'), debugger: newKeywordTester(AST_NODE_TYPES.DebuggerStatement, 'debugger'), default: newKeywordTester( [AST_NODE_TYPES.SwitchCase, AST_NODE_TYPES.ExportDefaultDeclaration], 'default', ), do: newKeywordTester(AST_NODE_TYPES.DoWhileStatement, 'do'), export: newKeywordTester( [ AST_NODE_TYPES.ExportDefaultDeclaration, AST_NODE_TYPES.ExportNamedDeclaration, ], 'export', ), for: newKeywordTester( [ AST_NODE_TYPES.ForStatement, AST_NODE_TYPES.ForInStatement, AST_NODE_TYPES.ForOfStatement, ], 'for', ), if: newKeywordTester(AST_NODE_TYPES.IfStatement, 'if'), import: newKeywordTester(AST_NODE_TYPES.ImportDeclaration, 'import'), let: newKeywordTester(AST_NODE_TYPES.VariableDeclaration, 'let'), return: newKeywordTester(AST_NODE_TYPES.ReturnStatement, 'return'), switch: newKeywordTester(AST_NODE_TYPES.SwitchStatement, 'switch'), throw: newKeywordTester(AST_NODE_TYPES.ThrowStatement, 'throw'), try: newKeywordTester(AST_NODE_TYPES.TryStatement, 'try'), var: newKeywordTester(AST_NODE_TYPES.VariableDeclaration, 'var'), while: newKeywordTester( [AST_NODE_TYPES.WhileStatement, AST_NODE_TYPES.DoWhileStatement], 'while', ), with: newKeywordTester(AST_NODE_TYPES.WithStatement, 'with'), // Additional Typescript constructs interface: newKeywordTester( AST_NODE_TYPES.TSInterfaceDeclaration, 'interface', ), type: newKeywordTester(AST_NODE_TYPES.TSTypeAliasDeclaration, 'type'), }; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ export default util.createRule<Options, MessageIds>({ name: 'padding-line-between-statements', meta: { type: 'layout', docs: { description: 'require or disallow padding lines between statements', recommended: false, extendsBaseRule: true, }, fixable: 'whitespace', hasSuggestions: true, schema: { definitions: { paddingType: { enum: Object.keys(PaddingTypes), }, statementType: { anyOf: [ { enum: Object.keys(StatementTypes) }, { type: 'array', items: { enum: Object.keys(StatementTypes) }, minItems: 1, uniqueItems: true, additionalItems: false, }, ], }, }, type: 'array', items: { type: 'object', properties: { blankLine: { $ref: '#/definitions/paddingType' }, prev: { $ref: '#/definitions/statementType' }, next: { $ref: '#/definitions/statementType' }, }, additionalProperties: false, required: ['blankLine', 'prev', 'next'], }, additionalItems: false, }, messages: { unexpectedBlankLine: 'Unexpected blank line before this statement.', expectedBlankLine: 'Expected blank line before this statement.', }, }, defaultOptions: [], create(context) { const sourceCode = context.getSourceCode(); const configureList = context.options || []; type Scope = null | { upper: Scope; prevNode: TSESTree.Node | null; }; let scopeInfo: Scope = null; /** * Processes to enter to new scope. * This manages the current previous statement. * * @private */ function enterScope(): void { scopeInfo = { upper: scopeInfo, prevNode: null, }; } /** * Processes to exit from the current scope. * * @private */ function exitScope(): void { if (scopeInfo) { scopeInfo = scopeInfo.upper; } } /** * Checks whether the given node matches the given type. * @param node The statement node to check. * @param type The statement type to check. * @returns `true` if the statement node matched the type. * @private */ function match(node: TSESTree.Node, type: string | string[]): boolean { let innerStatementNode = node; while (innerStatementNode.type === AST_NODE_TYPES.LabeledStatement) { innerStatementNode = innerStatementNode.body; } if (Array.isArray(type)) { return type.some(match.bind(null, innerStatementNode)); } return StatementTypes[type].test(innerStatementNode, sourceCode); } /** * Finds the last matched configure from configureList. * @paramprevNode The previous statement to match. * @paramnextNode The current statement to match. * @returns The tester of the last matched configure. * @private */ function getPaddingType( prevNode: TSESTree.Node, nextNode: TSESTree.Node, ): typeof PaddingTypes[keyof typeof PaddingTypes] { for (let i = configureList.length - 1; i >= 0; --i) { const configure = configureList[i]; if ( match(prevNode, configure.prev) && match(nextNode, configure.next) ) { return PaddingTypes[configure.blankLine]; } } return PaddingTypes.any; } /** * Gets padding line sequences between the given 2 statements. * Comments are separators of the padding line sequences. * @paramprevNode The previous statement to count. * @paramnextNode The current statement to count. * @returns The array of token pairs. * @private */ function getPaddingLineSequences( prevNode: TSESTree.Node, nextNode: TSESTree.Node, ): [TSESTree.Token, TSESTree.Token][] { const pairs: [TSESTree.Token, TSESTree.Token][] = []; let prevToken: TSESTree.Token = getActualLastToken(prevNode, sourceCode)!; if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { do { const token: TSESTree.Token = sourceCode.getTokenAfter(prevToken, { includeComments: true, })!; if (token.loc.start.line - prevToken.loc.end.line >= 2) { pairs.push([prevToken, token]); } prevToken = token; } while (prevToken.range[0] < nextNode.range[0]); } return pairs; } /** * Verify padding lines between the given node and the previous node. * @param node The node to verify. * * @private */ function verify(node: TSESTree.Node): void { if ( !node.parent || ![ AST_NODE_TYPES.BlockStatement, AST_NODE_TYPES.Program, AST_NODE_TYPES.SwitchCase, AST_NODE_TYPES.SwitchStatement, AST_NODE_TYPES.TSModuleBlock, ].includes(node.parent.type) ) { return; } // Save this node as the current previous statement. const prevNode = scopeInfo!.prevNode; // Verify. if (prevNode) { const type = getPaddingType(prevNode, node); const paddingLines = getPaddingLineSequences(prevNode, node); type.verify(context, prevNode, node, paddingLines); } scopeInfo!.prevNode = node; } /** * Verify padding lines between the given node and the previous node. * Then process to enter to new scope. * @param node The node to verify. * * @private */ function verifyThenEnterScope(node: TSESTree.Node): void { verify(node); enterScope(); } return { Program: enterScope, BlockStatement: enterScope, SwitchStatement: enterScope, TSModuleBlock: enterScope, 'Program:exit': exitScope, 'BlockStatement:exit': exitScope, 'SwitchStatement:exit': exitScope, 'TSModuleBlock:exit': exitScope, ':statement': verify, SwitchCase: verifyThenEnterScope, TSDeclareFunction: verifyThenEnterScope, 'SwitchCase:exit': exitScope, 'TSDeclareFunction:exit': exitScope, }; }, });
the_stack
import { Crypto } from "../crypto"; import { Model } from "../model"; import { Blob } from "../blob"; import * as Rbac from "../rbac"; import { Auth } from "../auth"; import { Logs } from "../logs"; import Client from "../client"; import { Fetch } from "../fetch"; import { Trust } from "../trust"; import ActionType from "./action_type"; import Api from "."; import { Db } from "./db"; import { Patch } from "rfc6902"; import * as z from "zod"; import * as utils from "../utils"; export namespace Net { export type OkResult = { type: "success" }; export type ValidationErrorResult = { type: "validationError"; error: true; errorStatus: 422; errors: { [attr: string]: string[]; }; }; export type ErrorResult = | { type: "error"; error: true; errorStatus: number; errorReason?: string; } | ValidationErrorResult | RequiresEmailAuthResult | RequiresExternalAuthResult | SignInWrongProviderErrorResult; export type SignedUserTrustedPubkeys = string; export type TokenSessionResult = { type: "tokenSession"; orgId: string; userId: string; deviceId: string; graph: Client.Graph.UserGraph; graphUpdatedAt: number; timestamp: number; signedTrustedRoot: Crypto.SignedData; } & Pick<Db.AuthToken, "token"> & Pick<Db.OrgUser, "provider" | "uid" | "email" | "firstName" | "lastName"> & ( | { hostType: "cloud"; deploymentTag?: undefined; } | { hostType: "self-hosted"; deploymentTag: string; } ); export type SessionResult = TokenSessionResult; export type AuthenticateCliKeyResult = { type: "authenticateCliKeyResult"; orgId: string; userId: string; graph: Client.Graph.UserGraph; graphUpdatedAt: number; timestamp: number; signedTrustedRoot: Crypto.SignedData; } & Pick<Db.CliUser, "name" | "encryptedPrivkey"> & ( | { hostType: "cloud"; deploymentTag?: undefined; } | { hostType: "self-hosted"; deploymentTag: string; } ); export type RegisterResult = Omit<TokenSessionResult, "signedTrustedRoot"> & { orgId: string; } & ( | { hostType: "cloud"; deploymentTag?: undefined; } | { hostType: "self-hosted"; deploymentTag: string; } ); export type AcceptInviteResult = RegisterResult; export type AcceptDeviceGrantResult = RegisterResult; export type RedeemRecoveryKeyResult = RegisterResult; export type SignInWrongProviderErrorResult = { type: "signInWrongProviderError"; error: true; errorReason: string; providers: { provider: Db.OrgUser["provider"]; externalAuthProviderId: string; }[]; }; export type ExistingAuthUser = { id: string; provider: Db.OrgUser["provider"]; externalAuthProviderId?: string; org: Pick<Db.Org, "id" | "name">; }; export type CreateExternalAuthSession = z.infer< typeof CreateExternalAuthSessionSchema >; const CreateExternalAuthSessionSchema = utils.intersection( z.object({ authType: z.enum([ Auth.AuthTypeSchema.Values.accept_device_grant, Auth.AuthTypeSchema.Values.accept_invite, Auth.AuthTypeSchema.Values.redeem_recovery_key, Auth.AuthTypeSchema.Values.sign_in, Auth.AuthTypeSchema.Values.sign_up, ]), authMethod: Auth.ExternalAuthMethodSchema, provider: Auth.ExternalAuthProviderTypeSchema, orgId: z.string(), }), z.union([ utils.intersection( z.object({ authType: z.literal(Auth.AuthTypeSchema.Values.sign_up) }), z.union([ z.object({ authMethod: z.literal( Auth.ExternalAuthMethodSchema.Values.oauth_hosted ), provider: Auth.HostedOauthProviderTypeSchema, providerSettings: Db.HostedOauthProviderSettingsSchema, }), z.object({ authMethod: z.literal("oauth_cloud"), provider: Auth.CloudOauthProviderTypeSchema, }), ]) ), utils.intersection( z.union([ z.object({ authType: z.enum([ Auth.AuthTypeSchema.Values.accept_invite, Auth.AuthTypeSchema.Values.accept_device_grant, Auth.AuthTypeSchema.Values.redeem_recovery_key, ]), // authObjectId can be an invitation ID authObjectId: z.string(), }), z.object({ authType: z.literal(Auth.AuthTypeSchema.Values.sign_in), userId: z.string(), externalAuthProviderId: z.string(), }), ]), z.union([ z.object({ authMethod: z.enum([ Auth.ExternalAuthMethodSchema.Values.oauth_hosted, Auth.ExternalAuthMethodSchema.Values.saml, ]), externalAuthProviderId: z.string(), }), z.object({ authMethod: z.literal( Auth.ExternalAuthMethodSchema.Values.oauth_cloud ), }), z.object({ authMethod: z.literal("saml"), provider: z.literal("saml"), externalAuthProviderId: z.string(), }), ]) ), ]) ); export type CreateExternalAuthInviteSession = z.infer< typeof CreateExternalAuthInviteSessionSchema >; const CreateExternalAuthInviteSessionSchema = utils.intersection( z.object({ authType: z.enum([ Auth.AuthTypeSchema.Values.accept_device_grant, Auth.AuthTypeSchema.Values.accept_invite, Auth.AuthTypeSchema.Values.redeem_recovery_key, Auth.AuthTypeSchema.Values.sign_in, Auth.AuthTypeSchema.Values.sign_up, ]), inviteExternalAuthUsersType: z.enum(["initial", "re-authenticate"]), provider: Auth.ExternalAuthProviderTypeSchema, }), z.union([ utils.intersection( z.object({ authMethod: z.literal( Auth.ExternalAuthMethodSchema.Values.oauth_hosted ), provider: Auth.HostedOauthProviderTypeSchema, }), z.union([ z.object({ inviteExternalAuthUsersType: z.literal("initial"), providerSettings: Db.HostedOauthProviderSettingsSchema, }), z.object({ inviteExternalAuthUsersType: z.literal("re-authenticate"), externalAuthProviderId: z.string(), }), ]) ), z.object({ authMethod: z.literal(Auth.ExternalAuthMethodSchema.Values.oauth_cloud), }), ]) ); export type OauthCallbackQueryParams = z.infer< typeof OauthCallbackQuerySchema >; export const OauthCallbackQuerySchema = z.object({ state: z.string(), code: z.string(), error: z.string().optional(), error_description: z.string().optional(), }); export type OauthCallback = z.infer<typeof OauthCallbackSchema>; export const OauthCallbackSchema = z .object({ provider: Auth.OauthProviderTypeSchema, }) .merge(OauthCallbackQuerySchema); export type SamlAcsCallbackBody = z.infer<typeof SamlAcsCallbackBodyParams>; export const SamlAcsCallbackBodyParams = z.object({ externalAuthProviderId: z.string(), samlResponse: z.string(), relayState: z.string(), }); export type DeviceParams = z.infer<typeof DeviceParamsSchema>; export const DeviceParamsSchema = z.object({ signedTrustedRoot: Crypto.SignedDataSchema, name: z.string(), pubkey: Crypto.PubkeySchema, }); export type IdParams = z.infer<typeof IdParamsSchema>; export const IdParamsSchema = z.object({ id: z.string(), }); export type RequiresEmailAuthResult = { type: "requiresEmailAuthError"; email: string; error: true; errorStatus: 422; errorReason: "Email auth required"; }; export type RequiresExternalAuthResult = { type: "requiresExternalAuthError"; error: true; errorStatus: 422; errorReason: "External auth required"; orgId: string; id: string; } & Pick<Db.OrgUser, "provider" | "externalAuthProviderId" | "uid">; export type NotModifiedResult = { type: "notModified"; status: 304; }; export type UserEnvUpdate = z.infer<typeof UserEnvUpdateSchema>; export const UserEnvUpdateSchema = z.object({ env: Crypto.EncryptedDataSchema.optional(), meta: Crypto.EncryptedDataSchema.optional(), inherits: Crypto.EncryptedDataSchema.optional(), inheritanceOverrides: z.record(Crypto.EncryptedDataSchema).optional(), changesets: Crypto.EncryptedDataSchema.optional(), changesetsById: z .record( z.object({ data: Crypto.EncryptedDataSchema, createdAt: z.number().optional(), createdById: z.string().optional(), }) ) .optional(), }); export type LocalsUpdate = z.infer<typeof LocalsUpdateSchema>; export const LocalsUpdateSchema = z.object({ env: Crypto.EncryptedDataSchema.optional(), meta: Crypto.EncryptedDataSchema.optional(), changesets: Crypto.EncryptedDataSchema.optional(), changesetsById: z .record( z.object({ data: Crypto.EncryptedDataSchema, createdAt: z.number().optional(), createdById: z.string().optional(), }) ) .optional(), }); export type EnvParentsEnvUpdate = z.infer<typeof EnvParentsEnvUpdateSchema>; export const EnvParentsEnvUpdateSchema = z.record( z.object({ environments: z.record(UserEnvUpdateSchema).optional(), locals: z.record(LocalsUpdateSchema).optional(), }) ); export type GeneratedEnvkeyEncryptedKeyParams = z.infer< typeof GeneratedEnvkeyEncryptedKeyParamsSchema >; export const GeneratedEnvkeyEncryptedKeyParamsSchema = Model.GeneratedEnvkeyFieldsSchema( Blob.GeneratedEnvkeyEncryptedKeySchema.pick({ data: true, }) ); export type EnvParams = z.infer<typeof EnvParamsSchema>; export const EnvParamsSchema = z.object({ keys: z.object({ users: z.record(z.record(EnvParentsEnvUpdateSchema)).optional(), keyableParents: z .record(z.record(GeneratedEnvkeyEncryptedKeyParamsSchema)) .optional(), blockKeyableParents: z .record(z.record(z.record(GeneratedEnvkeyEncryptedKeyParamsSchema))) .optional(), newDevice: EnvParentsEnvUpdateSchema.optional(), }), blobs: EnvParentsEnvUpdateSchema, encryptedByTrustChain: Crypto.SignedDataSchema.optional(), }); export type FetchEnvsParams = z.infer<typeof FetchEnvsParamsSchema>; export const FetchChangesetOptionsSchema = z.object({ createdAfter: z.number().optional(), }); export type FetchChangesetOptions = z.infer< typeof FetchChangesetOptionsSchema >; const FetchEnvsParamsSchema = z.object({ byEnvParentId: z.record( z.object({ envs: z.literal(true).optional(), changesets: z.literal(true).optional(), changesetOptions: FetchChangesetOptionsSchema.optional(), }) ), }); type EnvsResult = { envs: { keys: Blob.UserEncryptedKeysByEnvironmentIdOrComposite; blobs: Blob.UserEncryptedBlobsByComposite; }; }; export type EnvsAndOrChangesetsResult = EnvsResult & { changesets: { keys: Blob.UserEncryptedChangesetKeysByEnvironmentId; blobs: Blob.UserEncryptedBlobsByEnvironmentId; }; }; export type GraphDiffsResult = { type: "graphDiffs"; diffs: Patch; graphUpdatedAt: number; timestamp: number; }; export type GraphResult = { type: "graph"; graph: Client.Graph.UserGraph; graphUpdatedAt: number; timestamp: number; signedTrustedRoot?: Crypto.SignedData; }; export type GraphWithEnvsAndOrChangesetsResult = EnvsAndOrChangesetsResult & { graph: Client.Graph.UserGraph; graphUpdatedAt: number; timestamp: number; signedTrustedRoot?: Crypto.SignedData; }; export type FetchEnvsResult = EnvsAndOrChangesetsResult & { type: "envsAndOrChangesets"; timestamp: number; }; export type LoadedInvite = Omit< GraphWithEnvsAndOrChangesetsResult, "type" > & { type: "loadedInvite"; orgId: string; invite: Pick< Api.Db.Invite, | "id" | "encryptedPrivkey" | "pubkey" | "invitedByDeviceId" | "invitedByUserId" | "inviteeId" | "deviceId" >; }; export type LoadedDeviceGrant = Omit< GraphWithEnvsAndOrChangesetsResult, "type" > & { type: "loadedDeviceGrant"; orgId: string; deviceGrant: Pick< Api.Db.DeviceGrant, | "id" | "encryptedPrivkey" | "pubkey" | "grantedByDeviceId" | "grantedByUserId" | "granteeId" | "deviceId" >; }; export type LoadedRecoveryKey = Omit< GraphWithEnvsAndOrChangesetsResult, "type" > & { type: "loadedRecoveryKey"; orgId: string; recoveryKey: Pick< Api.Db.RecoveryKey, "encryptedPrivkey" | "pubkey" | "userId" | "deviceId" | "creatorDeviceId" >; }; export const OrderIndexByIdSchema = z.record(z.number()); export type OrderIndexById = z.infer<typeof OrderIndexByIdSchema>; const registerSchema = utils.intersection( z.object({ user: Model.OrgUserSchema.pick({ email: true, firstName: true, lastName: true, }), device: DeviceParamsSchema, org: Model.OrgSchema.pick({ name: true, settings: true, }), }), z.union([ utils.intersection( z.object({ hostType: z.literal("cloud"), }), z.union([ z.object({ provider: z.literal("email"), emailVerificationToken: z.string(), }), z.object({ provider: Auth.ExternalAuthProviderTypeSchema, externalAuthSessionId: z.string(), }), ]) ), z.object({ hostType: z.literal("self-hosted"), provider: z.literal("email"), emailVerificationToken: z.string().optional(), // for local self-hosted (development only) domain: z.string(), selfHostedFailoverRegion: z.string().optional(), }), z.object({ hostType: z.literal("community"), provider: z.literal("email"), emailVerificationToken: z.string(), communityAuth: z.string(), }), ]) ); export const SCHEMA_URN_ERROR = "urn:ietf:params:scim:api:messages:2.0:Error"; export const SCHEMA_URN_USER = "urn:ietf:params:scim:schemas:core:2.0:User"; export const SCHEMA_URN_LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse"; export interface ScimError { schemas: string[]; // schema of the error, kinda silly but that's the spec status: number; detail: string; scimType?: | "invalidFilter" | "tooMany" | "uniqueness" | "mutability" | "invalidSyntax" | "invalidPath" | "noTarget" | "invalidVers" | "sensitive"; } export interface ScimEmail { value: string; type?: "work" | "home" | "primary" | "other" | string; primary?: boolean; } export interface ScimUser { schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"]; id: string; externalId: string; userName: string; displayName?: string; name: { formatted?: string; familyName: string; givenName: string; }; active: boolean; emails: ScimEmail[]; } export interface ScimUserResponse extends ScimUser { // custom prop type: "scimUserResponse"; // required for user-only schema in rfc 7644 meta: { resourceType: "User"; created: string; lastModified: string; location: string; // custom prop orgId: string; // custom prop orgUserId?: string; }; } export interface ScimListResponse<T> { schemas: string[]; totalResults: number; Resources: T[]; startIndex: number; itemsPerPage: number; } export type ScimCreateUser = z.infer<typeof ScimCreateUserSchema>; export const ScimCreateUserSchema = z.object({ externalId: z.string().optional(), userName: z.string().optional(), active: z.boolean().optional(), emails: z .array( z .object({ primary: z.boolean().optional(), type: z.string().optional(), value: z.string().email(), }) // display, other props .nonstrict() ) .optional(), displayName: z.string().optional(), name: z .object({ formatted: z.string().optional(), familyName: z.string().optional(), givenName: z.string().optional(), }) .nonstrict() .optional(), }); export type ScimPatchUser = z.infer<typeof ScimPatchUserSchema>; export const ScimPatchUserSchema = z.array( z.union([ z .object({ op: z.enum(["Replace", "replace"]), path: z.literal("active"), value: z.union([z.string(), z.boolean()]), }) .nonstrict(), z .object({ op: z.enum(["Replace", "replace"]), path: z.literal("userName"), value: z.string(), }) .nonstrict(), z .object({ op: z.enum(["Add", "Replace", "add", "replace"]), path: z.enum(["name.familyName", "name.givenName"]), value: z.string(), }) .nonstrict(), z .object({ op: z.enum(["Add", "Replace", "add", "replace"]), // email path: z.string(), value: z.string(), }) .nonstrict(), ]) ); export const ApiParamSchemas = { [ActionType.REGISTER]: registerSchema, [ActionType.INIT_SELF_HOSTED]: z.object({ registerAction: z.object({ type: z.literal(ActionType.REGISTER), payload: registerSchema, meta: z.object({ loggableType: z.literal("authAction"), loggableType2: z.literal("orgAction"), client: Client.ClientParamsSchema, }), }), initInstructions: z .union([ z.object({ type: z.literal("dnsCnames"), records: z.array( z.object({ fqdn: z.string(), cname: z.string(), }) ), }), z.object({ type: z.literal("dnsVerifyInternalService"), serviceName: z.string(), record: z.object({ fqdn: z.string(), txt: z.string(), }), }), z.object({ type: z.literal("internalServiceName"), serviceName: z.string(), }), ]) .optional(), }), [ActionType.UPGRADE_SELF_HOSTED]: z.object({ apiVersionNumber: z.string(), infraVersionNumber: z.string().optional(), usingUpdaterVersion: z.string().optional(), }), [ActionType.UPGRADE_SELF_HOSTED_FORCE_CLEAR]: z.object({}), [ActionType.CREATE_SESSION]: utils.intersection( z.object({ orgId: z.string(), userId: z.string(), deviceId: z.string(), signature: z.string(), }), z.union([ z.object({ provider: z.literal("email"), emailVerificationToken: z.string(), }), z.object({ provider: Auth.ExternalAuthProviderTypeSchema, externalAuthSessionId: z.string(), }), ]) ), [ActionType.CLEAR_TOKEN]: z.object({}), [ActionType.FORGET_DEVICE]: z.object({}), [ActionType.CLEAR_USER_TOKENS]: z.object({ userId: z.string(), }), [ActionType.CLEAR_ORG_TOKENS]: z.object({}), [ActionType.GET_SESSION]: z.object({ graphUpdatedAt: z.number().optional(), }), [ActionType.FETCH_ORG_STATS]: z.object({}), [ActionType.RENAME_ORG]: z.object({ name: z.string() }), [ActionType.RENAME_USER]: z .object({ firstName: z.string(), lastName: z.string() }) .merge(IdParamsSchema), [ActionType.DELETE_ORG]: z.object({}), [ActionType.CREATE_EXTERNAL_AUTH_SESSION]: CreateExternalAuthSessionSchema, [ActionType.CREATE_EXTERNAL_AUTH_INVITE_SESSION]: CreateExternalAuthInviteSessionSchema, [ActionType.GET_EXTERNAL_AUTH_SESSION]: z.object({ id: z.string(), }), [ActionType.GET_EXTERNAL_AUTH_PROVIDERS]: z.object({ provider: Auth.ExternalAuthProviderTypeSchema, }), [ActionType.DELETE_EXTERNAL_AUTH_PROVIDER]: IdParamsSchema, [ActionType.GET_EXTERNAL_AUTH_USERS]: z.object({ provider: Auth.OauthProviderTypeSchema, query: z.string().optional(), externalAuthOrgId: z.string().optional(), }), [ActionType.GET_EXTERNAL_AUTH_ORGS]: z.object({ provider: Auth.OauthProviderTypeSchema, }), [ActionType.CREATE_SCIM_PROVISIONING_PROVIDER]: Model.ScimProvisioningProviderSchema.pick({ nickname: true, authScheme: true, }).merge( z.object({ secret: z.string(), }) ), [ActionType.UPDATE_SCIM_PROVISIONING_PROVIDER]: Model.ScimProvisioningProviderSchema.pick({ id: true, nickname: true, authScheme: true, }).merge( z.object({ secret: z.string().optional(), }) ), [ActionType.DELETE_SCIM_PROVISIONING_PROVIDER]: IdParamsSchema, [ActionType.LIST_INVITABLE_SCIM_USERS]: z.object({ id: z.string(), all: z.boolean().optional(), }), [ActionType.CHECK_SCIM_PROVIDER]: IdParamsSchema, // SCIM Request JSON. All may include additional ignored properties from // the SCIM spec, so be sure to add `.nonstrict()` [ActionType.CREATE_SCIM_USER]: ScimCreateUserSchema.nonstrict(), [ActionType.DELETE_SCIM_USER]: z.object({ id: z.string(), providerId: z.string(), }), [ActionType.GET_SCIM_USER]: z.object({ id: z.string(), providerId: z.string(), }), [ActionType.LIST_SCIM_USERS]: z .object({ providerId: z.string(), filter: z.string().optional(), // startIndex is a 1-based index startIndex: z.number().int().min(1).optional(), count: z.number().int().min(1).optional(), sortBy: z.string().optional(), sortOrder: z.string().optional(), // ignored query features attributes: z.string().optional(), excludedAttributes: z.string().optional(), }) .nonstrict(), [ActionType.UPDATE_SCIM_USER]: z .object({ id: z.string(), providerId: z.string(), operations: ScimPatchUserSchema.optional(), Operations: ScimPatchUserSchema.optional(), }) .merge(ScimCreateUserSchema) .nonstrict(), [ActionType.CREATE_EMAIL_VERIFICATION]: z .object({ confirmEmailProvider: z.boolean().optional(), communityAuth: z.string().optional(), }) .merge(Db.EmailVerificationSchema.pick({ authType: true, email: true })), [ActionType.CHECK_EMAIL_TOKEN_VALID]: Db.EmailVerificationSchema.pick({ email: true, token: true, }), [ActionType.CREATE_INVITE]: z .object({ signedTrustedRoot: Crypto.SignedDataSchema, user: Model.OrgUserSchema.pick({ email: true, firstName: true, lastName: true, provider: true, uid: true, externalAuthProviderId: true, orgRoleId: true, }), appUserGrants: z .array( Model.AppUserGrantSchema.pick({ appId: true, appRoleId: true, }) ) .optional(), userGroupIds: z.array(z.string()).optional(), scim: z .object({ providerId: z.string(), candidateId: z.string() }) .optional(), }) .merge( Db.InviteSchema.pick({ identityHash: true, pubkey: true, encryptedPrivkey: true, }) ) .merge(EnvParamsSchema), [ActionType.LOAD_INVITE]: z.object({}), [ActionType.REVOKE_INVITE]: IdParamsSchema, [ActionType.ACCEPT_INVITE]: z .object({ device: DeviceParamsSchema, }) .merge(EnvParamsSchema), [ActionType.OAUTH_CALLBACK]: OauthCallbackSchema, [ActionType.SAML_ACS_CALLBACK]: SamlAcsCallbackBodyParams, [ActionType.CREATE_DEVICE_GRANT]: z .object({ signedTrustedRoot: Crypto.SignedDataSchema, }) .merge( Db.DeviceGrantSchema.pick({ identityHash: true, pubkey: true, encryptedPrivkey: true, granteeId: true, }) ) .merge(EnvParamsSchema), [ActionType.LOAD_DEVICE_GRANT]: z.object({}), [ActionType.REVOKE_DEVICE_GRANT]: IdParamsSchema, [ActionType.ACCEPT_DEVICE_GRANT]: z .object({ device: DeviceParamsSchema, }) .merge(EnvParamsSchema), [ActionType.REVOKE_DEVICE]: IdParamsSchema, [ActionType.UPDATE_ORG_SETTINGS]: Model.OrgSettingsSchema, [ActionType.CREATE_ORG_SAML_PROVIDER]: z.object({ nickname: z.string(), identityProviderKnownService: Model.SamlIdpKnownServiceSchema.optional(), }), [ActionType.UPDATE_ORG_SAML_SETTINGS]: z.object({ id: z.string(), nickname: z.string().optional(), samlSettings: Model.SamlIdpSettingsSchema.merge( Model.SamlProviderEditableSettingsSchema ) .partial() .optional(), }), [ActionType.UPDATE_USER_ROLE]: z .object({ id: z.string(), orgRoleId: z.string(), }) .merge(EnvParamsSchema), [ActionType.REMOVE_FROM_ORG]: IdParamsSchema, [ActionType.CREATE_CLI_USER]: z .object({ cliKeyIdPart: z.string(), signedTrustedRoot: Crypto.SignedDataSchema, appUserGrants: z .array( Model.AppUserGrantSchema.pick({ appId: true, appRoleId: true, }) ) .optional(), }) .merge( Db.CliUserSchema.pick({ name: true, pubkey: true, encryptedPrivkey: true, orgRoleId: true, }) ) .merge(EnvParamsSchema), [ActionType.RENAME_CLI_USER]: z .object({ name: z.string() }) .merge(IdParamsSchema), [ActionType.DELETE_CLI_USER]: IdParamsSchema, [ActionType.AUTHENTICATE_CLI_KEY]: z.object({ cliKeyIdPart: z.string(), }), [ActionType.CREATE_RECOVERY_KEY]: z .object({ signedTrustedRoot: Crypto.SignedDataSchema, }) .merge( z.object({ recoveryKey: Db.RecoveryKeySchema.pick({ identityHash: true, pubkey: true, encryptedPrivkey: true, }), }) ) .merge(EnvParamsSchema), [ActionType.LOAD_RECOVERY_KEY]: z.object({ emailToken: z.string().optional(), }), [ActionType.REDEEM_RECOVERY_KEY]: z .object({ device: DeviceParamsSchema, emailToken: z.string().optional(), }) .merge(EnvParamsSchema), [ActionType.UPDATE_TRUSTED_ROOT_PUBKEY]: z.object({ signedTrustedRoot: Crypto.SignedDataSchema, replacementIds: z.array(z.string()), }), [ActionType.ENVKEY_FETCH_UPDATE_TRUSTED_ROOT_PUBKEY]: z.object({ signedTrustedRoot: Crypto.SignedDataSchema, replacementIds: z.array(z.string()), envkeyIdPart: z.string(), orgId: z.string(), signature: z.string(), }), [ActionType.CREATE_APP]: Model.AppSchema.pick({ name: true, settings: true, }), [ActionType.RENAME_APP]: z .object({ name: z.string() }) .merge(IdParamsSchema), [ActionType.UPDATE_APP_SETTINGS]: z .object({ settings: Model.AppSettingsSchema, }) .merge(IdParamsSchema), [ActionType.DELETE_APP]: IdParamsSchema.merge(EnvParamsSchema.partial()), [ActionType.GRANT_APP_ACCESS]: Model.AppUserGrantSchema.pick({ userId: true, appId: true, appRoleId: true, }).merge(EnvParamsSchema), [ActionType.REMOVE_APP_ACCESS]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_BLOCK]: Model.BlockSchema.pick({ name: true, settings: true, }), [ActionType.RENAME_BLOCK]: z .object({ name: z.string() }) .merge(IdParamsSchema), [ActionType.UPDATE_BLOCK_SETTINGS]: z .object({ settings: Model.BlockSettingsSchema, }) .merge(IdParamsSchema), [ActionType.DELETE_BLOCK]: IdParamsSchema, [ActionType.CONNECT_BLOCK]: Model.AppBlockSchema.pick({ appId: true, blockId: true, orderIndex: true, }).merge(EnvParamsSchema), [ActionType.DISCONNECT_BLOCK]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.UPDATE_ENVS]: EnvParamsSchema, [ActionType.FETCH_ENVS]: FetchEnvsParamsSchema, [ActionType.CREATE_VARIABLE_GROUP]: Model.VariableGroupSchema.pick({ envParentId: true, subEnvironmentId: true, name: true, }), [ActionType.DELETE_VARIABLE_GROUP]: IdParamsSchema, [ActionType.CREATE_SERVER]: Model.ServerSchema.pick({ appId: true, name: true, environmentId: true, }), [ActionType.DELETE_SERVER]: IdParamsSchema, [ActionType.CREATE_LOCAL_KEY]: Model.LocalKeySchema.pick({ appId: true, name: true, environmentId: true, autoGenerated: true, }), [ActionType.DELETE_LOCAL_KEY]: IdParamsSchema, [ActionType.GENERATE_KEY]: z .object({ envkeyIdPart: z.string(), signedTrustedRoot: Crypto.SignedDataSchema, }) .merge( Db.GeneratedEnvkeySchema.pick({ appId: true, keyableParentType: true, keyableParentId: true, pubkey: true, encryptedPrivkey: true, }) ) .merge(EnvParamsSchema), [ActionType.REVOKE_KEY]: IdParamsSchema, [ActionType.FETCH_LOGS]: Logs.FetchLogParamsSchema, [ActionType.RBAC_CREATE_ORG_ROLE]: utils.intersection( Rbac.RoleBaseSchema.pick({ name: true, description: true }) .merge(Rbac.OrgRoleBaseSchema.omit({ type: true })) .merge( z.object({ canBeManagedByOrgRoleIds: z.array(z.string()), canBeInvitedByOrgRoleIds: z.array(z.string()), }) ), utils.intersection( Rbac.WithPermissions(Rbac.OrgPermissionSchema), utils.intersection( Rbac.OrgRoleCanManageSchema, Rbac.OrgRoleCanInviteSchema ) ) ), [ActionType.RBAC_DELETE_ORG_ROLE]: IdParamsSchema, [ActionType.RBAC_UPDATE_ORG_ROLE]: utils.intersection( IdParamsSchema.merge( Rbac.RoleBaseSchema.pick({ name: true, description: true, }).partial() ) .merge( z .object({ canBeManagedByOrgRoleIds: z.array(z.string()), canBeInvitedByOrgRoleIds: z.array(z.string()), }) .partial() ) .merge( Rbac.OrgRoleBaseSchema.pick({ autoAppRoleId: true, }).partial() ) .merge(EnvParamsSchema.partial()), utils.intersection( Rbac.WithOptionalPermissions(Rbac.OrgPermissionSchema), utils.intersection( Rbac.OrgRoleOptionalCanManageSchema, Rbac.OrgRoleOptionalCanInviteSchema ) ) ), [ActionType.CREATE_ENVIRONMENT]: utils.intersection( Model.EnvironmentBaseSchema.pick({ envParentId: true, environmentRoleId: true, }).merge(EnvParamsSchema.partial()), z.union([ z.object({ isSub: z.undefined(), parentEnvironmentId: z.undefined(), subName: z.undefined(), }), z.object({ isSub: z.literal(true), parentEnvironmentId: z.string(), subName: z.string(), }), ]) ), [ActionType.DELETE_ENVIRONMENT]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.UPDATE_ENVIRONMENT_SETTINGS]: IdParamsSchema.merge( z.object({ settings: Model.EnvironmentSettingsSchema, }) ), [ActionType.RBAC_CREATE_ENVIRONMENT_ROLE]: Rbac.RoleBaseSchema.pick({ name: true, description: true, }) .merge( Rbac.EnvironmentRoleBaseSchema.omit({ type: true, orderIndex: true }) ) .merge( z.object({ appRoleEnvironmentRoles: Rbac.EnvironmentPermissionsSchema, }) ), [ActionType.RBAC_DELETE_ENVIRONMENT_ROLE]: IdParamsSchema, [ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE]: IdParamsSchema.merge( Rbac.RoleBaseSchema.pick({ name: true, description: true, }).partial() ) .merge( z .object({ appRoleEnvironmentRoles: Rbac.EnvironmentPermissionsSchema, }) .partial() ) .merge(Rbac.EnvironmentRoleBaseSchema.omit({ type: true }).partial()) .merge(EnvParamsSchema.partial()), [ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE_SETTINGS]: IdParamsSchema.merge( z.object({ settings: Rbac.EnvironmentRoleSettingsSchema, }) ), [ActionType.RBAC_REORDER_ENVIRONMENT_ROLES]: OrderIndexByIdSchema, [ActionType.RBAC_CREATE_APP_ROLE]: utils.intersection( Rbac.RoleBaseSchema.pick({ name: true, description: true, }) .merge(Rbac.AppRoleBaseSchema.omit({ type: true })) .merge( z.object({ canBeManagedByAppRoleIds: z.array(z.string()), canBeInvitedByAppRoleIds: z.array(z.string()), appRoleEnvironmentRoles: Rbac.EnvironmentPermissionsSchema, }) ), Rbac.WithPermissions(Rbac.AppPermissionSchema) ), [ActionType.RBAC_DELETE_APP_ROLE]: IdParamsSchema, [ActionType.RBAC_UPDATE_APP_ROLE]: utils.intersection( IdParamsSchema.merge( Rbac.RoleBaseSchema.pick({ name: true, description: true, }).partial() ) .merge( Rbac.AppRoleBaseSchema.pick({ defaultAllApps: true, canManageAppRoleIds: true, canInviteAppRoleIds: true, hasFullEnvironmentPermissions: true, }).partial() ) .merge( z .object({ canBeManagedByAppRoleIds: z.array(z.string()), canBeInvitedByAppRoleIds: z.array(z.string()), appRoleEnvironmentRoles: Rbac.EnvironmentPermissionsSchema, }) .partial() ) .merge(EnvParamsSchema.partial()), Rbac.WithOptionalPermissions(Rbac.AppPermissionSchema) ), [ActionType.RBAC_CREATE_INCLUDED_APP_ROLE]: Model.IncludedAppRoleSchema.pick({ appId: true, appRoleId: true, }).merge(EnvParamsSchema.partial()), [ActionType.DELETE_INCLUDED_APP_ROLE]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_GROUP]: Model.GroupSchema.pick({ name: true, objectType: true, }), [ActionType.RENAME_GROUP]: Model.GroupSchema.pick({ name: true, }).merge(IdParamsSchema), [ActionType.DELETE_GROUP]: IdParamsSchema.merge(EnvParamsSchema.partial()), [ActionType.CREATE_GROUP_MEMBERSHIP]: z .object({ orderIndex: z.number().optional(), }) .merge( Model.GroupMembershipSchema.pick({ groupId: true, objectId: true, }) ) .merge(EnvParamsSchema.partial()), [ActionType.DELETE_GROUP_MEMBERSHIP]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_USER_GROUP]: Model.AppUserGroupSchema.pick({ appId: true, userGroupId: true, appRoleId: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_USER_GROUP]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_GROUP_USER_GROUP]: Model.AppGroupUserGroupSchema.pick({ appGroupId: true, userGroupId: true, appRoleId: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_GROUP_USER_GROUP]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_GROUP_USER]: Model.AppGroupUserSchema.pick({ appGroupId: true, userId: true, appRoleId: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_GROUP_USER]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_BLOCK_GROUP]: Model.AppBlockGroupSchema.pick({ appId: true, blockGroupId: true, orderIndex: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_BLOCK_GROUP]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_GROUP_BLOCK]: Model.AppGroupBlockSchema.pick({ appGroupId: true, blockId: true, orderIndex: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_GROUP_BLOCK]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.CREATE_APP_GROUP_BLOCK_GROUP]: Model.AppGroupBlockGroupSchema.pick({ appGroupId: true, blockGroupId: true, orderIndex: true, }).merge(EnvParamsSchema), [ActionType.DELETE_APP_GROUP_BLOCK_GROUP]: IdParamsSchema.merge( EnvParamsSchema.partial() ), [ActionType.REORDER_BLOCKS]: z.object({ appId: z.string(), order: OrderIndexByIdSchema, }), [ActionType.REORDER_GROUP_MEMBERSHIPS]: z.object({ blockGroupId: z.string(), order: OrderIndexByIdSchema, }), [ActionType.REORDER_APP_BLOCK_GROUPS]: z.object({ appId: z.string(), order: OrderIndexByIdSchema, }), [ActionType.REORDER_APP_GROUP_BLOCKS]: z.object({ appGroupId: z.string(), order: OrderIndexByIdSchema, }), [ActionType.REORDER_APP_GROUP_BLOCK_GROUPS]: z.object({ appGroupId: z.string(), order: OrderIndexByIdSchema, }), [ActionType.REVOKE_TRUSTED_PUBKEYS]: z.object({ byRequestId: z.record(z.string()), signedPubkeys: z.record(Crypto.PubkeySchema), replacingRootTrustChain: Trust.SignedTrustChainSchema.optional(), signedTrustedRoot: Trust.SignedTrustChainSchema.optional(), }), [ActionType.FETCH_ENVKEY]: z.object({ envkeyIdPart: z.string(), }), [ActionType.CHECK_ENVKEY]: z.object({ envkeyIdPart: z.string(), }), [ActionType.FETCH_DELETED_GRAPH]: z.object({ startsAt: z.number().optional(), endsAt: z.number().optional(), }), [ActionType.UPDATE_LICENSE]: z.object({ signedLicense: z.string(), }), [ActionType.REENCRYPT_ENVS]: EnvParamsSchema, [ActionType.SELF_HOSTED_RESYNC_FAILOVER]: z.object({}), [ActionType.SET_ORG_ALLOWED_IPS]: Model.OrgSchema.pick({ localIpsAllowed: true, environmentRoleIpsAllowed: true, }), [ActionType.SET_APP_ALLOWED_IPS]: Model.AppSchema.pick({ environmentRoleIpsMergeStrategies: true, environmentRoleIpsAllowed: true, }).merge(IdParamsSchema), // BULK_GRAPH_ACTION schema isn't used anywhere as bulk actions are validated individually, // but it makes this object exhaustive so the compiler's happy [ActionType.BULK_GRAPH_ACTION]: z.any(), }; export const getSchema = (t: ActionType) => ApiParamSchemas[t] as z.ZodTypeAny | undefined; export type ApiParamTypes = { Register: z.infer<typeof ApiParamSchemas[ActionType.REGISTER]>; InitSelfHosted: z.infer< typeof ApiParamSchemas[ActionType.INIT_SELF_HOSTED] >; UpgradeSelfHosted: z.infer< typeof ApiParamSchemas[ActionType.UPGRADE_SELF_HOSTED] >; UpgradeSelfHostedForceClear: z.infer< typeof ApiParamSchemas[ActionType.UPGRADE_SELF_HOSTED_FORCE_CLEAR] >; CreateSession: z.infer<typeof ApiParamSchemas[ActionType.CREATE_SESSION]>; GetSession: z.infer<typeof ApiParamSchemas[ActionType.GET_SESSION]>; ClearToken: z.infer<typeof ApiParamSchemas[ActionType.CLEAR_TOKEN]>; ForgetDevice: z.infer<typeof ApiParamSchemas[ActionType.FORGET_DEVICE]>; ClearUserTokens: z.infer< typeof ApiParamSchemas[ActionType.CLEAR_USER_TOKENS] >; ClearOrgTokens: z.infer< typeof ApiParamSchemas[ActionType.CLEAR_ORG_TOKENS] >; DeleteOrg: z.infer<typeof ApiParamSchemas[ActionType.DELETE_ORG]>; RenameOrg: z.infer<typeof ApiParamSchemas[ActionType.RENAME_ORG]>; RenameUser: z.infer<typeof ApiParamSchemas[ActionType.RENAME_USER]>; CreateExternalAuthSession: z.infer< typeof ApiParamSchemas[ActionType.CREATE_EXTERNAL_AUTH_SESSION] >; CreateExternalAuthInviteSession: z.infer< typeof ApiParamSchemas[ActionType.CREATE_EXTERNAL_AUTH_INVITE_SESSION] >; GetExternalAuthSession: z.infer< typeof ApiParamSchemas[ActionType.GET_EXTERNAL_AUTH_SESSION] >; GetExternalAuthProviders: z.infer< typeof ApiParamSchemas[ActionType.GET_EXTERNAL_AUTH_PROVIDERS] >; DeleteExternalAuthProvider: z.infer< typeof ApiParamSchemas[ActionType.DELETE_EXTERNAL_AUTH_PROVIDER] >; OauthCallback: z.infer<typeof ApiParamSchemas[ActionType.OAUTH_CALLBACK]>; SamlAcsCallback: z.infer< typeof ApiParamSchemas[ActionType.SAML_ACS_CALLBACK] >; GetExternalAuthUsers: z.infer< typeof ApiParamSchemas[ActionType.GET_EXTERNAL_AUTH_USERS] >; GetExternalAuthOrgs: z.infer< typeof ApiParamSchemas[ActionType.GET_EXTERNAL_AUTH_ORGS] >; CreateEmailVerification: z.infer< typeof ApiParamSchemas[ActionType.CREATE_EMAIL_VERIFICATION] >; CheckEmailTokenValid: z.infer< typeof ApiParamSchemas[ActionType.CHECK_EMAIL_TOKEN_VALID] >; CreateInvite: z.infer<typeof ApiParamSchemas[ActionType.CREATE_INVITE]>; LoadInvite: z.infer<typeof ApiParamSchemas[ActionType.LOAD_INVITE]>; RevokeInvite: z.infer<typeof ApiParamSchemas[ActionType.REVOKE_INVITE]>; AcceptInvite: z.infer<typeof ApiParamSchemas[ActionType.ACCEPT_INVITE]>; CreateRecoveryKey: z.infer< typeof ApiParamSchemas[ActionType.CREATE_RECOVERY_KEY] >; LoadRecoveryKey: z.infer< typeof ApiParamSchemas[ActionType.LOAD_RECOVERY_KEY] >; RedeemRecoveryKey: z.infer< typeof ApiParamSchemas[ActionType.REDEEM_RECOVERY_KEY] >; UpdateTrustedRootPubkey: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_TRUSTED_ROOT_PUBKEY] >; EnvkeyFetchUpdateTrustedRootPubkey: z.infer< typeof ApiParamSchemas[ActionType.ENVKEY_FETCH_UPDATE_TRUSTED_ROOT_PUBKEY] >; LoadDeviceGrant: z.infer< typeof ApiParamSchemas[ActionType.LOAD_DEVICE_GRANT] >; AcceptDeviceGrant: z.infer< typeof ApiParamSchemas[ActionType.ACCEPT_DEVICE_GRANT] >; FetchEnvs: z.infer<typeof ApiParamSchemas[ActionType.FETCH_ENVS]>; FetchLogs: z.infer<typeof ApiParamSchemas[ActionType.FETCH_LOGS]>; FetchDeletedGraph: z.infer< typeof ApiParamSchemas[ActionType.FETCH_DELETED_GRAPH] >; CreateDeviceGrant: z.infer< typeof ApiParamSchemas[ActionType.CREATE_DEVICE_GRANT] >; RevokeDeviceGrant: z.infer< typeof ApiParamSchemas[ActionType.REVOKE_DEVICE_GRANT] >; RevokeDevice: z.infer<typeof ApiParamSchemas[ActionType.REVOKE_DEVICE]>; UpdateOrgSettings: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_ORG_SETTINGS] >; CreateOrgSamlProvider: z.infer< typeof ApiParamSchemas[ActionType.CREATE_ORG_SAML_PROVIDER] >; UpdateOrgSamlSettings: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_ORG_SAML_SETTINGS] >; CreateScimProvisioningProvider: z.infer< typeof ApiParamSchemas[ActionType.CREATE_SCIM_PROVISIONING_PROVIDER] >; UpdateScimProvisioningProvider: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_SCIM_PROVISIONING_PROVIDER] >; DeleteScimProvisioningProvider: z.infer< typeof ApiParamSchemas[ActionType.DELETE_SCIM_PROVISIONING_PROVIDER] >; ListInvitableScimUsers: z.infer< typeof ApiParamSchemas[ActionType.LIST_INVITABLE_SCIM_USERS] >; CheckScimProvider: z.infer< typeof ApiParamSchemas[ActionType.CHECK_SCIM_PROVIDER] >; CreateScimUser: z.infer< typeof ApiParamSchemas[ActionType.CREATE_SCIM_USER] >; GetScimUser: z.infer<typeof ApiParamSchemas[ActionType.GET_SCIM_USER]>; ListScimUsers: z.infer<typeof ApiParamSchemas[ActionType.LIST_SCIM_USERS]>; DeleteScimUser: z.infer< typeof ApiParamSchemas[ActionType.DELETE_SCIM_USER] >; UpdateScimUser: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_SCIM_USER] >; UpdateUserRole: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_USER_ROLE] >; RemoveFromOrg: z.infer<typeof ApiParamSchemas[ActionType.REMOVE_FROM_ORG]>; CreateCliUser: z.infer<typeof ApiParamSchemas[ActionType.CREATE_CLI_USER]>; RenameCliUser: z.infer<typeof ApiParamSchemas[ActionType.RENAME_CLI_USER]>; DeleteCliUser: z.infer<typeof ApiParamSchemas[ActionType.DELETE_CLI_USER]>; AuthenticateCliKey: z.infer< typeof ApiParamSchemas[ActionType.AUTHENTICATE_CLI_KEY] >; CreateApp: z.infer<typeof ApiParamSchemas[ActionType.CREATE_APP]>; RenameApp: z.infer<typeof ApiParamSchemas[ActionType.RENAME_APP]>; UpdateAppSettings: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_APP_SETTINGS] >; DeleteApp: z.infer<typeof ApiParamSchemas[ActionType.DELETE_APP]>; GrantAppAccess: z.infer< typeof ApiParamSchemas[ActionType.GRANT_APP_ACCESS] >; RemoveAppAccess: z.infer< typeof ApiParamSchemas[ActionType.REMOVE_APP_ACCESS] >; CreateBlock: z.infer<typeof ApiParamSchemas[ActionType.CREATE_BLOCK]>; RenameBlock: z.infer<typeof ApiParamSchemas[ActionType.RENAME_BLOCK]>; UpdateBlockSettings: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_BLOCK_SETTINGS] >; DeleteBlock: z.infer<typeof ApiParamSchemas[ActionType.DELETE_BLOCK]>; ConnectBlock: z.infer<typeof ApiParamSchemas[ActionType.CONNECT_BLOCK]>; DisconnectBlock: z.infer< typeof ApiParamSchemas[ActionType.DISCONNECT_BLOCK] >; UpdateEnvs: z.infer<typeof ApiParamSchemas[ActionType.UPDATE_ENVS]>; CreateVariableGroup: z.infer< typeof ApiParamSchemas[ActionType.CREATE_VARIABLE_GROUP] >; DeleteVariableGroup: z.infer< typeof ApiParamSchemas[ActionType.DELETE_VARIABLE_GROUP] >; CreateServer: z.infer<typeof ApiParamSchemas[ActionType.CREATE_SERVER]>; DeleteServer: z.infer<typeof ApiParamSchemas[ActionType.DELETE_SERVER]>; CreateLocalKey: z.infer< typeof ApiParamSchemas[ActionType.CREATE_LOCAL_KEY] >; DeleteLocalKey: z.infer< typeof ApiParamSchemas[ActionType.DELETE_LOCAL_KEY] >; GenerateKey: z.infer<typeof ApiParamSchemas[ActionType.GENERATE_KEY]>; RevokeKey: z.infer<typeof ApiParamSchemas[ActionType.REVOKE_KEY]>; RbacCreateOrgRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_CREATE_ORG_ROLE] >; RbacDeleteOrgRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_DELETE_ORG_ROLE] >; RbacUpdateOrgRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_UPDATE_ORG_ROLE] >; CreateEnvironment: z.infer< typeof ApiParamSchemas[ActionType.CREATE_ENVIRONMENT] >; DeleteEnvironment: z.infer< typeof ApiParamSchemas[ActionType.DELETE_ENVIRONMENT] >; UpdateEnvironmentSettings: z.infer< typeof ApiParamSchemas[ActionType.UPDATE_ENVIRONMENT_SETTINGS] >; RbacCreateEnvironmentRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_CREATE_ENVIRONMENT_ROLE] >; RbacDeleteEnvironmentRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_DELETE_ENVIRONMENT_ROLE] >; RbacUpdateEnvironmentRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE] >; RbacUpdateEnvironmentRoleSettings: z.infer< typeof ApiParamSchemas[ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE_SETTINGS] >; RbacReorderEnvironmentRoles: z.infer< typeof ApiParamSchemas[ActionType.RBAC_REORDER_ENVIRONMENT_ROLES] >; RbacCreateAppRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_CREATE_APP_ROLE] >; RbacDeleteAppRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_DELETE_APP_ROLE] >; RbacUpdateAppRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_UPDATE_APP_ROLE] >; RbacCreateIncludedAppRole: z.infer< typeof ApiParamSchemas[ActionType.RBAC_CREATE_INCLUDED_APP_ROLE] >; DeleteIncludedAppRole: z.infer< typeof ApiParamSchemas[ActionType.DELETE_INCLUDED_APP_ROLE] >; CreateGroup: z.infer<typeof ApiParamSchemas[ActionType.CREATE_GROUP]>; RenameGroup: z.infer<typeof ApiParamSchemas[ActionType.RENAME_GROUP]>; DeleteGroup: z.infer<typeof ApiParamSchemas[ActionType.DELETE_GROUP]>; CreateGroupMembership: z.infer< typeof ApiParamSchemas[ActionType.CREATE_GROUP_MEMBERSHIP] >; DeleteGroupMembership: z.infer< typeof ApiParamSchemas[ActionType.DELETE_GROUP_MEMBERSHIP] >; CreateAppUserGroup: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_USER_GROUP] >; DeleteAppUserGroup: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_USER_GROUP] >; CreateAppGroupUserGroup: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_GROUP_USER_GROUP] >; DeleteAppGroupUserGroup: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_GROUP_USER_GROUP] >; CreateAppGroupUser: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_GROUP_USER] >; DeleteAppGroupUser: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_GROUP_USER] >; CreateAppBlockGroup: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_BLOCK_GROUP] >; DeleteAppBlockGroup: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_BLOCK_GROUP] >; CreateAppGroupBlock: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_GROUP_BLOCK] >; DeleteAppGroupBlock: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_GROUP_BLOCK] >; CreateAppGroupBlockGroup: z.infer< typeof ApiParamSchemas[ActionType.CREATE_APP_GROUP_BLOCK_GROUP] >; DeleteAppGroupBlockGroup: z.infer< typeof ApiParamSchemas[ActionType.DELETE_APP_GROUP_BLOCK_GROUP] >; ReorderBlocks: z.infer<typeof ApiParamSchemas[ActionType.REORDER_BLOCKS]>; ReorderGroupMemberships: z.infer< typeof ApiParamSchemas[ActionType.REORDER_GROUP_MEMBERSHIPS] >; ReorderAppBlockGroups: z.infer< typeof ApiParamSchemas[ActionType.REORDER_APP_BLOCK_GROUPS] >; ReorderAppGroupBlocks: z.infer< typeof ApiParamSchemas[ActionType.REORDER_APP_GROUP_BLOCKS] >; ReorderAppGroupBlockGroups: z.infer< typeof ApiParamSchemas[ActionType.REORDER_APP_GROUP_BLOCK_GROUPS] >; RevokeTrustedPubkeys: z.infer< typeof ApiParamSchemas[ActionType.REVOKE_TRUSTED_PUBKEYS] >; FetchEnvkey: z.infer<typeof ApiParamSchemas[ActionType.FETCH_ENVKEY]>; CheckEnvkey: z.infer<typeof ApiParamSchemas[ActionType.CHECK_ENVKEY]>; UpdateLicense: z.infer<typeof ApiParamSchemas[ActionType.UPDATE_LICENSE]>; ReencryptEnvs: z.infer<typeof ApiParamSchemas[ActionType.REENCRYPT_ENVS]>; FetchOrgStats: z.infer<typeof ApiParamSchemas[ActionType.FETCH_ORG_STATS]>; SelfHostedResyncFailover: z.infer< typeof ApiParamSchemas[ActionType.SELF_HOSTED_RESYNC_FAILOVER] >; SetOrgAllowedIps: z.infer< typeof ApiParamSchemas[ActionType.SET_ORG_ALLOWED_IPS] >; SetAppAllowedIps: z.infer< typeof ApiParamSchemas[ActionType.SET_APP_ALLOWED_IPS] >; }; export type ApiResultTypes = { Register: ValidationErrorResult | RegisterResult; InitSelfHosted: OkResult; UpgradeSelfHosted: GraphDiffsResult; UpgradeSelfHostedForceClear: GraphDiffsResult; CreateSession: SessionResult; GetSession: SessionResult | NotModifiedResult; ClearToken: OkResult; ForgetDevice: OkResult; ClearUserTokens: OkResult; ClearOrgTokens: OkResult; DeleteOrg: OkResult; RenameOrg: GraphDiffsResult; RenameUser: GraphDiffsResult; CreateExternalAuthSession: | { type: "pendingExternalAuthSession"; id: string; authUrl: string; authMethod: Auth.AuthMethod; } | RequiresEmailAuthResult | SignInWrongProviderErrorResult; CreateExternalAuthInviteSession: ApiResultTypes["CreateExternalAuthSession"]; GetExternalAuthSession: | { type: "externalAuthSession"; session: Pick< Db.ExternalAuthSession, | "id" | "error" | "errorAt" | "authType" | "authMethod" | "provider" | "externalAuthProviderId" | "verifiedEmail" | "externalUid" | "userId" | "orgId" | "suggestFirstName" | "suggestLastName" >; existingUsers: ExistingAuthUser[]; } | RequiresExternalAuthResult; GetExternalAuthProviders: { type: "externalAuthProviders"; providers: (Model.ExternalAuthProvider & { endpoint?: string })[]; samlSettingsByProviderId?: Record< string, Model.SamlProviderSettings | undefined >; }; DeleteExternalAuthProvider: GraphDiffsResult; OauthCallback: { type: "oauthCallback"; result: string }; SamlAcsCallback: { type: "samlAcsCallback"; email: string; userId: string; externalAuthSessionId: string; }; GetExternalAuthUsers: { type: "externalAuthUsers"; users: Model.ExternalAuthUser[]; }; GetExternalAuthOrgs: { type: "externalAuthOrgs"; orgs: { [id: string]: string; }; }; CreateEmailVerification: OkResult | SignInWrongProviderErrorResult; CheckEmailTokenValid: OkResult; CreateInvite: ValidationErrorResult | GraphDiffsResult; LoadInvite: LoadedInvite | RequiresExternalAuthResult; RevokeInvite: GraphDiffsResult; AcceptInvite: AcceptInviteResult; CreateRecoveryKey: GraphDiffsResult; LoadRecoveryKey: LoadedRecoveryKey | RequiresEmailAuthResult; RedeemRecoveryKey: RedeemRecoveryKeyResult; UpdateTrustedRootPubkey: OkResult; FetchGraph: GraphResult; LoadDeviceGrant: LoadedDeviceGrant | RequiresExternalAuthResult; AcceptDeviceGrant: AcceptDeviceGrantResult; FetchEnvs: FetchEnvsResult; FetchLogs: { type: "logs"; logs: Logs.LoggedAction[]; totalCount?: number; countReachedLimit?: boolean; deletedGraph?: Client.Graph.UserGraph; ips?: string[]; }; FetchDeletedGraph: { type: "deletedGraph"; deletedGraph: Client.Graph.UserGraph; }; CreateDeviceGrant: GraphDiffsResult | ValidationErrorResult; RevokeDeviceGrant: GraphDiffsResult; RevokeDevice: GraphDiffsResult; UpdateOrgSettings: ValidationErrorResult | GraphDiffsResult; CreateOrgSamlProvider: GraphDiffsResult; UpdateOrgSamlSettings: GraphDiffsResult; CreateScimProvisioningProvider: GraphDiffsResult; UpdateScimProvisioningProvider: GraphDiffsResult; DeleteScimProvisioningProvider: GraphDiffsResult; CheckScimProvider: { type: "checkScimProviderResponse"; status: number; nickname: string; }; CreateScimUser: { status: number } & ( | ScimUserResponse | ({ type: "scimError" } & ScimError) ); GetScimUser: { status: number } & ( | ScimUserResponse | ({ type: "scimError" } & ScimError) ); ListScimUsers: { status: number } & ( | ({ type: "scimUserCandidateList" } & ScimListResponse<ScimUser>) // note: not ScimUserResponse | ({ type: "scimError" } & ScimError) ); DeleteScimUser: GraphDiffsResult | ({ type: "scimError" } & ScimError); UpdateScimUser: { status: number } & ( | ScimUserResponse | ({ type: "scimError" } & ScimError) ); ListInvitableScimUsers: { type: "scimUserCandidates"; scimUserCandidates: Model.ScimUserCandidate[]; }; UpdateUserRole: ValidationErrorResult | GraphDiffsResult; RemoveFromOrg: GraphDiffsResult; CreateCliUser: ValidationErrorResult | GraphDiffsResult; RenameCliUser: GraphDiffsResult; DeleteCliUser: GraphDiffsResult; AuthenticateCliKey: AuthenticateCliKeyResult; CreateApp: ValidationErrorResult | GraphDiffsResult; RenameApp: GraphDiffsResult; UpdateAppSettings: ValidationErrorResult | GraphDiffsResult; DeleteApp: GraphDiffsResult; GrantAppAccess: GraphDiffsResult; RemoveAppAccess: GraphDiffsResult; CreateBlock: ValidationErrorResult | GraphDiffsResult; RenameBlock: GraphDiffsResult; UpdateBlockSettings: ValidationErrorResult | GraphDiffsResult; DeleteBlock: GraphDiffsResult; ConnectBlock: GraphDiffsResult; DisconnectBlock: GraphDiffsResult; UpdateEnvs: ValidationErrorResult | GraphDiffsResult; CreateVariableGroup: ValidationErrorResult | GraphDiffsResult; DeleteVariableGroup: GraphDiffsResult; CreateServer: ValidationErrorResult | GraphDiffsResult; DeleteServer: GraphDiffsResult; CreateLocalKey: ValidationErrorResult | GraphDiffsResult; DeleteLocalKey: GraphDiffsResult; GenerateKey: GraphDiffsResult; RevokeKey: GraphDiffsResult; RbacCreateOrgRole: ValidationErrorResult | GraphDiffsResult; RbacDeleteOrgRole: GraphDiffsResult; RbacUpdateOrgRole: ValidationErrorResult | GraphDiffsResult; CreateEnvironment: ValidationErrorResult | GraphDiffsResult; DeleteEnvironment: GraphDiffsResult; UpdateEnvironmentSettings: ValidationErrorResult | GraphDiffsResult; RbacCreateEnvironmentRole: ValidationErrorResult | GraphDiffsResult; RbacDeleteEnvironmentRole: GraphDiffsResult; RbacUpdateEnvironmentRole: ValidationErrorResult | GraphDiffsResult; RbacUpdateEnvironmentRoleSettings: ValidationErrorResult | GraphDiffsResult; RbacReorderEnvironmentRoles: GraphDiffsResult; RbacCreateAppRole: ValidationErrorResult | GraphDiffsResult; RbacDeleteAppRole: GraphDiffsResult; RbacUpdateAppRole: ValidationErrorResult | GraphDiffsResult; RbacCreateIncludedAppRole: ValidationErrorResult | GraphDiffsResult; DeleteIncludedAppRole: GraphDiffsResult; CreateGroup: ValidationErrorResult | GraphDiffsResult; RenameGroup: ValidationErrorResult | GraphDiffsResult; DeleteGroup: GraphDiffsResult; CreateGroupMembership: ValidationErrorResult | GraphDiffsResult; DeleteGroupMembership: GraphDiffsResult; CreateAppUserGroup: ValidationErrorResult | GraphDiffsResult; DeleteAppUserGroup: GraphDiffsResult; CreateAppGroupUserGroup: ValidationErrorResult | GraphDiffsResult; DeleteAppGroupUserGroup: GraphDiffsResult; CreateAppGroupUser: ValidationErrorResult | GraphDiffsResult; DeleteAppGroupUser: GraphDiffsResult; CreateAppBlockGroup: ValidationErrorResult | GraphDiffsResult; DeleteAppBlockGroup: GraphDiffsResult; CreateAppGroupBlock: ValidationErrorResult | GraphDiffsResult; DeleteAppGroupBlock: GraphDiffsResult; CreateAppGroupBlockGroup: ValidationErrorResult | GraphDiffsResult; DeleteAppGroupBlockGroup: GraphDiffsResult; ReorderBlocks: GraphDiffsResult; ReorderGroupMemberships: GraphDiffsResult; ReorderAppBlockGroups: GraphDiffsResult; ReorderAppGroupBlocks: GraphDiffsResult; ReorderAppGroupBlockGroups: GraphDiffsResult; RevokeTrustedPubkeys: GraphDiffsResult; UpdateLicense: GraphDiffsResult; ReencryptEnvs: GraphDiffsResult; FetchEnvkey: Fetch.Result; CheckEnvkey: Fetch.CheckResult; EnvkeyFetchUpdateTrustedRootPubkey: OkResult; FetchOrgStats: { type: "orgStats"; orgStats: Model.OrgStats; }; SelfHostedResyncFailover: OkResult; SetOrgAllowedIps: GraphDiffsResult; SetAppAllowedIps: GraphDiffsResult; }; export type ApiParams = ApiParamTypes[keyof ApiParamTypes]; export type ApiResult = ApiResultTypes[keyof ApiResultTypes]; export type ScimApiResult = | ApiResultTypes["CheckScimProvider"] | ApiResultTypes["CreateScimUser"] | ApiResultTypes["GetScimUser"] | ApiResultTypes["ListScimUsers"] | ApiResultTypes["DeleteScimUser"] | ApiResultTypes["UpdateScimUser"]; }
the_stack
import { mount } from 'enzyme'; import React, { ComponentType, FC, Fragment } from 'react'; import omit from 'lodash/omit'; import flow from 'lodash/flow'; import { withDesign, DesignableProps, Design, extendDesignable, DesignableComponentsProps, designable, withFinalDesign, startWith, replaceWith, } from '../src/Design'; import { withShowDesignKeys, asToken, HOC } from '../src'; type SpanType = ComponentType<any>; type MyDesignableComponents = { foo: SpanType, bar: SpanType, baz: SpanType, }; type MyDesign = Design<MyDesignableComponents>; const Span: SpanType = props => <span {...props} />; const hoc = (newClassName: string):HOC => C => (props: any) => { const { className = '', ...rest } = props; const combinedClassName = `${className} ${newClassName}`.trim(); return <C className={combinedClassName} {...rest} />; }; const myStartComponents = { foo: Span as SpanType, bar: Span as SpanType, baz: Span as SpanType, }; const DesignPrinter: FC<DesignableProps<MyDesignableComponents>> = ({ design }) => { const components = { ...myStartComponents }; if (design) { if (design.foo) { components.foo = design.foo(components.foo); } if (design.bar) { components.bar = design.bar(components.bar); } if (design.baz) { components.baz = design.baz(components.baz); } } const Foo = components.foo; const Bar = components.bar; const Baz = components.baz; return ( <div> <Foo id="foo" /> <Bar id="bar" /> <Baz id="baz" /> </div> ); }; describe('extendDesignable', () => { const Test$: FC<any> = ({ design }: { design: { [key: string]: () => Function } }) => ( <span id="test"> {design ? Object.values(design).map(h => h()()) : 'no design'} </span> ); const design = { foo: () => () => <span key="foo">foo</span>, bar: () => () => <span key="bar">bar</span>, }; it('Passes a design through to an underlying component', () => { const Test = extendDesignable()({})(Test$); const wrapper = mount(<Test design={design} />); expect(wrapper.text()).toBe('foobar'); }); it('Strips the design when a transformer returns undefind', () => { const Test = extendDesignable(() => undefined)({})(Test$); const wrapper = mount(<Test design={design} />); expect(wrapper.text()).toBe('no design'); }); it('Removes keys from the design correctly', () => { const Test = extendDesignable((d: any) => omit(d, 'foo'))({})(Test$); const wrapper = mount(<Test design={design} />); expect(wrapper.text()).toBe('bar'); }); }); describe('withDesign', () => { it('applies a design correctly', () => { const inner: MyDesign = { foo: hoc('innerA'), bar: hoc('innerB'), }; const outer: MyDesign = { foo: hoc('outerC'), bar: hoc('outerD'), baz: hoc('outerE'), }; const Test = withDesign(inner)(DesignPrinter); const wrapper = mount(<Test />); expect(wrapper.find('#foo').last().props().className).toBe('innerA'); expect(wrapper.find('#bar').last().props().className).toBe('innerB'); const Test1 = withDesign(outer)(Test); const wrapper1 = mount(<Test1 />); // have to use last() because each hoc adds a component that is found expect(wrapper1.find('#foo').last().props().className).toBe('outerC innerA'); expect(wrapper1.find('#bar').last().props().className).toBe('outerD innerB'); expect(wrapper1.find('#baz').last().props().className).toBe('outerE'); }); }); describe('withFinalDesign', () => { it('Applies a final design finally', () => { type Components = { Foo: ComponentType<any>, }; const startComponents: Components = { Foo: (props: any) => <span id="foo" {...props} />, }; const Test$: FC<DesignableComponentsProps<Components>> = ( { components, ...rest }, ) => { const { Foo } = components; return <Foo {...rest} />; }; const baseDesign = { Foo: hoc('base') }; const nextDesign = { Foo: hoc('next') }; const innerFinal = { Foo: hoc('inner-final') }; const outerFinal = { Foo: hoc('outer-final') }; const Test = flow( designable(startComponents), withFinalDesign(innerFinal), withDesign(baseDesign), withFinalDesign(outerFinal), withDesign(nextDesign), )(Test$); const wrapper = mount(<Test />); expect(wrapper.find('span#foo').prop('className')) .toBe('outer-final inner-final next base'); }); }); describe('withShowDesignKeys', () => { const Base = ({ components }: any) => { const { Foo, Bar } = components; return <Foo><Bar /></Foo>; }; const startComponents = { Foo: (props: any) => <span id="foo" {...props} />, Bar: (props: any) => <span id="bar" {...props} />, }; it('Does not add design keys without withShowDesignKeys', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), )(Base); const wrapper = mount(<Test />); expect(wrapper.find('span#foo').prop('data-bl-design-key')).toBeUndefined(); }); it('Adds design keys when enabled', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), withShowDesignKeys(), )(Base); const wrapper = mount(<Test />); expect(wrapper.find('span#foo').prop('data-bl-design-key')).toBe('Base:Foo'); expect(wrapper.find('span#bar').prop('data-bl-design-key')).toBe('Base:Bar'); }); it('Does not add a design keys when disabled', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), withShowDesignKeys(false), )(Base); const wrapper = mount(<Test />); expect(wrapper.find('span#foo').prop('data-bl-design-key')).toBeUndefined(); expect(wrapper.find('span#bar').prop('data-bl-design-key')).toBeUndefined(); }); it('Rewrites default a componentName data attr', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), withShowDesignKeys(), )(Base); const AddDesignKeys = withShowDesignKeys(true, 'layer-region')(Fragment); const wrapper = mount(<AddDesignKeys><Test /></AddDesignKeys>); expect(wrapper.find('span#foo').prop('data-layer-region')).toBe('Base:Foo'); expect(wrapper.find('span#foo').prop('data-bl-design-key')).toBeUndefined(); }); it('Rewrites design keys via wrapper values', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), withShowDesignKeys(false, 'bl-design-key'), )(Base); const AddDesignKeys = withShowDesignKeys(true, 'layer-region')(Fragment); const wrapper = mount(<AddDesignKeys><Test /></AddDesignKeys>); expect(wrapper.find('span#foo').prop('data-layer-region')).toBe('Base:Foo'); expect(wrapper.find('span#foo').prop('data-bl-design-key')).toBeUndefined(); }); it('Adds design keys if component wrapped in withShowDesignKeys', () => { const Test: ComponentType<any> = flow( designable(startComponents, 'Base'), )(Base); const AddDesignKeys = withShowDesignKeys(true, 'test-attr')(Fragment); const wrapper = mount( <AddDesignKeys><Test /></AddDesignKeys>, ); expect(wrapper.find('span#foo').prop('data-test-attr')).toBe('Base:Foo'); }); describe('startWith', () => { const InnerBase = ({ components: C }: any) => ( <C.Component id="inner">Inner</C.Component> ); const Inner = designable({ Component: 'div' as any }, 'ProblemInner')( InnerBase, ); const OuterBase = ({ components: C }: any) => ( <C.Wrapper id="outer"> <Inner /> </C.Wrapper> ); const Outer = flow( designable({ Wrapper: 'div' as any }, 'Problem'), withDesign<any>({ Wrapper: startWith('h1' as any), }), )(OuterBase); it('Replaces a component with the outermost', () => { const Test = withDesign({ Component: flow( startWith('span' as any), startWith('section' as any), ) as HOC, })(Inner); const wrapper = mount(<Test />); expect(wrapper.find('div#inner')).toHaveLength(0); expect(wrapper.find('span#inner')).toHaveLength(0); expect(wrapper.find('section#inner')).toHaveLength(1); }); it('Replaces a component without altering a prior hoc', () => { const Test = withDesign({ Component: flow( (C: any) => (props: any) => <C {...props} foo="bar" />, startWith('span' as any), ), })(Inner); const wrapper = mount(<Test />); expect(wrapper.find('span#inner').prop('foo')).toEqual('bar'); }); it('Does not propagate a starting component to an inner design', () => { const wrapper = mount(<Outer />); expect(wrapper.find('h1#outer')).toHaveLength(1); expect(wrapper.find('h1#inner')).toHaveLength(0); expect(wrapper.find('div#inner')).toHaveLength(1); }); }); }); describe('replaceWith', () => { const Start = (props: any) => <div {...props} />; const Replacement = (props: any) => <span {...props} />; const Base = ({ components: C }: any) => ( <C.Component id="test" /> ); const TestDesignable = designable({ Component: Start }, 'ProblemInner')(Base); it('replaces a component', () => { let wrapper = mount(<TestDesignable />); expect(wrapper.find('div#test')).toHaveLength(1); const Test = withDesign({ Component: replaceWith(Replacement), })(TestDesignable); wrapper = mount(<Test />); expect(wrapper.find('div#test')).toHaveLength(0); expect(wrapper.find('span#test')).toHaveLength(1); }); it('erases previous hocs', () => { const TestBase = withDesign({ Component: (C: any) => (props: any) => <C {...props} foo="bar" />, })(TestDesignable); let wrapper = mount(<TestBase />); expect(wrapper.find('div#test').prop('foo')).toBe('bar'); const Test = withDesign({ Component: replaceWith(Replacement), })(TestBase); wrapper = mount(<Test />); expect(wrapper.find('span#test').prop('foo')).toBeUndefined(); }); it('Propagates metadata without altering the replacement.', () => { const Start$ = asToken({ title: 'Foo' })(Start); expect(Start$.title).toBe('Foo'); const Test = replaceWith(Replacement)(Start$); expect(Test.title).toBe('Foo'); // @ts-ignore expect(Replacement.title).toBeUndefined(); }); it('Can replace with a tag inside withdesign', () => { const Test = withDesign({ Component: replaceWith('span'), })(TestDesignable); const wrapper = mount(<Test />); expect(wrapper.find('div#test')).toHaveLength(0); expect(wrapper.find('span#test')).toHaveLength(1); }); });
the_stack
import { getCoreSystem, CoreSystem, SYSTEM_ID, getCoreSystemCursor, parseVersion, Version, parseRange, stripVersion, VersionRange, GENESIS_SYSTEM_VERSION, } from '../lib/collections/CoreSystem' import { getCurrentTime, unprotectString, waitForPromiseAll } from '../lib/lib' import { Meteor } from 'meteor/meteor' import { prepareMigration, runMigration } from './migration/databaseMigration' import { CURRENT_SYSTEM_VERSION } from './migration/currentSystemVersion' import { setSystemStatus, StatusCode, removeSystemStatus } from './systemStatus/systemStatus' import { Blueprints, Blueprint } from '../lib/collections/Blueprints' import * as _ from 'underscore' import { ShowStyleBases } from '../lib/collections/ShowStyleBases' import { Studios, StudioId } from '../lib/collections/Studios' import { logger } from './logging' import * as semver from 'semver' import { findMissingConfigs } from './api/blueprints/config' import { ShowStyleVariants } from '../lib/collections/ShowStyleVariants' import { syncFunction } from './codeControl' const PackageInfo = require('../package.json') import Agent from 'meteor/kschingiz:meteor-elastic-apm' import { profiler } from './api/profiler' import * as path from 'path' import { TMP_TSR_VERSION } from '@sofie-automation/blueprints-integration' import { createShowStyleCompound } from './api/showStyles' export { PackageInfo } function initializeCoreSystem() { let system = getCoreSystem() if (!system) { // At this point, we probably have a system that is as fresh as it gets let version = parseVersion(GENESIS_SYSTEM_VERSION) CoreSystem.insert({ _id: SYSTEM_ID, created: getCurrentTime(), modified: getCurrentTime(), version: version, previousVersion: null, storePath: '', // to be filled in later serviceMessages: {}, apm: { enabled: false, transactionSampleRate: -1, }, cron: { casparCGRestart: { enabled: true, }, }, }) // Check what migration has to provide: let migration = prepareMigration(true) if (migration.migrationNeeded && migration.manualStepCount === 0 && migration.chunks.length <= 1) { // Since we've determined that the migration can be done automatically, and we have a fresh system, just do the migration automatically: runMigration(migration.chunks, migration.hash, []) } } // Monitor database changes: let systemCursor = getCoreSystemCursor() systemCursor.observeChanges({ added: checkDatabaseVersions, changed: checkDatabaseVersions, removed: checkDatabaseVersions, }) const observeBlueprintChanges = () => { checkDatabaseVersions() queueCheckBlueprintsConfig() } const blueprintsCursor = Blueprints.find({}) blueprintsCursor.observeChanges({ added: observeBlueprintChanges, changed: observeBlueprintChanges, removed: observeBlueprintChanges, }) const studiosCursor = Studios.find({}) studiosCursor.observeChanges({ added: queueCheckBlueprintsConfig, changed: queueCheckBlueprintsConfig, removed: queueCheckBlueprintsConfig, }) const showStyleBaseCursor = ShowStyleBases.find({}) showStyleBaseCursor.observeChanges({ added: queueCheckBlueprintsConfig, changed: queueCheckBlueprintsConfig, removed: queueCheckBlueprintsConfig, }) const showStyleVariantCursor = ShowStyleVariants.find({}) showStyleVariantCursor.observeChanges({ added: queueCheckBlueprintsConfig, changed: queueCheckBlueprintsConfig, removed: queueCheckBlueprintsConfig, }) checkDatabaseVersions() } let lastDatabaseVersionBlueprintIds: { [id: string]: true } = {} function checkDatabaseVersions() { // Core system let databaseSystem = getCoreSystem() if (!databaseSystem) { setSystemStatus('databaseVersion', { statusCode: StatusCode.BAD, messages: ['Database not set up'] }) } else { let dbVersion = databaseSystem.version ? parseVersion(databaseSystem.version) : null let currentVersion = parseVersion(CURRENT_SYSTEM_VERSION) setSystemStatus( 'databaseVersion', checkDatabaseVersion(currentVersion, dbVersion, 'to fix, run migration', 'core', 'system database') ) // Blueprints: let blueprintIds: { [id: string]: true } = {} Blueprints.find().forEach((blueprint) => { if (blueprint.code) { blueprintIds[unprotectString(blueprint._id)] = true // @ts-ignore if (!blueprint.databaseVersion || _.isString(blueprint.databaseVersion)) blueprint.databaseVersion = {} if (!blueprint.databaseVersion.showStyle) blueprint.databaseVersion.showStyle = {} if (!blueprint.databaseVersion.studio) blueprint.databaseVersion.studio = {} let o: { statusCode: StatusCode messages: string[] } = { statusCode: StatusCode.BAD, messages: [], } let studioIds: { [studioId: string]: true } = {} ShowStyleBases.find({ blueprintId: blueprint._id, }).forEach((showStyleBase) => { if (o.statusCode === StatusCode.GOOD) { o = checkDatabaseVersion( blueprint.blueprintVersion ? parseVersion(blueprint.blueprintVersion) : null, parseRange( blueprint.databaseVersion.showStyle[unprotectString(showStyleBase._id)] || '0.0.0' ), 'to fix, run migration', 'blueprint.blueprintVersion', `databaseVersion.showStyle[${showStyleBase._id}]` ) } // TODO - is this correct for the current relationships? What about studio blueprints? Studios.find({ supportedShowStyleBase: showStyleBase._id, }).forEach((studio) => { if (!studioIds[unprotectString(studio._id)]) { // only run once per blueprint and studio studioIds[unprotectString(studio._id)] = true if (o.statusCode === StatusCode.GOOD) { o = checkDatabaseVersion( blueprint.blueprintVersion ? parseVersion(blueprint.blueprintVersion) : null, parseRange( blueprint.databaseVersion.studio[unprotectString(studio._id)] || '0.0.0' ), 'to fix, run migration', 'blueprint.blueprintVersion', `databaseVersion.studio[${studio._id}]` ) } } }) }) checkBlueprintCompability(blueprint) } }) _.each(lastDatabaseVersionBlueprintIds, (_val, id: string) => { if (!blueprintIds[id]) { removeSystemStatus('blueprintVersion_' + id) } }) lastDatabaseVersionBlueprintIds = blueprintIds } } /** * Compares two versions and returns a system Status * @param currentVersion * @param dbVersion */ function checkDatabaseVersion( currentVersion: Version | null, expectVersion: VersionRange | null, fixMessage: string, meName: string, theyName: string ): { statusCode: StatusCode; messages: string[] } { if (currentVersion) currentVersion = semver.clean(currentVersion) if (expectVersion) { if (currentVersion) { if (semver.satisfies(currentVersion, expectVersion)) { return { statusCode: StatusCode.GOOD, messages: [`${meName} version: ${currentVersion}`], } } else { const currentV = new semver.SemVer(currentVersion, { includePrerelease: true }) try { const expectV = new semver.SemVer(stripVersion(expectVersion), { includePrerelease: true }) const message = `Version mismatch: ${meName} version: "${currentVersion}" does not satisfy expected version of ${theyName}: "${expectVersion}"` + (fixMessage ? ` (${fixMessage})` : '') if (!expectV || !currentV) { return { statusCode: StatusCode.BAD, messages: [message], } } else if (expectV.major !== currentV.major) { return { statusCode: StatusCode.BAD, messages: [message], } } else if (expectV.minor !== currentV.minor) { return { statusCode: StatusCode.WARNING_MAJOR, messages: [message], } } else if (expectV.patch !== currentV.patch) { return { statusCode: StatusCode.WARNING_MINOR, messages: [message], } } else if (!_.isEqual(expectV.prerelease, currentV.prerelease)) { return { statusCode: StatusCode.WARNING_MINOR, messages: [message], } } else { return { statusCode: StatusCode.BAD, messages: [message], } } // the expectedVersion may be a proper range, in which case the new semver.SemVer will throw an error, even though the semver.satisfies check would work. } catch (e) { const message = `Version mismatch: ${meName} version: "${currentVersion}" does not satisfy expected version range of ${theyName}: "${expectVersion}"` + (fixMessage ? ` (${fixMessage})` : '') return { statusCode: StatusCode.BAD, messages: [message], } } } } else { return { statusCode: StatusCode.FATAL, messages: [`Current ${meName} version missing (when comparing with ${theyName})`], } } } else { return { statusCode: StatusCode.FATAL, messages: [`Expected ${theyName} version missing (when comparing with ${meName})`], } } } function checkBlueprintCompability(blueprint: Blueprint) { if (!PackageInfo.dependencies) throw new Meteor.Error(500, `Package.dependencies not set`) const systemStatusId = 'blueprintCompability_' + blueprint._id const systemVersions = getRelevantSystemVersions() const integrationStatus = checkDatabaseVersion( parseVersion(blueprint.integrationVersion || '0.0.0'), parseRange('~' + PackageInfo.version), 'Blueprint has to be updated', 'blueprint.integrationVersion', 'core.@sofie-automation/blueprints-integration' ) const tsrStatus = checkDatabaseVersion( parseVersion(blueprint.TSRVersion || '0.0.0'), parseRange('~' + systemVersions['timeline-state-resolver-types']), 'Blueprint has to be updated', 'blueprint.TSRVersion', 'core.timeline-state-resolver-types' ) if (integrationStatus.statusCode >= StatusCode.WARNING_MAJOR) { integrationStatus.messages[0] = 'Integration version: ' + integrationStatus.messages[0] setSystemStatus(systemStatusId, integrationStatus) } else if (tsrStatus && tsrStatus.statusCode >= StatusCode.WARNING_MAJOR) { tsrStatus.messages[0] = 'Core - TSR library version: ' + tsrStatus.messages[0] setSystemStatus(systemStatusId, tsrStatus) } else { setSystemStatus(systemStatusId, { statusCode: StatusCode.GOOD, messages: ['Versions match'], }) } } let checkBlueprintsConfigTimeout: number | undefined function queueCheckBlueprintsConfig() { const RATE_LIMIT = 10000 // We want to rate limit this. It doesn't matter if it is delayed, so lets do that to keep it simple if (!checkBlueprintsConfigTimeout) { checkBlueprintsConfigTimeout = Meteor.setTimeout(() => { checkBlueprintsConfigTimeout = undefined checkBlueprintsConfig() }, RATE_LIMIT) } } let lastBlueprintConfigIds: { [id: string]: true } = {} const checkBlueprintsConfig = syncFunction(function checkBlueprintsConfig() { let blueprintIds: { [id: string]: true } = {} // Studios _.each(Studios.find({}).fetch(), (studio) => { const blueprint = Blueprints.findOne(studio.blueprintId) if (!blueprint) return const diff = findMissingConfigs(blueprint.studioConfigManifest, studio.blueprintConfig) const systemStatusId = `blueprintConfig_${blueprint._id}_studio_${studio._id}` setBlueprintConfigStatus(systemStatusId, diff, studio._id) blueprintIds[systemStatusId] = true }) // ShowStyles _.each(ShowStyleBases.find({}).fetch(), (showBase) => { const blueprint = Blueprints.findOne(showBase.blueprintId) if (!blueprint || !blueprint.showStyleConfigManifest) return const variants = ShowStyleVariants.find({ showStyleBaseId: showBase._id, }).fetch() const allDiffs: string[] = [] _.each(variants, (variant) => { const compound = createShowStyleCompound(showBase, variant) if (!compound) return const diff = findMissingConfigs(blueprint.showStyleConfigManifest, compound.blueprintConfig) if (diff && diff.length) { allDiffs.push(`Variant ${variant._id}: ${diff.join(', ')}`) } }) const systemStatusId = `blueprintConfig_${blueprint._id}_showStyle_${showBase._id}` setBlueprintConfigStatus(systemStatusId, allDiffs) blueprintIds[systemStatusId] = true }) // Check for removed _.each(lastBlueprintConfigIds, (_val, id: string) => { if (!blueprintIds[id]) { removeSystemStatus(id) } }) lastBlueprintConfigIds = blueprintIds }, 'checkBlueprintsConfig') function setBlueprintConfigStatus(systemStatusId: string, diff: string[], studioId?: StudioId) { if (diff && diff.length > 0) { setSystemStatus(systemStatusId, { studioId: studioId, statusCode: StatusCode.WARNING_MAJOR, messages: [`Config is missing required fields: ${diff.join(', ')}`], }) } else { setSystemStatus(systemStatusId, { studioId: studioId, statusCode: StatusCode.GOOD, messages: ['Config is valid'], }) } } let SYSTEM_VERSIONS: { [name: string]: string } | undefined export function getRelevantSystemVersions(): { [name: string]: string } { if (SYSTEM_VERSIONS) { return SYSTEM_VERSIONS } const versions: { [name: string]: string } = {} let dependencies: any = PackageInfo.dependencies if (dependencies) { const libNames: string[] = ['mos-connection', 'superfly-timeline'] const sanitizeVersion = (v: string) => { if (v.match(/git/i) || v.match(/file:../i)) { return '0.0.0' } else { return v } } const getRealVersion = async (name: string, fallback: string): Promise<string> => { try { const pkgInfo = require(name + '/package.json') return pkgInfo.version } catch (e) { logger.warn(`Failed to read version of package "${name}": ${e}`) return sanitizeVersion(fallback) } } waitForPromiseAll([ ...libNames.map(async (name) => { versions[name] = await getRealVersion(name, dependencies[name]) }), ]) versions['core'] = PackageInfo.versionExtended || PackageInfo.version // package version versions['timeline-state-resolver-types'] = TMP_TSR_VERSION } else { logger.error(`Core package dependencies missing`) } SYSTEM_VERSIONS = versions return versions } function startupMessage() { if (!Meteor.isTest) { console.log('process started') // This is a message all Sofie processes log upon startup logger.info(`Core starting up`) logger.info(`Core system version: "${CURRENT_SYSTEM_VERSION}"`) // @ts-ignore if (global.gc) { logger.info(`Manual garbage-collection is enabled`) } else { logger.warn( `Enable garbage-collection by passing --expose_gc to node in prod or set SERVER_NODE_OPTIONS=--expose_gc in dev` ) } const versions = getRelevantSystemVersions() _.each(versions, (version, name) => { logger.info(`Core package ${name} version: "${version}"`) }) } } function startInstrumenting() { if (!!process.env.JEST_WORKER_ID) { return } // attempt init elastic APM const system = getCoreSystem() const { APM_HOST, APM_SECRET, KIBANA_INDEX, APP_HOST } = process.env if (APM_HOST && system && system.apm) { logger.info(`APM agent starting up`) Agent.start({ serviceName: KIBANA_INDEX || 'tv-automation-server-core', hostname: APP_HOST, serverUrl: APM_HOST, secretToken: APM_SECRET, active: system.apm.enabled, transactionSampleRate: system.apm.transactionSampleRate, disableMeteorInstrumentations: ['methods', 'http-out', 'session', 'async', 'metrics'], }) profiler.setActive(system.apm.enabled || false) } else { logger.info(`APM agent inactive`) Agent.start({ serviceName: 'tv-automation-server-core', active: false, disableMeteorInstrumentations: ['methods', 'http-out', 'session', 'async', 'metrics'], }) } } Meteor.startup(() => { if (Meteor.isServer) { startupMessage() initializeCoreSystem() startInstrumenting() } })
the_stack
import {Sprite, SpriteMesh} from '../sprite-mesh'; const {expect} = chai; describe('SpriteMesh', () => { describe('constructor', () => { it('should create empty state when constructed', () => { const spriteMesh = new SpriteMesh(1); expect(spriteMesh.spriteWidth).to.equal(1); expect(spriteMesh.spriteHeight).to.equal(1); expect(spriteMesh.positionData.length).to.equal(12); expect(spriteMesh.colorData.length).to.equal(16); expect(spriteMesh.faceIndexData).to.deep.equal(Uint32Array.from([ 0, 1, 2, 0, 2, 3 ])); expect(spriteMesh.vertexIndexData).to.deep.equal(Float32Array.from([ 0, 1, 2, 3 ])); expect(spriteMesh.opacityData).to.deep.equal(Float32Array.from([ 0, 0, 0, 0 ])); }); }); describe('createSprite', () => { it('should produce new Sprites on request', () => { const spriteMesh = new SpriteMesh(2); const firstSprite = spriteMesh.createSprite(); expect(firstSprite.spriteMesh).to.equal(spriteMesh); expect(firstSprite.spriteIndex).to.equal(0); const secondSprite = spriteMesh.createSprite(); expect(secondSprite.spriteMesh).to.equal(spriteMesh); expect(secondSprite.spriteIndex).to.equal(1); }); }); describe('direct attribute setters', () => { it('should reflect setting positions in buffer data', () => { const spriteMesh = new SpriteMesh(2); spriteMesh.setX(0, 4); spriteMesh.setY(0, 6); spriteMesh.setZ(0, 8); spriteMesh.setX(1, 10); spriteMesh.setY(1, 12); spriteMesh.setZ(1, 14); expect(spriteMesh.positionData).to.deep.equal(Float32Array.from([ // First Sprite. 4, 6, 8, // A 5, 6, 8, // B 5, 7, 8, // C 4, 7, 8, // D // Second Sprite. 10, 12, 14, // A 11, 12, 14, // B 11, 13, 14, // C 10, 13, 14, // D ])); }); it('should reflect setting colors in buffer data', () => { const spriteMesh = new SpriteMesh(2); spriteMesh.setR(0, 100); spriteMesh.setG(0, 110); spriteMesh.setB(0, 120); spriteMesh.setA(0, 130); spriteMesh.setR(1, 200); spriteMesh.setG(1, 210); spriteMesh.setB(1, 220); spriteMesh.setA(1, 230); expect(spriteMesh.colorData).to.deep.equal(Uint8Array.from([ // First Sprite. 100, 110, 120, 130, // A 100, 110, 120, 130, // B 100, 110, 120, 130, // C 100, 110, 120, 130, // D // Second Sprite. 200, 210, 220, 230, // A 200, 210, 220, 230, // B 200, 210, 220, 230, // C 200, 210, 220, 230, // D ])); }); it('should reflect setting opacity in buffer data', () => { const spriteMesh = new SpriteMesh(2); spriteMesh.setOpacity(0, 0.25); spriteMesh.setOpacity(1, 0.75); expect(spriteMesh.opacityData).to.deep.equal(Float32Array.from([ // First Sprite. 0.25, 0.25, 0.25, 0.25, // ABCD // Second Sprite. 0.75, 0.75, 0.75, 0.75, // ABCD ])); }); it('should reflect setting timestamp in buffer data', () => { const spriteMesh = new SpriteMesh(2); // Vertex timestamps are relative to the mesh's construction timestamp. spriteMesh.setTimestamp(0, 10 + spriteMesh.constructionTimestamp); spriteMesh.setTimestamp(1, 20 + spriteMesh.constructionTimestamp); expect(spriteMesh.timestampData).to.deep.equal(Float32Array.from([ // First Sprite. 10, 10, 10, 10, // ABCD // Second Sprite. 20, 20, 20, 20, // ABCD ])); }); }); describe('sprite attribute setters', () => { it('should reflect setting positions in buffer data', () => { const spriteMesh = new SpriteMesh(2); const firstSprite = spriteMesh.createSprite(); const secondSprite = spriteMesh.createSprite(); firstSprite.x = 4; firstSprite.y = 6; firstSprite.z = 8; secondSprite.x = 10; secondSprite.y = 12; secondSprite.z = 14; expect(spriteMesh.positionData).to.deep.equal(Float32Array.from([ // First Sprite. 4, 6, 8, // A 5, 6, 8, // B 5, 7, 8, // C 4, 7, 8, // D // Second Sprite. 10, 12, 14, // A 11, 12, 14, // B 11, 13, 14, // C 10, 13, 14, // D ])); }); it('should reflect setting colors in buffer data', () => { const spriteMesh = new SpriteMesh(2); const firstSprite = spriteMesh.createSprite(); const secondSprite = spriteMesh.createSprite(); firstSprite.r = 100; firstSprite.g = 110; firstSprite.b = 120; firstSprite.a = 130; secondSprite.r = 200; secondSprite.g = 210; secondSprite.b = 220; secondSprite.a = 230; expect(spriteMesh.colorData).to.deep.equal(Uint8Array.from([ // First Sprite. 100, 110, 120, 130, // A 100, 110, 120, 130, // B 100, 110, 120, 130, // C 100, 110, 120, 130, // D // Second Sprite. 200, 210, 220, 230, // A 200, 210, 220, 230, // B 200, 210, 220, 230, // C 200, 210, 220, 230, // D ])); }); it('should reflect setting opacity in buffer data', () => { const spriteMesh = new SpriteMesh(2); const firstSprite = spriteMesh.createSprite(); const secondSprite = spriteMesh.createSprite(); firstSprite.opacity = 0.25; secondSprite.opacity = 0.75; expect(spriteMesh.opacityData).to.deep.equal(Float32Array.from([ // First Sprite. 0.25, 0.25, 0.25, 0.25, // ABCD // Second Sprite. 0.75, 0.75, 0.75, 0.75, // ABCD ])); }); it('should reflect setting timestamp in buffer data', () => { const spriteMesh = new SpriteMesh(2); const firstSprite = spriteMesh.createSprite(); const secondSprite = spriteMesh.createSprite(); firstSprite.timestamp = 10 + spriteMesh.constructionTimestamp; secondSprite.timestamp = 20 + spriteMesh.constructionTimestamp; expect(spriteMesh.timestampData).to.deep.equal(Float32Array.from([ // First Sprite. 10, 10, 10, 10, // ABCD // Second Sprite. 20, 20, 20, 20, // ABCD ])); }); }); describe('rebase', () => { it('should reflect rebased values in base attributes', () => { const spriteMesh = new SpriteMesh(1); const sprite = spriteMesh.createSprite(); sprite.x = 10; sprite.y = 10; sprite.z = 10; sprite.r = 100; sprite.g = 100; sprite.b = 100; sprite.a = 100; sprite.opacity = 1; sprite.timestamp = 1000 + spriteMesh.constructionTimestamp; expect(spriteMesh.getBaseX(0)).to.equal(0); expect(spriteMesh.getBaseY(0)).to.equal(0); expect(spriteMesh.getBaseZ(0)).to.equal(0); expect(spriteMesh.getBaseR(0)).to.equal(0); expect(spriteMesh.getBaseG(0)).to.equal(0); expect(spriteMesh.getBaseB(0)).to.equal(0); expect(spriteMesh.getBaseA(0)).to.equal(0); expect(spriteMesh.getBaseOpacity(0)).to.equal(0); expect(spriteMesh.getBaseTimestamp(0)) .to.equal(spriteMesh.constructionTimestamp); sprite.rebase(500 + spriteMesh.constructionTimestamp); expect(spriteMesh.getBaseX(0)).to.equal(5); expect(spriteMesh.getBaseY(0)).to.equal(5); expect(spriteMesh.getBaseZ(0)).to.equal(5); expect(spriteMesh.getBaseR(0)).to.equal(50); expect(spriteMesh.getBaseG(0)).to.equal(50); expect(spriteMesh.getBaseB(0)).to.equal(50); expect(spriteMesh.getBaseA(0)).to.equal(50); expect(spriteMesh.getBaseOpacity(0)).to.equal(0.5); expect(spriteMesh.getBaseTimestamp(0)) .to.equal(500 + spriteMesh.constructionTimestamp); sprite.rebase(1000 + spriteMesh.constructionTimestamp); expect(spriteMesh.getBaseX(0)).to.equal(10); expect(spriteMesh.getBaseY(0)).to.equal(10); expect(spriteMesh.getBaseZ(0)).to.equal(10); expect(spriteMesh.getBaseR(0)).to.equal(100); expect(spriteMesh.getBaseG(0)).to.equal(100); expect(spriteMesh.getBaseB(0)).to.equal(100); expect(spriteMesh.getBaseA(0)).to.equal(100); expect(spriteMesh.getBaseOpacity(0)).to.equal(1); expect(spriteMesh.getBaseTimestamp(0)) .to.equal(1000 + spriteMesh.constructionTimestamp); sprite.rebase(2000 + spriteMesh.constructionTimestamp); expect(spriteMesh.getBaseTimestamp(0)) .to.equal(2000 + spriteMesh.constructionTimestamp); }); }); describe('findSprites', () => { const spriteMesh = new SpriteMesh(4); spriteMesh.setX(0, 4); spriteMesh.setY(0, 6); spriteMesh.setZ(0, 8); spriteMesh.setX(1, -14); spriteMesh.setY(1, -12); spriteMesh.setZ(1, -10); spriteMesh.setX(2, 40); spriteMesh.setY(2, 40); spriteMesh.setZ(2, 0); spriteMesh.setX(3, 40); spriteMesh.setY(3, 40); spriteMesh.setZ(3, 0); it('should find matching sprites', () => { expect(spriteMesh.findSprites(4, 6)).to.deep.equal([0]); expect(spriteMesh.findSprites(4, 6.5)).to.deep.equal([0]); expect(spriteMesh.findSprites(4, 7)).to.deep.equal([0]); expect(spriteMesh.findSprites(4.5, 6)).to.deep.equal([0]); expect(spriteMesh.findSprites(4.5, 6.5)).to.deep.equal([0]); expect(spriteMesh.findSprites(4.5, 7)).to.deep.equal([0]); expect(spriteMesh.findSprites(5, 6)).to.deep.equal([0]); expect(spriteMesh.findSprites(5, 6.5)).to.deep.equal([0]); expect(spriteMesh.findSprites(5, 7)).to.deep.equal([0]); expect(spriteMesh.findSprites(-14, -12)).to.deep.equal([1]); expect(spriteMesh.findSprites(-14, -11.5)).to.deep.equal([1]); expect(spriteMesh.findSprites(-14, -11)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13.5, -12)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13.5, -11.5)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13.5, -11)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13, -12)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13, -11.5)).to.deep.equal([1]); expect(spriteMesh.findSprites(-13, -11)).to.deep.equal([1]); }); it('should find overlapping sprites', () => { expect(spriteMesh.findSprites(40, 40)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(40, 40.5)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(40, 41)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(40.5, 40)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(40.5, 40.5)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(40.5, 41)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(41, 40)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(41, 40.5)).to.deep.equal([2, 3]); expect(spriteMesh.findSprites(41, 41)).to.deep.equal([2, 3]); }); it('should not find non-matching sprites', () => { expect(spriteMesh.findSprites(0, 0)).to.deep.equal([]); expect(spriteMesh.findSprites(3.5, 6.5)).to.deep.equal([]); expect(spriteMesh.findSprites(5.5, 6.5)).to.deep.equal([]); expect(spriteMesh.findSprites(4.5, 7.5)).to.deep.equal([]); expect(spriteMesh.findSprites(4.5, 5.5)).to.deep.equal([]); expect(spriteMesh.findSprites(-14.5, -11.5)).to.deep.equal([]); expect(spriteMesh.findSprites(-12.5, -11.5)).to.deep.equal([]); expect(spriteMesh.findSprites(-13.5, -12.5)).to.deep.equal([]); expect(spriteMesh.findSprites(-13.5, -10.5)).to.deep.equal([]); }); }); });
the_stack
import type { IAnimation } from "./util/Animation"; import type { Entity } from "./util/Entity"; import type { Sprite } from "./render/Sprite"; import type { Text } from "./render/Text"; import type { Theme } from "./Theme"; import type { IPoint } from "./util/IPoint"; import type { IRenderer } from "./render/backend/Renderer"; import { Container } from "./render/Container"; import { HorizontalLayout } from "./render/HorizontalLayout"; import { VerticalLayout } from "./render/VerticalLayout"; import { GridLayout } from "./render/GridLayout"; import { IDisposer, Disposer } from "./util/Disposer"; import { ResizeSensor } from "./util/ResizeSensor"; import { InterfaceColors } from "./util/InterfaceColors"; import { Graphics } from "./render/Graphics"; import { Rectangle } from "./render/Rectangle"; import { Tooltip } from "./render/Tooltip"; import { NumberFormatter } from "./util/NumberFormatter"; import { DateFormatter } from "./util/DateFormatter"; import { DurationFormatter } from "./util/DurationFormatter"; import { ILocale, Language } from "./util/Language"; import { Events, EventDispatcher } from "./util/EventDispatcher"; import { DefaultTheme } from "../themes/DefaultTheme"; import { CanvasRenderer } from "./render/backend/CanvasRenderer"; import { p100, percent } from "./util/Percent"; import { color } from "./util/Color"; import { populateString } from "./util/PopulateString"; import { registry } from "./Registry"; import * as $order from "./util/Order"; import * as $array from "./util/Array"; import * as $object from "./util/Object"; import * as $utils from "./util/Utils"; import en from "../../locales/en"; function rAF(fps: number | undefined, callback: (currentTime: number) => void): void { if (fps == null) { requestAnimationFrame(callback); } else { setTimeout(() => { requestAnimationFrame(callback); }, 1000 / fps); } } /** * @ignore */ interface IParent extends Entity { _prepareChildren(): void; _updateChildren(): void; } interface IBounds extends Entity { depth(): number; _updateBounds(): void; } export interface IRootEvents { framestarted: { timestamp: number; }; frameended: { timestamp: number; }; } // TODO implement Disposer /** * Root element of the chart. * * @see {@link https://www.amcharts.com/docs/v5/getting-started/#Root_element} for more info */ export class Root implements IDisposer { /** * A reference to original chart container (div element). */ public dom: HTMLElement; public _inner: HTMLElement; protected _isDirty: boolean = false; protected _isDirtyParents: boolean = false; protected _dirty: { [id: number]: Entity } = {}; protected _dirtyParents: { [id: number]: IParent } = {}; protected _dirtyBounds: { [id: number]: IBounds } = {}; protected _dirtyPositions: { [id: number]: Sprite } = {}; protected _ticker: ((currentTime: number) => void) | null = null; protected _tickers: Array<(currentTime: number) => void> = []; /** * Root's event dispatcher. * * @see {@link https://www.amcharts.com/docs/v5/concepts/events/} for more info */ public events: EventDispatcher<Events<this, IRootEvents>> = new EventDispatcher(); /** * @todo needs description */ public animationTime: number | null = null; private _animations: Array<IAnimation> = []; public _renderer: IRenderer = new CanvasRenderer(); public _rootContainer!: Container; /** * Main content container. */ public container!: Container; /** * A [[Container]] used to display tooltips in. */ public tooltipContainer!: Container public _tooltip!: Tooltip; // Locale-related /** * @ignore */ public language: Language = Language.new(this, {}); /** * Locale used by the chart. * * @see {@link https://www.amcharts.com/docs/v5/concepts/locales/} */ public locale: ILocale = en; // Date-time related /** * Use UTC when formatting date/time. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-dates/#UTC_and_time_zones} for more info */ public utc: boolean = false; /** * Use specific time zone when formatting date/time. * * @ignore timezones are not yet supported */ public timezone: string | null = null; /** * The maximum FPS that the Root will run at. * * If `undefined` it will run at the highest FPS. */ public fps: number | undefined; /** * Number formatter. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-numbers/} for more info */ public numberFormatter: NumberFormatter = NumberFormatter.new(this, {}); /** * Date/time formatter. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-dates/} for more info */ public dateFormatter: DateFormatter = DateFormatter.new(this, {}); /** * Duration formatter. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-dates/} for more info */ public durationFormatter: DurationFormatter = DurationFormatter.new(this, {}); // Accessibility /** * Global tab index for using for the whole chart * * @see {@link https://www.amcharts.com/docs/v5/concepts/accessibility/} for more info */ public tabindex: number = 0; //@todo maybe make this better protected _tabindexes: Sprite[] = []; protected _focusElementDirty: boolean = false; protected _focusElementContainer: HTMLDivElement | undefined; protected _focusedSprite: Sprite | undefined; protected _keyboardDragPoint: IPoint | undefined; protected _tooltipElementContainer: HTMLDivElement | undefined; protected _readerAlertElement: HTMLDivElement | undefined; public _logo?: Container; /** * Used for dynamically-created CSS and JavaScript with strict source policies. */ public nonce?: string; /** * Special color set to be used for various controls. * * @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/#Interface_colors} for more info */ public interfaceColors: InterfaceColors; /** * An instance of vertical layout object that can be used to set `layout` setting * of a [[Container]]. * * @default VerticalLayout.new() */ public verticalLayout: VerticalLayout = VerticalLayout.new(this, {}); /** * An instance of horizontal layout object that can be used to set `layout` setting * of a [[Container]]. * * @default HorizontalLayout.new() */ public horizontalLayout: VerticalLayout = HorizontalLayout.new(this, {}); /** * An instance of grid layout object that can be used to set `layout` setting * of a [[Container]]. * * @default VerticalLayout.new() */ public gridLayout: VerticalLayout = GridLayout.new(this, {}); /** * Indicates whether chart should resized automatically when parent container * width and/or height changes. * * If disabled (`autoResize = false`) you can make the chart resize manually * by calling root element's `resize()` method. */ public autoResize: boolean = true; protected _isDisposed: boolean = false; protected _disposers: Array<IDisposer> = []; protected _resizeSensorDisposer?: IDisposer; public _tooltips: Array<Tooltip> = []; protected constructor(id: string | HTMLElement, isReal: boolean) { if (!isReal) { throw new Error("You cannot use `new Class()`, instead use `Class.new()`"); } let dom: HTMLElement | null; if (id instanceof HTMLElement) { dom = id; } else { dom = document.getElementById(id); } $array.each(registry.rootElements, (root) => { if (root.dom === dom) { throw new Error("You cannot have multiple Roots on the same DOM node"); } }); this.interfaceColors = InterfaceColors.new(this, {}); if (dom === null) { throw new Error("Could not find HTML element with id `" + id + "`"); } this.dom = dom; let inner: HTMLDivElement = document.createElement("div"); inner.style.position = "relative"; dom.appendChild(inner); this._inner = inner; registry.rootElements.push(this); } public static new(id: string | HTMLElement): Root { const root = new Root(id, true); root._init(); return root; } public moveDOM(id: string | HTMLElement): void { let dom: HTMLElement | null; if (id instanceof HTMLElement) { dom = id; } else { dom = document.getElementById(id); } if (dom) { while (this.dom.childNodes.length > 0) { dom.appendChild(this.dom.childNodes[0]); } this.dom = dom; this._initResizeSensor(); this.resize(); } } protected _handleLogo(): void { if (this._logo) { if (this._rootContainer.getPrivate("width", 0) <= 150 || this._rootContainer.getPrivate("height", 0) <= 60) { this._logo.hide(); } else { this._logo.show(); } } } public _showBranding(): void { if (!this._logo) { const logo = this.tooltipContainer.children.push(Container.new(this, { interactive: true, interactiveChildren: false, position: "absolute", setStateOnChildren: true, paddingTop: 9, paddingRight: 9, paddingBottom: 9, paddingLeft: 9, scale: .6, y: percent(100), centerY: p100, tooltipText: "Created using amCharts 5", tooltipX: p100, cursorOverStyle: "pointer", background: Rectangle.new(this, { fill: color(0x474758), fillOpacity: 0, tooltipY: 5 }) })); const tooltip = Tooltip.new(this, { pointerOrientation: "horizontal", paddingTop: 4, paddingRight: 7, paddingBottom: 4, paddingLeft: 7 }); tooltip.label.setAll({ fontSize: 12 }); tooltip.get("background")!.setAll({ fill: this.interfaceColors.get("background"), stroke: this.interfaceColors.get("grid"), strokeOpacity: 0.3 }) logo.set("tooltip", tooltip); logo.events.on("click", () => { window.open("https://www.amcharts.com/", "_blank"); }); logo.states.create("hover", {}); const m = logo.children.push(Graphics.new(this, { stroke: color(0xcccccc), strokeWidth: 3, svgPath: "M5 25 L13 25h13.6c3.4 0 6 0 10.3-4.3s5.2-12 8.6-12c3.4 0 4.3 8.6 7.7 8.6M83.4 25H79.8c-3.4 0-6 0-10.3-4.3s-5.2-12-8.6-12-4.3 8.6-7.7 8.6" })); m.states.create("hover", { stroke: color(0x3CABFF) }); const a = logo.children.push(Graphics.new(this, { stroke: color(0x888888), strokeWidth: 3, svgPath: "M83.4 25h-31C37 25 39.5 4.4 28.4 4.4S18.9 24.2 4.3 25H0" })); a.states.create("hover", { stroke: color(0x474758) }); //logo.set("tooltip", this._tooltip); //logo.setPrivate("tooltipTarget", logo.get("background")); this._logo = logo; this._handleLogo(); } } protected _init(): void { const renderer = this._renderer; const rootContainer = Container.new(this, { visible: true, width: this.dom.clientWidth, height: this.dom.clientHeight }); this._rootContainer = rootContainer; this._rootContainer._defaultThemes.push(DefaultTheme.new(this)); const container = rootContainer.children.push(Container.new(this, { visible: true, width: p100, height: p100 })); this.container = container; renderer.resize(this.dom.clientWidth, this.dom.clientHeight); //@todo: better appendChild - refer this._inner.appendChild(renderer.view); // TODO: TMP TMP TMP for testing only, remove //document.body.appendChild((<any>renderer)._ghostView); this._initResizeSensor(); // Create element which is used to make announcements to screen reader const readerAlertElement = document.createElement("div"); readerAlertElement.setAttribute("role", "alert"); readerAlertElement.style.zIndex = "-100000"; readerAlertElement.style.opacity = "0"; readerAlertElement.style.position = "absolute"; readerAlertElement.style.top = "0"; this._readerAlertElement = readerAlertElement; this._inner.appendChild(this._readerAlertElement); const focusElementContainer = document.createElement("div"); focusElementContainer.style.position = "absolute"; focusElementContainer.style.pointerEvents = "none"; focusElementContainer.style.top = "0px"; focusElementContainer.style.left = "0px"; focusElementContainer.style.overflow = "hidden"; focusElementContainer.style.width = this.dom.clientWidth + "px"; focusElementContainer.style.height = this.dom.clientHeight + "px"; focusElementContainer.setAttribute("role", "application"); $utils.setInteractive(focusElementContainer, false); this._focusElementContainer = focusElementContainer; this._inner.appendChild(this._focusElementContainer); this._tooltipElementContainer = document.createElement("div"); this._inner.appendChild(this._tooltipElementContainer); // Add keyboard events for accessibility, e.g. simulating drag with arrow // keys and click with ENTER if ($utils.supports("keyboardevents")) { this._disposers.push($utils.addEventListener(focusElementContainer, "keydown", (ev: KeyboardEvent) => { const focusedSprite = this._focusedSprite; if (focusedSprite) { if (ev.keyCode == 27) { // ESC pressed - lose current focus $utils.blur(); this._focusedSprite = undefined; } let dragOffsetX = 0; let dragOffsetY = 0; // TODO: figure out if using bogus MouseEvent is fine, or it will // fail on some platforms switch (ev.keyCode) { case 13: ev.preventDefault(); const downEvent = renderer.getEvent(new MouseEvent("click")); focusedSprite.events.dispatch("click", { type: "click", originalEvent: downEvent.event, point: downEvent.point, simulated: true, target: focusedSprite }); return; case 37: dragOffsetX = -6; break; case 39: dragOffsetX = 6; break; case 38: dragOffsetY = -6; break; case 40: dragOffsetY = 6; break; default: return; } if (dragOffsetX != 0 || dragOffsetY != 0) { ev.preventDefault(); if (!focusedSprite.isDragging()) { // Start dragging this._keyboardDragPoint = { x: 0, y: 0 } const downEvent = renderer.getEvent(new MouseEvent("mousedown", { clientX: 0, clientY: 0 })); if (focusedSprite.events.isEnabled("pointerdown")) { focusedSprite.events.dispatch("pointerdown", { type: "pointerdown", originalEvent: downEvent.event, point: downEvent.point, simulated: true, target: focusedSprite }); } } else { // Move focus marker //this._positionFocusElement(focusedSprite); } // Move incrementally const dragPoint = this._keyboardDragPoint!; dragPoint.x += dragOffsetX; dragPoint.y += dragOffsetY; const moveEvent = renderer.getEvent(new MouseEvent("mousemove", { clientX: dragPoint.x, clientY: dragPoint.y }), false); if (focusedSprite.events.isEnabled("globalpointermove")) { focusedSprite.events.dispatch("globalpointermove", { type: "globalpointermove", originalEvent: moveEvent.event, point: moveEvent.point, simulated: true, target: focusedSprite }); } } } })); this._disposers.push($utils.addEventListener(focusElementContainer, "keyup", (ev: KeyboardEvent) => { if (this._focusedSprite) { const focusedSprite = this._focusedSprite; const keyCode = ev.keyCode; switch (keyCode) { case 37: case 39: case 38: case 40: if (focusedSprite.isDragging()) { // Simulate drag stop const dragPoint = this._keyboardDragPoint!; const upEvent = renderer.getEvent(new MouseEvent("mouseup", { clientX: dragPoint.x, clientY: dragPoint.y })); if (focusedSprite.events.isEnabled("globalpointerup")) { focusedSprite.events.dispatch("globalpointerup", { type: "globalpointerup", originalEvent: upEvent.event, point: upEvent.point, simulated: true, target: focusedSprite }); } //this._positionFocusElement(focusedSprite); this._keyboardDragPoint = undefined; // @todo dispatch mouseup event instead of calling dragStop? // this._dispatchEvent("globalpointerup", target, upEvent); return; } else if(focusedSprite.get("focusableGroup")) { // Find next item in focusable group const group = focusedSprite.get("focusableGroup"); const items = this._tabindexes.filter(item => item.get("focusableGroup") == group); let index = items.indexOf(focusedSprite); const lastIndex = items.length - 1; index += (keyCode == 39 || keyCode == 40) ? 1 : -1; if (index < 0) { index = lastIndex; } else if (index > lastIndex) { index = 0; } $utils.focus(items[index].getPrivate("focusElement")!.dom); } break; } } })); } this._startTicker(); this.setThemes([]); this._addTooltip(); if (!this._hasLicense()) { this._showBranding(); } } private _initResizeSensor(): void { if (this._resizeSensorDisposer) { this._resizeSensorDisposer.dispose(); } this._resizeSensorDisposer = new ResizeSensor(this.dom, () => { if (this.autoResize) { this.resize(); } }); this._disposers.push(this._resizeSensorDisposer); } /** * If automatic resizing of char is disabled (`root.autoResize = false`), it * can be resized manually by calling this method. */ public resize(): void { const dom = this.dom; const w = dom.clientWidth; const h = dom.clientHeight; if (w > 0 && h > 0) { const focusElementContainer = this._focusElementContainer!; focusElementContainer.style.width = w + "px"; focusElementContainer.style.height = h + "px"; this._renderer.resize(w, h); const rootContainer = this._rootContainer; rootContainer.setPrivate("width", w); rootContainer.setPrivate("height", h); this._render(); this._handleLogo(); } } private _render() { this._renderer.render(this._rootContainer._display); if (this._focusElementDirty) { this._updateCurrentFocus(); this._focusElementDirty = false; } } private _runTickers(currentTime: number) { $array.each(this._tickers, (f) => { f(currentTime); }); } private _runAnimations(currentTime: number) { $array.keepIf(this._animations, (animation) => { return !animation._runAnimation(currentTime); }); } private _runDirties() { //console.log("tick **************************************************************"); let allParents: { [id: number]: IParent } = {}; while (this._isDirtyParents) { // This must be before calling _prepareChildren this._isDirtyParents = false; $object.keys(this._dirtyParents).forEach((key) => { const parent = this._dirtyParents[key]; delete this._dirtyParents[key]; if (!parent.isDisposed()) { allParents[parent.uid] = parent; parent._prepareChildren(); } }); } $object.keys(allParents).forEach((key) => { allParents[key]._updateChildren(); }); const objects: Array<Entity> = []; // console.log("_beforeChanged") $object.keys(this._dirty).forEach((key) => { const entity = this._dirty[key]; if (entity.isDisposed()) { delete this._dirty[entity.uid]; } else { objects.push(entity); entity._beforeChanged(); } }); // console.log("_changed") objects.forEach((entity) => { entity._changed(); delete this._dirty[entity.uid]; entity._clearDirty(); }); this._isDirty = false; const depths: { [id: number]: number } = {}; const bounds: Array<IBounds> = []; $object.keys(this._dirtyBounds).forEach((key) => { const entity = this._dirtyBounds[key]; delete this._dirtyBounds[key]; if (!entity.isDisposed()) { depths[entity.uid] = entity.depth(); bounds.push(entity); } }); // High depth -> low depth bounds.sort((x, y) => { return $order.compare(depths[y.uid], depths[x.uid]); }); // console.log("_updateBounds") bounds.forEach((entity) => { entity._updateBounds(); }); // console.log("_updatePosition") const dirtyPositions = this._dirtyPositions; $object.keys(dirtyPositions).forEach((key) => { const sprite = dirtyPositions[key]; delete dirtyPositions[key]; if (!sprite.isDisposed()) { sprite._updatePosition(); } }); // console.log("_afterChanged") objects.forEach((entity) => { entity._afterChanged(); }); } private _runTicker(currentTime: number) { if (!this.isDisposed()) { this.animationTime = currentTime; if (this.events.isEnabled("framestarted")) { this.events.dispatch("framestarted", { type: "framestarted", target: this, timestamp: currentTime, }); } this._runTickers(currentTime); this._runAnimations(currentTime); this._runDirties(); this._render(); if (this.events.isEnabled("frameended")) { this.events.dispatch("frameended", { type: "frameended", target: this, timestamp: currentTime, }); } // No more work to do if (this._tickers.length === 0 && this._animations.length === 0 && !this._isDirty) { this._ticker = null; this.animationTime = null; } else { rAF(this.fps, this._ticker!); } } } private _startTicker() { if (this._ticker === null) { this.animationTime = null; this._ticker = (currentTime) => { this._runTicker(currentTime); }; rAF(this.fps, this._ticker!); } } public _addDirtyEntity(entity: Entity) { if (this._dirty[entity.uid] === undefined) { this._isDirty = true; this._dirty[entity.uid] = entity; this._startTicker(); } } public _addDirtyParent(parent: IParent) { if (this._dirtyParents[parent.uid] === undefined) { this._isDirty = true; this._isDirtyParents = true; this._dirtyParents[parent.uid] = parent; this._startTicker(); } } public _addDirtyBounds(entity: IBounds) { if (this._dirtyBounds[entity.uid] === undefined) { this._isDirty = true; this._dirtyBounds[entity.uid] = entity; this._startTicker(); } } public _addDirtyPosition(sprite: Sprite) { if (this._dirtyPositions[sprite.uid] === undefined) { this._isDirty = true; this._dirtyPositions[sprite.uid] = sprite; this._startTicker(); } } public _addAnimation(animation: IAnimation) { // TODO use numeric id instead if (this._animations.indexOf(animation) === -1) { this._animations.push(animation); this._startTicker(); } } public eachFrame(f: (currentTime: number) => void): IDisposer { this._tickers.push(f); this._startTicker(); return new Disposer(() => { $array.removeFirst(this._tickers, f); }); } /** * Returns width of the target container, in pixels. * * @return Width */ public width(): number { return this.dom.clientWidth; } /** * Returns height of the target container, in pixels. * * @return Height */ public height(): number { return this.dom.clientHeight; } /** * Disposes root and all the content in it. */ public dispose(): void { if (!this._isDisposed) { this._isDisposed = true; this._rootContainer.dispose(); this._renderer.dispose(); this.horizontalLayout.dispose(); this.verticalLayout.dispose(); this.interfaceColors.dispose(); $array.each(this._disposers, (x) => { x.dispose(); }); if (this._inner) { $utils.removeElement(this._inner); } $array.remove(registry.rootElements, this); } } /** * Returns `true` if root element is disposed. * * @return Disposed? */ public isDisposed(): boolean { return this._isDisposed; } /** * Triggers screen reader read out a message. * * @see {@link https://www.amcharts.com/docs/v5/concepts/accessibility/} for more info * @param text Alert text */ public readerAlert(text: string): void { this._readerAlertElement!.innerHTML = text; } /** * Sets themes to be used for the chart. * * @see {@link https://www.amcharts.com/docs/v5/concepts/themes/} for more info * @param themes A list of themes */ public setThemes(themes: Array<Theme>): void { this._rootContainer.set("themes", themes); // otherwise new themes are not applied const tooltipContainer = this.tooltipContainer; if (tooltipContainer) { tooltipContainer._applyThemes(); } // @todo review this const interfaceColors = this.interfaceColors; if (interfaceColors) { interfaceColors._applyThemes(); } } protected _addTooltip() { if (!this.tooltipContainer) { const tooltipContainer = this._rootContainer.children.push(Container.new(this, { position: "absolute", isMeasured: false, width: p100, height: p100, layer: 100 })); this.tooltipContainer = tooltipContainer; const tooltip = Tooltip.new(this, {}); this.container.set("tooltip", tooltip); tooltip.hide(0); this._tooltip = tooltip; } } /** * Accesibility */ public _registerTabindexOrder(target: Sprite): void { if (target.get("focusable")) { $array.pushOne(this._tabindexes, target); } else { $array.remove(this._tabindexes, target); } this._invalidateTabindexes(); } public _unregisterTabindexOrder(target: Sprite): void { $array.remove(this._tabindexes, target); this._invalidateTabindexes(); } public _invalidateTabindexes(): void { this._tabindexes.sort((a: Sprite, b: Sprite) => { const aindex = a.get("tabindexOrder", 0); const bindex = b.get("tabindexOrder", 0); if (aindex == bindex) { return 0; } else if (aindex > bindex) { return 1; } else { return -1; } }); const groups: Array<string | number> = []; $array.each(this._tabindexes, (item, index) => { if (!item.getPrivate("focusElement")) { this._makeFocusElement(index, item); } else { this._moveFocusElement(index, item); } const group = item.get("focusableGroup"); if (group) { if (groups.indexOf(group) !== -1) { // Non-first element in the group, make it not directly focusable item.getPrivate("focusElement")!.dom.setAttribute("tabindex", "-1"); } else { groups.push(group); } } }); } public _updateCurrentFocus(): void { if (this._focusedSprite) { this._decorateFocusElement(this._focusedSprite); this._positionFocusElement(this._focusedSprite); } } public _decorateFocusElement(target: Sprite, focusElement?: HTMLDivElement): void { // Decorate with proper accessibility attributes if (!focusElement) { focusElement = target.getPrivate("focusElement")!.dom; } if (!focusElement) { return; } if (target.get("visible") && target.get("role") != "tooltip" && !target.isHidden()) { if (focusElement.getAttribute("tabindex") != "-1") { focusElement.setAttribute("tabindex", "" + this.tabindex); } } else { focusElement.removeAttribute("tabindex") } const role = target.get("role"); if (role) { focusElement.setAttribute("role", role); } else { focusElement.removeAttribute("role"); } const ariaLabel = target.get("ariaLabel"); if (ariaLabel) { const label = populateString(target, ariaLabel); focusElement.setAttribute("aria-label", label); } else { focusElement.removeAttribute("aria-label"); } const ariaLive = target.get("ariaLive"); if (ariaLive) { focusElement.setAttribute("aria-live", ariaLive); } else { focusElement.removeAttribute("aria-live"); } const ariaChecked = target.get("ariaChecked"); if (ariaChecked != null) { focusElement.setAttribute("aria-checked", ariaChecked ? "true" : "false"); } else { focusElement.removeAttribute("aria-checked"); } if (target.get("ariaHidden")) { focusElement.setAttribute("aria-hidden", "hidden"); } else { focusElement.removeAttribute("aria-hidden"); } const ariaOrientation = target.get("ariaOrientation"); if (ariaOrientation) { focusElement.setAttribute("aria-orientation", ariaOrientation); } else { focusElement.removeAttribute("aria-orientation"); } const ariaValueNow = target.get("ariaValueNow"); if (ariaValueNow) { focusElement.setAttribute("aria-valuenow", ariaValueNow); } else { focusElement.removeAttribute("aria-valuenow"); } const ariaValueMin = target.get("ariaValueMin"); if (ariaValueMin) { focusElement.setAttribute("aria-valuemin", ariaValueMin); } else { focusElement.removeAttribute("aria-valuemin"); } const ariaValueMax = target.get("ariaValueMax"); if (ariaValueMax) { focusElement.setAttribute("aria-valuemax", ariaValueMax); } else { focusElement.removeAttribute("aria-valuemax"); } const ariaValueText = target.get("ariaValueText"); if (ariaValueText) { focusElement.setAttribute("aria-valuetext", ariaValueText); } else { focusElement.removeAttribute("aria-valuetext"); } const ariaControls = target.get("ariaControls"); if (ariaControls) { focusElement.setAttribute("aria-controls", ariaControls); } else { focusElement.removeAttribute("aria-controls"); } } public _makeFocusElement(index: number, target: Sprite): void { if (target.getPrivate("focusElement")) { return; } // Init const focusElement = document.createElement("div"); if (target.get("role") != "tooltip") { focusElement.tabIndex = this.tabindex; } focusElement.style.position = "absolute"; $utils.setInteractive(focusElement, false); const disposers: Array<IDisposer> = []; target.setPrivate("focusElement", { dom: focusElement, disposers, }); this._decorateFocusElement(target); disposers.push($utils.addEventListener(focusElement, "focus", (ev: FocusEvent) => { this._handleFocus(ev, index); })); disposers.push($utils.addEventListener(focusElement, "blur", (ev: FocusEvent) => { this._handleBlur(ev, index); })); this._moveFocusElement(index, target); } public _removeFocusElement(target: Sprite): void { // Init const container = this._focusElementContainer!; const focusElement = target.getPrivate("focusElement")!; container.removeChild(focusElement.dom); $array.each(focusElement.disposers, (x) => { x.dispose(); }); } protected _moveFocusElement(index: number, target: Sprite): void { // Get container const container = this._focusElementContainer!; const focusElement = target.getPrivate("focusElement")!.dom; if (focusElement === this._focusElementContainer!.children[index]) { // Nothing to do return; } const next = this._focusElementContainer!.children[index + 1]; if (next) { container.insertBefore(focusElement, next); } else { container.append(focusElement); } } protected _positionFocusElement(target: Sprite): void { const bounds = target.globalBounds(); const width = bounds.right == bounds.left ? target.width() : bounds.right - bounds.left; const height = bounds.top == bounds.bottom ? target.height() : bounds.bottom - bounds.top; const focusElement = target.getPrivate("focusElement")!.dom; focusElement.style.top = (bounds.top - 2) + "px"; focusElement.style.left = (bounds.left - 2) + "px"; focusElement.style.width = (width + 4) + "px"; focusElement.style.height = (height + 4) + "px"; } protected _handleFocus(ev: FocusEvent, index: number): void { // Get element const focused = this._tabindexes[index]; // Size and position this._positionFocusElement(focused); //this._decorateFocusElement(focused); this._focusedSprite = focused; if (focused.events.isEnabled("focus")) { focused.events.dispatch("focus", { type: "focus", originalEvent: ev, target: focused }); } } protected _handleBlur(ev: FocusEvent, _index: number): void { const focused = this._focusedSprite; if (focused && focused.events.isEnabled("blur")) { focused.events.dispatch("blur", { type: "blur", originalEvent: ev, target: focused }); } this._focusedSprite = undefined; } /** * @ignore */ public updateTooltip(target: Text): void { const text = target._getText(); let tooltipElement = target.getPrivate("tooltipElement"); if (target.get("role") == "tooltip" && text != "") { if (!tooltipElement) { tooltipElement = this._makeTooltipElement(target); } if (tooltipElement.innerHTML != text) { tooltipElement.innerHTML = text!; } } else if (tooltipElement) { tooltipElement.remove(); target.removePrivate("tooltipElement"); } } public _makeTooltipElement(target: Text): HTMLDivElement { const container = this._tooltipElementContainer!; const tooltipElement = document.createElement("div"); tooltipElement.style.position = "absolute"; tooltipElement.style.opacity = "0.0000001"; $utils.setInteractive(tooltipElement, false); this._decorateFocusElement(target, tooltipElement); container.append(tooltipElement); target.setPrivate("tooltipElement", tooltipElement); return tooltipElement; } public _invalidateAccessibility(target: Sprite): void { this._focusElementDirty = true; const focusElement = target.getPrivate("focusElement"); if (target.get("focusable")) { if (focusElement) { this._decorateFocusElement(target); this._positionFocusElement(target); } // else { // this._renderer._makeFocusElement(0, this); // } } else if (focusElement) { this._removeFocusElement(target); } //this.updateCurrentFocus(); } /** * Returns `true` if `target` is currently focused. * * @param target Target * @return Focused? */ public focused(target: Sprite): boolean { return this._focusedSprite === target; } /** * Converts document coordinates to coordinates withing root element. * * @param point Document point * @return Root point */ public documentPointToRoot(point: IPoint): IPoint { const bbox = this.dom.getBoundingClientRect(); return { x: point.x - bbox.left, y: point.y - bbox.top }; } /** * @ignore */ public addDisposer<T extends IDisposer>(disposer: T): T { this._disposers.push(disposer); return disposer; } /** * To all the clever heads out there. Yes, we did not make any attempts to * scramble this. * * This is a part of a tool meant for our users to manage their commercial * licenses for removal of amCharts branding from charts. * * The only legit way to do so is to purchase a commercial license for amCharts: * https://www.amcharts.com/online-store/ * * Removing or altering this code, or disabling amCharts branding in any other * way is against the license and thus illegal. */ protected _hasLicense(): boolean { for (let i = 0; i < registry.licenses.length; i++) { if (registry.licenses[i].match(/^AM5C.{5,}/i)) { return true; } } return false; } }
the_stack
import { Array2DHashSet } from "../misc/Array2DHashSet"; import { ArrayEqualityComparator } from "../misc/ArrayEqualityComparator"; import { Comparable } from "../misc/Stubs"; import { Equatable } from "../misc/Stubs"; import { MurmurHash } from "../misc/MurmurHash"; import { NotNull, Override } from "../Decorators"; import { ObjectEqualityComparator } from "../misc/ObjectEqualityComparator"; import { Recognizer } from "../Recognizer"; import { RuleContext } from "../RuleContext"; import * as Utils from "../misc/Utils"; function max<T extends Comparable<T>>(items: Iterable<T>): T | undefined { let result: T | undefined; for (let current of items) { if (result === undefined) { result = current; continue; } let comparison = result.compareTo(current); if (comparison < 0) { result = current; } } return result; } function min<T extends Comparable<T>>(items: Iterable<T>): T | undefined { let result: T | undefined; for (let current of items) { if (result === undefined) { result = current; continue; } let comparison = result.compareTo(current); if (comparison > 0) { result = current; } } return result; } /** A tree structure used to record the semantic context in which * an ATN configuration is valid. It's either a single predicate, * a conjunction `p1&&p2`, or a sum of products `p1||p2`. * * I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of * {@link SemanticContext} within the scope of this outer class. */ export abstract class SemanticContext implements Equatable { private static _NONE: SemanticContext; /** * The default {@link SemanticContext}, which is semantically equivalent to * a predicate of the form `{true}?`. */ static get NONE(): SemanticContext { if (SemanticContext._NONE === undefined) { SemanticContext._NONE = new SemanticContext.Predicate(); } return SemanticContext._NONE; } /** * For context independent predicates, we evaluate them without a local * context (i.e., unedfined context). That way, we can evaluate them without * having to create proper rule-specific context during prediction (as * opposed to the parser, which creates them naturally). In a practical * sense, this avoids a cast exception from RuleContext to myruleContext. * * For context dependent predicates, we must pass in a local context so that * references such as $arg evaluate properly as _localctx.arg. We only * capture context dependent predicates in the context in which we begin * prediction, so we passed in the outer context here in case of context * dependent predicate evaluation. */ public abstract eval<T>(parser: Recognizer<T, any>, parserCallStack: RuleContext): boolean; /** * Evaluate the precedence predicates for the context and reduce the result. * * @param parser The parser instance. * @param parserCallStack * @returns The simplified semantic context after precedence predicates are * evaluated, which will be one of the following values. * * * {@link #NONE}: if the predicate simplifies to `true` after * precedence predicates are evaluated. * * `undefined`: if the predicate simplifies to `false` after * precedence predicates are evaluated. * * `this`: if the semantic context is not changed as a result of * precedence predicate evaluation. * * A non-`undefined` {@link SemanticContext}: the new simplified * semantic context after precedence predicates are evaluated. */ public evalPrecedence(parser: Recognizer<any, any>, parserCallStack: RuleContext): SemanticContext | undefined { return this; } public abstract hashCode(): number; public abstract equals(obj: any): boolean; public static and(a: SemanticContext | undefined, b: SemanticContext): SemanticContext { if (!a || a === SemanticContext.NONE) { return b; } if (b === SemanticContext.NONE) { return a; } let result: SemanticContext.AND = new SemanticContext.AND(a, b); if (result.opnds.length === 1) { return result.opnds[0]; } return result; } /** * * @see ParserATNSimulator#getPredsForAmbigAlts */ public static or(a: SemanticContext | undefined, b: SemanticContext): SemanticContext { if (!a) { return b; } if (a === SemanticContext.NONE || b === SemanticContext.NONE) { return SemanticContext.NONE; } let result: SemanticContext.OR = new SemanticContext.OR(a, b); if (result.opnds.length === 1) { return result.opnds[0]; } return result; } } export namespace SemanticContext { /** * This random 30-bit prime represents the value of `AND.class.hashCode()`. */ const AND_HASHCODE = 40363613; /** * This random 30-bit prime represents the value of `OR.class.hashCode()`. */ const OR_HASHCODE = 486279973; function filterPrecedencePredicates(collection: SemanticContext[]): SemanticContext.PrecedencePredicate[] { let result: SemanticContext.PrecedencePredicate[] = []; for (let i = 0; i < collection.length; i++) { let context: SemanticContext = collection[i]; if (context instanceof SemanticContext.PrecedencePredicate) { result.push(context); // Remove the item from 'collection' and move i back so we look at the same index again collection.splice(i, 1); i--; } } return result; } export class Predicate extends SemanticContext { public ruleIndex: number; public predIndex: number; public isCtxDependent: boolean; // e.g., $i ref in pred constructor(); constructor(ruleIndex: number, predIndex: number, isCtxDependent: boolean); constructor(ruleIndex: number = -1, predIndex: number = -1, isCtxDependent: boolean = false) { super(); this.ruleIndex = ruleIndex; this.predIndex = predIndex; this.isCtxDependent = isCtxDependent; } @Override public eval<T>(parser: Recognizer<T, any>, parserCallStack: RuleContext): boolean { let localctx: RuleContext | undefined = this.isCtxDependent ? parserCallStack : undefined; return parser.sempred(localctx, this.ruleIndex, this.predIndex); } @Override public hashCode(): number { let hashCode: number = MurmurHash.initialize(); hashCode = MurmurHash.update(hashCode, this.ruleIndex); hashCode = MurmurHash.update(hashCode, this.predIndex); hashCode = MurmurHash.update(hashCode, this.isCtxDependent ? 1 : 0); hashCode = MurmurHash.finish(hashCode, 3); return hashCode; } @Override public equals(obj: any): boolean { if (!(obj instanceof Predicate)) { return false; } if (this === obj) { return true; } return this.ruleIndex === obj.ruleIndex && this.predIndex === obj.predIndex && this.isCtxDependent === obj.isCtxDependent; } @Override public toString(): string { return "{" + this.ruleIndex + ":" + this.predIndex + "}?"; } } export class PrecedencePredicate extends SemanticContext implements Comparable<PrecedencePredicate> { public precedence: number; constructor(precedence: number) { super(); this.precedence = precedence; } @Override public eval<T>(parser: Recognizer<T, any>, parserCallStack: RuleContext): boolean { return parser.precpred(parserCallStack, this.precedence); } @Override public evalPrecedence(parser: Recognizer<any, any>, parserCallStack: RuleContext): SemanticContext | undefined { if (parser.precpred(parserCallStack, this.precedence)) { return SemanticContext.NONE; } else { return undefined; } } @Override public compareTo(o: PrecedencePredicate): number { return this.precedence - o.precedence; } @Override public hashCode(): number { let hashCode: number = 1; hashCode = 31 * hashCode + this.precedence; return hashCode; } @Override public equals(obj: any): boolean { if (!(obj instanceof PrecedencePredicate)) { return false; } if (this === obj) { return true; } return this.precedence === obj.precedence; } @Override // precedence >= _precedenceStack.peek() public toString(): string { return "{" + this.precedence + ">=prec}?"; } } /** * This is the base class for semantic context "operators", which operate on * a collection of semantic context "operands". * * @since 4.3 */ export abstract class Operator extends SemanticContext { /** * Gets the operands for the semantic context operator. * * @returns a collection of {@link SemanticContext} operands for the * operator. * * @since 4.3 */ // @NotNull public abstract readonly operands: Iterable<SemanticContext>; } /** * A semantic context which is true whenever none of the contained contexts * is false. */ export class AND extends Operator { public opnds: SemanticContext[]; constructor(@NotNull a: SemanticContext, @NotNull b: SemanticContext) { super(); let operands: Array2DHashSet<SemanticContext> = new Array2DHashSet<SemanticContext>(ObjectEqualityComparator.INSTANCE); if (a instanceof AND) { operands.addAll(a.opnds); } else { operands.add(a); } if (b instanceof AND) { operands.addAll(b.opnds); } else { operands.add(b); } this.opnds = operands.toArray(); let precedencePredicates: PrecedencePredicate[] = filterPrecedencePredicates(this.opnds); // interested in the transition with the lowest precedence let reduced = min(precedencePredicates); if (reduced) { this.opnds.push(reduced); } } @Override get operands(): Iterable<SemanticContext> { return this.opnds; } @Override public equals(obj: any): boolean { if (this === obj) { return true; } if (!(obj instanceof AND)) { return false; } return ArrayEqualityComparator.INSTANCE.equals(this.opnds, obj.opnds); } @Override public hashCode(): number { return MurmurHash.hashCode(this.opnds, AND_HASHCODE); } /** * {@inheritDoc} * * The evaluation of predicates by this context is short-circuiting, but * unordered. */ @Override public eval<T>(parser: Recognizer<T, any>, parserCallStack: RuleContext): boolean { for (let opnd of this.opnds) { if (!opnd.eval(parser, parserCallStack)) { return false; } } return true; } @Override public evalPrecedence(parser: Recognizer<any, any>, parserCallStack: RuleContext): SemanticContext | undefined { let differs: boolean = false; let operands: SemanticContext[] = []; for (let context of this.opnds) { let evaluated: SemanticContext | undefined = context.evalPrecedence(parser, parserCallStack); differs = differs || (evaluated !== context); if (evaluated == null) { // The AND context is false if any element is false return undefined; } else if (evaluated !== SemanticContext.NONE) { // Reduce the result by skipping true elements operands.push(evaluated); } } if (!differs) { return this; } if (operands.length === 0) { // all elements were true, so the AND context is true return SemanticContext.NONE; } let result: SemanticContext = operands[0]; for (let i = 1; i < operands.length; i++) { result = SemanticContext.and(result, operands[i]); } return result; } @Override public toString(): string { return Utils.join(this.opnds, "&&"); } } /** * A semantic context which is true whenever at least one of the contained * contexts is true. */ export class OR extends Operator { public opnds: SemanticContext[]; constructor(@NotNull a: SemanticContext, @NotNull b: SemanticContext) { super(); let operands: Array2DHashSet<SemanticContext> = new Array2DHashSet<SemanticContext>(ObjectEqualityComparator.INSTANCE); if (a instanceof OR) { operands.addAll(a.opnds); } else { operands.add(a); } if (b instanceof OR) { operands.addAll(b.opnds); } else { operands.add(b); } this.opnds = operands.toArray(); let precedencePredicates: PrecedencePredicate[] = filterPrecedencePredicates(this.opnds); // interested in the transition with the highest precedence let reduced = max(precedencePredicates); if (reduced) { this.opnds.push(reduced); } } @Override get operands(): Iterable<SemanticContext> { return this.opnds; } @Override public equals(obj: any): boolean { if (this === obj) { return true; } if (!(obj instanceof OR)) { return false; } return ArrayEqualityComparator.INSTANCE.equals(this.opnds, obj.opnds); } @Override public hashCode(): number { return MurmurHash.hashCode(this.opnds, OR_HASHCODE); } /** * {@inheritDoc} * * The evaluation of predicates by this context is short-circuiting, but * unordered. */ @Override public eval<T>(parser: Recognizer<T, any>, parserCallStack: RuleContext): boolean { for (let opnd of this.opnds) { if (opnd.eval(parser, parserCallStack)) { return true; } } return false; } @Override public evalPrecedence(parser: Recognizer<any, any>, parserCallStack: RuleContext): SemanticContext | undefined { let differs: boolean = false; let operands: SemanticContext[] = []; for (let context of this.opnds) { let evaluated: SemanticContext | undefined = context.evalPrecedence(parser, parserCallStack); differs = differs || (evaluated !== context); if (evaluated === SemanticContext.NONE) { // The OR context is true if any element is true return SemanticContext.NONE; } else if (evaluated) { // Reduce the result by skipping false elements operands.push(evaluated); } } if (!differs) { return this; } if (operands.length === 0) { // all elements were false, so the OR context is false return undefined; } let result: SemanticContext = operands[0]; for (let i = 1; i < operands.length; i++) { result = SemanticContext.or(result, operands[i]); } return result; } @Override public toString(): string { return Utils.join(this.opnds, "||"); } } }
the_stack
import { Component, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; import { SafeHtml } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { ShowdownExtension } from 'showdown'; import { catchError, filter, flatMap, map, switchMap, tap } from 'rxjs/operators'; import { merge, Observable, of, Subscription } from 'rxjs'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { ArtemisMarkdownService } from 'app/shared/markdown.service'; import { ProgrammingExerciseTaskExtensionWrapper } from './extensions/programming-exercise-task.extension'; import { ProgrammingExercisePlantUmlExtensionWrapper } from 'app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension'; import { ProgrammingExerciseInstructionService } from 'app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service'; import { TaskArray, TaskArrayWithExercise } from 'app/exercises/programming/shared/instructions-render/task/programming-exercise-task.model'; import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { Participation } from 'app/entities/participation/participation.model'; import { Feedback } from 'app/entities/feedback.model'; import { ResultService } from 'app/exercises/shared/result/result.service'; import { RepositoryFileService } from 'app/exercises/shared/result/repository.service'; import { problemStatementHasChanged } from 'app/exercises/shared/exercise/exercise-utils'; import { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service'; import { hasParticipationChanged } from 'app/overview/participation-utils'; import { Result } from 'app/entities/result.model'; import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; import { findLatestResult } from 'app/shared/util/utils'; @Component({ selector: 'jhi-programming-exercise-instructions', templateUrl: './programming-exercise-instruction.component.html', styleUrls: ['./programming-exercise-instruction.scss'], }) export class ProgrammingExerciseInstructionComponent implements OnChanges, OnDestroy { @Input() public exercise: ProgrammingExercise; @Input() public participation: Participation; @Input() public exerciseHints: ExerciseHint[]; @Input() generateHtmlEvents: Observable<void>; @Input() personalParticipation: boolean; // If there are no instructions available (neither in the exercise problemStatement or the legacy README.md) emits an event @Output() public onNoInstructionsAvailable = new EventEmitter(); public problemStatement: string; public participationSubscription: Subscription; public isInitial = true; public isLoading: boolean; public latestResultValue?: Result; get latestResult() { return this.latestResultValue; } set latestResult(result: Result | undefined) { this.latestResultValue = result; this.programmingExerciseTaskWrapper.setExercise(this.exercise); this.programmingExerciseTaskWrapper.setLatestResult(this.latestResult); this.programmingExercisePlantUmlWrapper.setLatestResult(this.latestResult); } public tasks: TaskArray; public renderedMarkdown: SafeHtml; private injectableContentForMarkdownCallbacks: Array<() => void> = []; markdownExtensions: ShowdownExtension[]; private injectableContentFoundSubscription: Subscription; private tasksSubscription: Subscription; private generateHtmlSubscription: Subscription; constructor( private translateService: TranslateService, private resultService: ResultService, private repositoryFileService: RepositoryFileService, private participationWebsocketService: ParticipationWebsocketService, private markdownService: ArtemisMarkdownService, private programmingExerciseInstructionService: ProgrammingExerciseInstructionService, private programmingExerciseTaskWrapper: ProgrammingExerciseTaskExtensionWrapper, private programmingExercisePlantUmlWrapper: ProgrammingExercisePlantUmlExtensionWrapper, private programmingExerciseParticipationService: ProgrammingExerciseParticipationService, private exerciseHintService: ExerciseHintService, ) {} /** * If the participation changes, the participation's instructions need to be loaded and the * subscription for the participation's result needs to be set up. * @param changes */ public ngOnChanges(changes: SimpleChanges) { of(!!this.markdownExtensions) .pipe( // Set up the markdown extensions if they are not set up yet so that tasks, UMLs, etc. can be parsed. tap((markdownExtensionsInitialized: boolean) => !markdownExtensionsInitialized && this.setupMarkdownSubscriptions()), switchMap(() => this.loadExerciseHints(this.exercise.id)), tap((hints: ExerciseHint[]) => { this.exerciseHints = hints; this.programmingExerciseTaskWrapper.exerciseHints = hints; }), // If the participation has changed, set up the websocket subscriptions. map(() => hasParticipationChanged(changes)), tap((participationHasChanged: boolean) => { if (participationHasChanged) { this.isInitial = true; if (this.generateHtmlSubscription) { this.generateHtmlSubscription.unsubscribe(); } if (this.generateHtmlEvents) { this.generateHtmlEvents.subscribe(() => { this.updateMarkdown(); }); } this.setupResultWebsocket(); } }), switchMap((participationHasChanged: boolean) => { // If the exercise is not loaded, the instructions can't be loaded and so there is no point in loading the results, etc, yet. if (!this.isLoading && this.exercise && this.participation && (this.isInitial || participationHasChanged)) { this.isLoading = true; return this.loadInstructions().pipe( // If no instructions can be loaded, abort pipe and hide the instruction panel tap((problemStatement) => { if (!problemStatement) { this.onNoInstructionsAvailable.emit(); this.isLoading = false; this.isInitial = false; return of(undefined); } }), filter((problemStatement) => !!problemStatement), tap((problemStatement) => (this.problemStatement = problemStatement!)), switchMap(() => this.loadInitialResult()), tap((latestResult) => { this.latestResult = latestResult; }), tap(() => { this.updateMarkdown(); this.isInitial = false; this.isLoading = false; }), ); } else if (problemStatementHasChanged(changes) && this.problemStatement === undefined) { // Refreshes the state in the singleton task and uml extension service this.latestResult = this.latestResultValue; this.problemStatement = this.exercise.problemStatement!; this.updateMarkdown(); return of(undefined); } else if (this.exercise && problemStatementHasChanged(changes)) { // Refreshes the state in the singleton task and uml extension service this.latestResult = this.latestResultValue; this.problemStatement = this.exercise.problemStatement!; return of(undefined); } else { return of(undefined); } }), ) .subscribe(); } private loadExerciseHints(exerciseId: number | undefined) { if (this.exerciseHints) { return of(this.exerciseHints); } if (this.exercise && this.exercise.exerciseHints) { return of(this.exercise.exerciseHints); } if (!exerciseId) { return of([]); } return this.exerciseHintService.findByExerciseId(exerciseId).pipe( map(({ body }) => body), catchError(() => of([])), ); } /** * Setup the markdown extensions for parsing the tasks and tests and subscriptions necessary to receive injectable content. */ private setupMarkdownSubscriptions() { this.markdownExtensions = [this.programmingExerciseTaskWrapper.getExtension(), this.programmingExercisePlantUmlWrapper.getExtension()]; if (this.injectableContentFoundSubscription) { this.injectableContentFoundSubscription.unsubscribe(); } this.injectableContentFoundSubscription = merge( this.programmingExerciseTaskWrapper.subscribeForInjectableElementsFound(), this.programmingExercisePlantUmlWrapper.subscribeForInjectableElementsFound(), ).subscribe((injectableCallback) => { this.injectableContentForMarkdownCallbacks = [...this.injectableContentForMarkdownCallbacks, injectableCallback]; }); if (this.tasksSubscription) { this.tasksSubscription.unsubscribe(); } this.tasksSubscription = this.programmingExerciseTaskWrapper.subscribeForFoundTestsInTasks().subscribe((tasks: TaskArrayWithExercise) => { // Multiple instances of the code editor use the TaskWrapperService. We have to check, that the returned tasks belong to this exercise if (tasks.exerciseId === this.exercise.id) { this.tasks = tasks.tasks; } }); } /** * Set up the websocket for retrieving build results. * Online updates the build logs if the result is new, otherwise doesn't react. */ private setupResultWebsocket() { if (this.participationSubscription) { this.participationSubscription.unsubscribe(); } this.participationSubscription = this.participationWebsocketService .subscribeForLatestResultOfParticipation(this.participation.id!, this.personalParticipation, this.exercise.id!) .pipe(filter((result) => !!result)) .subscribe((result: Result) => { this.latestResult = result; this.programmingExerciseTaskWrapper.setLatestResult(this.latestResult); this.programmingExercisePlantUmlWrapper.setLatestResult(this.latestResult); this.updateMarkdown(); }); } /** * Render the markdown into html. */ updateMarkdown(): void { // make sure that always the correct result is set, before updating markdown // looks weird, but in setter of latestResult are setters of sub components invoked this.latestResult = this.latestResult; this.injectableContentForMarkdownCallbacks = []; this.renderedMarkdown = this.markdownService.safeHtmlForMarkdown(this.problemStatement, this.markdownExtensions); // Wait a tick for the template to render before injecting the content. setTimeout(() => this.injectableContentForMarkdownCallbacks.forEach((callback) => callback()), 0); } /** * This method is used for initially loading the results so that the instructions can be rendered. */ loadInitialResult(): Observable<Result | undefined> { if (this.participation && this.participation.id && this.participation.results && this.participation.results.length) { // Get the result with the highest id (most recent result) const latestResult = findLatestResult(this.participation.results); if (!latestResult) { return of(undefined); } return latestResult.feedbacks ? of(latestResult) : this.loadAndAttachResultDetails(latestResult); } else if (this.participation && this.participation.id) { // Only load results if the exercise already is in our database, otherwise there can be no build result anyway return this.loadLatestResult(); } else { return of(undefined); } } /** * Retrieve latest result for the participation/exercise/course combination. * If there is no result, return undefined. */ loadLatestResult(): Observable<Result | undefined> { return this.programmingExerciseParticipationService.getLatestResultWithFeedback(this.participation.id!).pipe( catchError(() => of(undefined)), flatMap((latestResult: Result) => (latestResult && !latestResult.feedbacks ? this.loadAndAttachResultDetails(latestResult) : of(latestResult))), ); } /** * Fetches details for the result (if we received one) and attach them to the result. * Mutates the input parameter result. * @param result - result to which instructions will be attached. */ loadAndAttachResultDetails(result: Result): Observable<Result> { const currentParticipation = result.participation ? result.participation : this.participation; return this.resultService.getFeedbackDetailsForResult(currentParticipation.id!, result.id!).pipe( map((res) => res && res.body), map((feedbacks: Feedback[]) => { result.feedbacks = feedbacks; return result; }), catchError(() => of(result)), ); } /** * Loads the instructions for the programming exercise. * We added the problemStatement later, historically the instructions where a file in the student's repository * This is why we now prefer the problemStatement and if it doesn't exist try to load the readme. */ loadInstructions(): Observable<string | undefined> { if (this.exercise.problemStatement) { return of(this.exercise.problemStatement); } else { if (!this.participation.id) { return of(undefined); } return this.repositoryFileService.get(this.participation.id, 'README.md').pipe( catchError(() => of(undefined)), // Old readme files contain chars instead of our domain command tags - replace them when loading the file map((fileObj) => fileObj && fileObj.fileContent.replace(new RegExp(/✅/, 'g'), '[task]')), ); } } /** * Unsubscribes from all subscriptions. */ ngOnDestroy() { if (this.participationSubscription) { this.participationSubscription.unsubscribe(); } if (this.generateHtmlSubscription) { this.generateHtmlSubscription.unsubscribe(); } if (this.injectableContentFoundSubscription) { this.injectableContentFoundSubscription.unsubscribe(); } if (this.tasksSubscription) { this.tasksSubscription.unsubscribe(); } } }
the_stack
import { TestHelper } from './TestHelper'; /** * Unit tests. */ const FAILURE_STRING: string = 'The cohesion of this class is too low. Consider splitting this class into multiple cohesive classes: '; describe('minClassCohesionRule', (): void => { const ruleName: string = 'min-class-cohesion'; it('should pass on empty class', (): void => { const script: string = ` class EmptyClass { } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on class with instance fields and no instance methods', (): void => { const script: string = ` // classes with instance fields class ClassWithField { private field; } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on class with constructor parameters creating instance fields and no instance methods', (): void => { const script: string = ` // classes with instance fields class ClassWithField { constructor(private field) { } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should fail on class without instance fields', (): void => { const script: string = ` // classes without instance fields class ClassWithoutFields { private someMethod() { } } `; TestHelper.assertViolations(ruleName, script, [ { failure: FAILURE_STRING + 'ClassWithoutFields', name: 'file.ts', ruleName: 'min-class-cohesion', startPosition: { character: 13, line: 3 }, }, ]); }); it('should pass on class with constructor parameters, instance fields, and instance method using all fields', (): void => { const script: string = ` class CohesiveClass { constructor(private a: number) { } public b: number; public sum(): number { return this.a + this.b; } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on class with constructor parameters, instance fields, and instance method using all fields', (): void => { const script: string = ` class HalfCohesiveClass { constructor(private a: number) { } public b: number; public getA(): number { return this.a; } public getB(): number { return this.b; } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should fail on class with constructor parameters, instance fields, and instance method using all fields', (): void => { const script: string = ` class ThirdCohesiveClass { constructor(private a: number) { } public b: number; private c: number; public getA(): number { return this.a; } public getB(): number { return this.b; } public getC(): number { return this.c; } } `; TestHelper.assertViolations(ruleName, script, [ { failure: FAILURE_STRING + 'ThirdCohesiveClass', name: 'file.ts', ruleName: 'min-class-cohesion', startPosition: { character: 13, line: 2 }, }, ]); }); it('should pass on Stack class', (): void => { const script: string = ` class Stack { private topOfStack: number = 0; private elements: number[] = []; public size(): number { return this.topOfStack; } public push(element: number): void { this.topOfStack++; this.elements.push(element); } public pop(): number { if (this.topOfStack === 0) throw new Error("PoppedWhenEmpty"); const element: number = this.elements[--this.topOfStack]; this.elements = this.elements.slice(this.topOfStack, 1); return element; } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on SubClass class', (): void => { const script: string = ` class BaseClass { private field1: number = 2; } class SubClass extends BaseClass { private field2: number = 2; private subFunction() { return this.field1 + this.field2; } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on SubClass class not using instance fields', (): void => { const script: string = ` class BaseClass { private field1: number = 2; } class SubClass extends BaseClass { private field2: number = 2; private subFunction() { return this.field1; } } `; TestHelper.assertViolations(ruleName, script, [ // { // "failure": FAILURE_STRING + "SubClass", // "name": "file.ts", // "ruleName": "min-class-cohesion", // "ruleSeverity": "ERROR", // "startPosition": { // "character": 13, // "line": 5 // } // } ]); }); it('should pass on class with cohesive getters', (): void => { const script: string = ` class CohesiveClass { constructor(private a: number) { } public b: number; public get sum(): number { return this.a + this.b; } } `; TestHelper.assertViolations(ruleName, script, []); }); it('should pass on class with uncohesive static methods', (): void => { const script: string = ` class CohesiveClass { constructor(private a: number) { } public b: number; public get sum(): number { return this.a + this.b; } public static bad1(): number { return 1; } public static bad2(): number { return 2; } public static bad3(): number { return 3; } } `; TestHelper.assertViolations(ruleName, script, []); }); context( 'reading options', (): void => { context( '90% cohesion', (): void => { let options: any[]; beforeEach((): void => { options = [true, 0.9]; }); it('should fail on Stack class', (): void => { const script: string = ` class Stack { private topOfStack: number = 0; private elements: number[] = []; public size(): number { return this.topOfStack; } public push(element: number): void { this.topOfStack++; this.elements.push(element); } public pop(): number { if (this.topOfStack === 0) throw new Error("PoppedWhenEmpty"); const element: number = this.elements[--this.topOfStack]; this.elements = this.elements.slice(this.topOfStack, 1); return element; } } `; TestHelper.assertViolationsWithOptions(ruleName, options, script, [ { failure: FAILURE_STRING + 'Stack', name: 'file.ts', ruleName: 'min-class-cohesion', startPosition: { character: 17, line: 2 }, }, ]); }); } ); context( '80% cohesion', (): void => { let options: any[]; beforeEach((): void => { options = [true, 0.8]; }); it('should pass on Stack class', (): void => { const script: string = ` class Stack { private topOfStack: number = 0; private elements: number[] = []; public size(): number { return this.topOfStack; } public push(element: number): void { this.topOfStack++; this.elements.push(element); } public pop(): number { if (this.topOfStack === 0) throw new Error("PoppedWhenEmpty"); const element: number = this.elements[--this.topOfStack]; this.elements = this.elements.slice(this.topOfStack, 1); return element; } } `; TestHelper.assertViolationsWithOptions(ruleName, options, script, []); }); } ); } ); });
the_stack
import seedrandom from 'seedrandom' import { BigNumber } from '@ethersproject/bignumber' import { Edge, Graph, Vertice } from '../src/entities/MultiRouter' import { Pool, PoolType, RToken } from '../src/types/MultiRouterTypes' type Topology = [number, number[][]] function createTopology(t: Topology): [Graph, Vertice, Vertice] { const tokens: RToken[] = [] for (let i = 0; i < t[0]; ++i) { tokens.push({ name: '' + i, address: '' + i }) } const bn = BigNumber.from(1e6) const pools = t[1].map((e, i) => { return new Pool({ address: '' + i, token0: tokens[e[0]], token1: tokens[e[1]], type: PoolType.ConstantProduct, reserve0: bn, reserve1: bn, fee: 0.003 }) }) const g = new Graph(pools, tokens[0], 0) // just a dummy g.edges.forEach(e => { e.amountInPrevious = 1 e.amountOutPrevious = 1 const edge = t[1][parseInt(e.pool.address)] console.assert(edge[0] == parseInt(e.vert0.token.name), 'internal Error 28') console.assert(edge[1] == parseInt(e.vert1.token.name), 'internal Error 29') e.direction = edge[0] == parseInt(e.vert0.token.name) }) g.getOrCreateVertice(tokens[0]) g.getOrCreateVertice(tokens[tokens.length - 1]) return [g, g.tokens.get(tokens[0]) as Vertice, g.tokens.get(tokens[tokens.length - 1]) as Vertice] } function createCorrectTopology(t: Topology, paths: number): [Graph, Vertice, Vertice] { const tokens: RToken[] = [] for (let i = 0; i < t[0]; ++i) { tokens.push({ name: '' + i, address: '' + i }) } const bn = BigNumber.from(1e6) const pools = t[1].map((e, i) => { return new Pool({ address: '' + i, token0: tokens[e[0]], token1: tokens[e[1]], type: PoolType.ConstantProduct, reserve0: bn, reserve1: bn, fee: 0.003 }) }) const g = new Graph(pools, tokens[0], 0) // just a dummy const from = g.getOrCreateVertice(tokens[0]) const to = g.getOrCreateVertice(tokens[tokens.length - 1]) for (let i = 0; i < paths; ++i) { const p = generatePath(g, from, to, new Set<Vertice>()) if (p === undefined) return [g, from, to] else applyPath(p, from, to) } return [g, from, to] } function generatePath(g: Graph, from: Vertice, to: Vertice, used: Set<Vertice>): Edge[] | undefined { if (from === to) return [] used.add(from) let edges = from.edges.filter(e => !used.has(from.getNeibour(e) as Vertice)) while (edges.length) { const r = Math.floor(rnd() * from.edges.length) const edge = from.edges[r] const p = generatePath(g, from.getNeibour(edge) as Vertice, to, used) if (p !== undefined) return [edge, ...p] edges.splice(r, 1) } return undefined } function applyPath(p: Edge[], from: Vertice, to: Vertice) { let v = from p.forEach(e => { if (e.amountInPrevious == 0) { e.direction = v == e.vert0 e.amountInPrevious = 1 e.amountOutPrevious = 1 } else { if (e.direction == (v == e.vert0)) { e.amountInPrevious++ e.amountOutPrevious++ } else { e.amountInPrevious-- e.amountOutPrevious-- } } console.assert(e.amountOutPrevious >= 0) console.assert(e.amountInPrevious >= 0) v = v.getNeibour(e) as Vertice }) console.assert(v === to) } it('Simple topology', () => { const topology: Topology = [2, [[0, 1]]] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(2) expect(res[1].length).toEqual(2) expect(res[1][0]).toEqual(g[1]) expect(res[1][1]).toEqual(g[2]) }) it('Line topology', () => { const topology: Topology = [ 5, [ [0, 1], [1, 2], [2, 3], [3, 4] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(2) expect(res[1].length).toEqual(5) expect(res[1][0]).toEqual(g[1]) expect(res[1][4]).toEqual(g[2]) }) it('Verts after the last', () => { const topology: Topology = [ 5, [ [0, 1], [1, 2], [2, 4], [4, 3] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(3) expect(res[1].length).toEqual(1) expect(res[1][0].token.name).toEqual('3') }) it('Fork topology', () => { const topology: Topology = [ 5, [ [0, 1], [1, 4], [0, 2], [2, 4], [1, 3], [3, 4], [0, 4] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(2) expect(res[1].length).toEqual(5) expect(res[1][0]).toEqual(g[1]) expect(res[1][4]).toEqual(g[2]) }) it('Unreached verts', () => { const topology: Topology = [ 5, [ [0, 1], [1, 4], [2, 3], [3, 4] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(2) expect(res[1].length).toEqual(3) expect(res[1][0]).toEqual(g[1]) expect(res[1][2]).toEqual(g[2]) }) it('Dead end', () => { const topology: Topology = [ 5, [ [0, 1], [1, 4], [0, 3], [3, 2] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(3) expect(res[1].length).toEqual(2) }) it('Cycle from begin', () => { const topology: Topology = [ 5, [ [0, 1], [1, 2], [2, 3], [3, 0], [3, 4] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(0) expect(res[1].length).toEqual(4) }) it('Cycle not from begin', () => { const topology: Topology = [ 5, [ [0, 1], [1, 2], [2, 3], [3, 4], [3, 1] ] ] const g = createTopology(topology) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(0) expect(res[1].length).toEqual(3) }) const testSeed = '0' // Change it to change random generator values const rnd: () => number = seedrandom(testSeed) // random [0, 1) function getRandomTopology(tokens: number, density: number): Topology { const edges = [] for (let i = 0; i < tokens; ++i) { for (let j = 0; j < tokens; ++j) { if (i == j) continue const r = rnd() if (r < density) edges.push([i, j]) if (r < density * density) edges.push([i, j]) } } return [tokens, edges] } function vertIndex(v: Vertice): number { return parseInt(v.token.name) } function getEdge(i: number, res: [number, Vertice[]]): [number, number] { return [vertIndex(res[1][i]), vertIndex(res[1][i - 1])] } function findEdge(edge: [number, number], t: Topology): number { for (let j = 0; j < t[1].length; j++) { if (t[1][j][0] == edge[0] && t[1][j][1] == edge[1]) { return j } } return -1 } // 0 - cycle, 2 - ok, 3 - deadend, 4 - not connected function checkTopologySort(t: Topology) { //, res: [number, Vertice]) { //console.log(t); const g = createTopology(t) const res = g[0].topologySort(g[1], g[2]) //console.log('Result:', res[0], res[1].map(vertIndex)); if (res[0] === 0) { // check cycle really exists expect(res[1].length).toBeGreaterThan(1) for (let i = res[1].length - 1; i >= 1; i--) { const edge = getEdge(i, res) expect(findEdge(edge, t)).not.toEqual(-1) } // remove arbitrary edge from the cycle and launch checkTopologySort again const r = Math.floor(rnd() * (res[1].length - 1) + 1) console.assert(r >= 1 && r < res[1].length, 'Inernal Error 137') const edge = getEdge(r, res) const index = findEdge(edge, t) const nextEdgeList = [...t[1]] nextEdgeList.splice(index, 1) const t2: Topology = [t[0], nextEdgeList] checkTopologySort(t2) // recursion till the end of all cycles return 0 } if (res[0] === 2) { // check topology is correct expect(res[1][0]).toEqual(g[1]) expect(res[1][res[1].length - 1]).toEqual(g[2]) const vertPlace = new Map<number, number>() const notLastVert = new Set<number>() res[1].forEach((e, i) => vertPlace.set(vertIndex(e), i)) t[1].forEach(([a, b]) => { const p1 = vertPlace.get(a) const p2 = vertPlace.get(b) if (p1 !== undefined) { expect(p2).toBeDefined() expect(p1 as number).toBeLessThan(p2 as number) notLastVert.add(a) } }) expect(notLastVert.size).toEqual(res[1].length - 1) expect(notLastVert.has(vertIndex(g[2]))).toBeFalsy() return 2 } if (res[0] == 3 && res[1][res[1].length - 1] === g[1]) { // No way between start and end verts expect(res[1].length).toBeGreaterThan(0) const verts = new Set<number>() res[1].forEach(e => verts.add(vertIndex(e))) expect(verts.has(vertIndex(g[1]))).toBeTruthy() expect(verts.has(vertIndex(g[2]))).toBeFalsy() const vertsReached = new Set<number>() t[1].forEach(([a, b]) => { const p1 = verts.has(a) const p2 = verts.has(b) if (p1) expect(p2).toBeTruthy() if (p1) vertsReached.add(b) }) expect(vertsReached.size).toEqual(res[1].length - 1) expect(vertsReached.has(vertIndex(g[1]))).toBeFalsy() // add edge const nextEdgeList = [...t[1]] nextEdgeList.push([vertIndex(res[1][0]), vertIndex(g[2])]) const t2: Topology = [t[0], nextEdgeList] const nextRes = checkTopologySort(t2) expect(nextRes).not.toEqual(4) return 4 } if (res[0] === 3) { expect(res[1].length).toBeGreaterThan(0) const verts = new Set<number>() res[1].forEach(e => verts.add(vertIndex(e))) expect(verts.has(vertIndex(g[1]))).toBeFalsy() expect(verts.has(vertIndex(g[2]))).toBeFalsy() const vertsReached = new Set<number>() t[1].forEach(([a, b]) => { const p1 = verts.has(a) const p2 = verts.has(b) if (p1) expect(p2).toBeTruthy() if (p2) vertsReached.add(b) }) expect(vertsReached.size).toEqual(res[1].length) // remove all dead end const nextEdgeList = t[1].filter(([_, b]) => !verts.has(b)) const t2: Topology = [t[0], nextEdgeList] const nextRes = checkTopologySort(t2) expect(nextRes).toEqual(2) return 3 } expect(true).toBeFalsy() return 1 } it('test test', () => { const topology: Topology = [ 5, [ [0, 1], [1, 2], [2, 3], [3, 4], [3, 1] ] ] const res = checkTopologySort(topology) expect(res).toEqual(0) }) it('random topology test (tokens=5, dencity=0.3', () => { for (let i = 0; i < 30; ++i) { const topology: Topology = getRandomTopology(5, 0.3) checkTopologySort(topology) } }) it('random topology test (tokens=5, dencity=0.7', () => { for (let i = 0; i < 10; ++i) { const topology: Topology = getRandomTopology(5, 0.7) checkTopologySort(topology) } }) it('random topology test (tokens=10, dencity=0.3', () => { for (let i = 0; i < 10; ++i) { const topology: Topology = getRandomTopology(10, 0.3) checkTopologySort(topology) } }) it('random topology clean test', () => { for (let i = 0; i < 100; ++i) { let g: [Graph, Vertice, Vertice] do { const t = getRandomTopology(5, 0.5) g = createCorrectTopology(t, 10) } while (g[0].topologySort(g[1], g[2])[0] !== 0) // find topology with cycles const [nodes] = g[0].cleanTopology(g[1], g[2]) const res = g[0].topologySort(g[1], g[2]) expect(res[0]).toEqual(2) expect(res[1].length).toEqual(nodes.length) } })
the_stack
import { DeFiDRpcError } from '@defichain/testcontainers' import { getProviders, MockProviders } from '../provider.mock' import { P2WPKHTransactionBuilder } from '../../src' import { fundEllipticPair, sendTransaction } from '../test.utils' import { WIF } from '@defichain/jellyfish-crypto' import BigNumber from 'bignumber.js' import { LoanMasterNodeRegTestContainer } from './loan_container' import { TestingGroup } from '@defichain/jellyfish-testing' import { RegTest, RegTestGenesisKeys } from '@defichain/jellyfish-network' import { P2WPKH } from '@defichain/jellyfish-address' import { Script } from '@defichain/jellyfish-transaction' import { VaultActive } from '@defichain/jellyfish-api-core/src/category/loan' const tGroup = TestingGroup.create(2, i => new LoanMasterNodeRegTestContainer(RegTestGenesisKeys[i])) const alice = tGroup.get(0) const bob = tGroup.get(1) let bobColScript: Script let bobColAddr: string let bobVaultId: string let bobVaultId1: string let bobVaultAddr: string let bobVaultAddr1: string let bobLiqVaultId: string let bobloanAddr: string let tslaLoanHeight: number let aliceColAddr: string let aProviders: MockProviders let aBuilder: P2WPKHTransactionBuilder let bProviders: MockProviders let bBuilder: P2WPKHTransactionBuilder const netInterest = (3 + 0) / 100 // (scheme.rate + loanToken.interest) / 100 const blocksPerDay = (60 * 60 * 24) / (10 * 60) // 144 in regtest const priceFeeds = [ { token: 'DFI', currency: 'USD' }, { token: 'BTC', currency: 'USD' }, { token: 'TSLA', currency: 'USD' }, { token: 'AMZN', currency: 'USD' }, { token: 'UBER', currency: 'USD' }, { token: 'DUSD', currency: 'USD' } ] async function setup (): Promise<void> { // token setup aliceColAddr = await aProviders.getAddress() await alice.token.dfi({ address: aliceColAddr, amount: 15000 }) await alice.generate(1) await alice.token.create({ symbol: 'BTC', collateralAddress: aliceColAddr }) await alice.generate(1) await alice.token.mint({ symbol: 'BTC', amount: 10000 }) await alice.generate(1) // oracle setup const addr = await alice.generateAddress() const oracleId = await alice.rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 }) await alice.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await alice.rpc.oracle.setOracleData( oracleId, timestamp, { prices: [ { tokenAmount: '1@DFI', currency: 'USD' }, { tokenAmount: '10000@BTC', currency: 'USD' }, { tokenAmount: '2@TSLA', currency: 'USD' }, { tokenAmount: '4@AMZN', currency: 'USD' }, { tokenAmount: '4@UBER', currency: 'USD' }, { tokenAmount: '1@DUSD', currency: 'USD' } ] } ) await alice.generate(1) // setCollateralToken DFI await alice.rpc.loan.setCollateralToken({ token: 'DFI', factor: new BigNumber(1), fixedIntervalPriceId: 'DFI/USD' }) await alice.generate(1) // setCollateralToken BTC await alice.rpc.loan.setCollateralToken({ token: 'BTC', factor: new BigNumber(0.5), fixedIntervalPriceId: 'BTC/USD' }) await alice.generate(1) // setLoanToken TSLA await alice.rpc.loan.setLoanToken({ symbol: 'TSLA', fixedIntervalPriceId: 'TSLA/USD' }) await alice.generate(1) // setLoanToken AMZN await alice.rpc.loan.setLoanToken({ symbol: 'AMZN', fixedIntervalPriceId: 'AMZN/USD' }) await alice.generate(1) // setLoanToken UBER await alice.rpc.loan.setLoanToken({ symbol: 'UBER', fixedIntervalPriceId: 'UBER/USD' }) await alice.generate(1) // setLoanToken DUSD await alice.rpc.loan.setLoanToken({ symbol: 'DUSD', fixedIntervalPriceId: 'DUSD/USD' }) await alice.generate(1) // createLoanScheme 'scheme' await alice.rpc.loan.createLoanScheme({ minColRatio: 200, interestRate: new BigNumber(3), id: 'scheme' }) await alice.generate(1) await alice.rpc.loan.createLoanScheme({ minColRatio: 150, interestRate: new BigNumber(3), id: 'default' }) await alice.generate(1) await tGroup.waitForSync() bobColAddr = await bProviders.getAddress() await bob.token.dfi({ address: bobColAddr, amount: 30000 }) await bob.generate(1) await tGroup.waitForSync() await alice.rpc.account.accountToAccount(aliceColAddr, { [bobColAddr]: '1@BTC' }) await alice.generate(1) await tGroup.waitForSync() // create vault for taking large loan tokens const aliceVaultAddr = await alice.generateAddress() const aliceVaultId = await alice.rpc.loan.createVault({ ownerAddress: aliceVaultAddr, loanSchemeId: 'default' }) await alice.generate(1) await alice.rpc.loan.depositToVault({ vaultId: aliceVaultId, from: aliceColAddr, amount: '10000@DFI' }) await alice.generate(1) await alice.rpc.loan.takeLoan({ vaultId: aliceVaultId, to: aliceColAddr, amounts: ['300@TSLA', '400@AMZN', '400@UBER', '1000@DUSD'] }) await alice.generate(1) // create TSLA-DUSD await alice.poolpair.create({ tokenA: 'TSLA', tokenB: 'DUSD', ownerAddress: aliceColAddr }) await alice.generate(1) // add TSLA-DUSD await alice.poolpair.add({ a: { symbol: 'TSLA', amount: 200 }, b: { symbol: 'DUSD', amount: 100 } }) await alice.generate(1) // create AMZN-DUSD await alice.poolpair.create({ tokenA: 'AMZN', tokenB: 'DUSD' }) await alice.generate(1) // add AMZN-DUSD await alice.poolpair.add({ a: { symbol: 'AMZN', amount: 400 }, b: { symbol: 'DUSD', amount: 100 } }) await alice.generate(1) // create DUSD-DFI await alice.poolpair.create({ tokenA: 'DUSD', tokenB: 'DFI' }) await alice.generate(1) // add DUSD-DFI await alice.poolpair.add({ a: { symbol: 'DUSD', amount: 250 }, b: { symbol: 'DFI', amount: 100 } }) await alice.generate(1) await tGroup.waitForSync() // createVault bobVaultAddr = await bob.generateAddress() bobVaultId = await bob.rpc.loan.createVault({ ownerAddress: bobVaultAddr, loanSchemeId: 'scheme' }) await bob.generate(1) // depositToVault DFI 1000 await bob.rpc.loan.depositToVault({ vaultId: bobVaultId, from: bobColAddr, amount: '10000@DFI' }) await bob.generate(1) // depositToVault BTC 1 await bob.rpc.loan.depositToVault({ vaultId: bobVaultId, from: bobColAddr, amount: '1@BTC' }) await bob.generate(1) // createVault #2 bobVaultAddr1 = await bob.generateAddress() bobVaultId1 = await bob.rpc.loan.createVault({ ownerAddress: bobVaultAddr1, loanSchemeId: 'scheme' }) await bob.generate(1) await bob.rpc.loan.depositToVault({ vaultId: bobVaultId1, from: bobColAddr, amount: '10000@DFI' }) await bob.generate(1) // createVault for liquidation const bobLiqVaultAddr = await bob.generateAddress() bobLiqVaultId = await bob.rpc.loan.createVault({ ownerAddress: bobLiqVaultAddr, loanSchemeId: 'scheme' }) await bob.generate(1) await bob.rpc.loan.depositToVault({ vaultId: bobLiqVaultId, from: bobColAddr, amount: '10000@DFI' }) await bob.generate(1) await bob.rpc.loan.takeLoan({ vaultId: bobLiqVaultId, amounts: '100@UBER' }) await bob.generate(1) await tGroup.waitForSync() // liquidated: true await alice.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '100@UBER', currency: 'USD' }] }) await alice.generate(1) await tGroup.waitForSync() bobloanAddr = await bProviders.getAddress() await bob.rpc.loan.takeLoan({ vaultId: bobVaultId, to: bobloanAddr, amounts: '40@TSLA' }) await bob.generate(1) await tGroup.waitForSync() tslaLoanHeight = await bob.container.getBlockCount() } describe('paybackLoan success', () => { beforeEach(async () => { await tGroup.start() await alice.container.waitForWalletCoinbaseMaturity() aProviders = await getProviders(alice.container) aProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[0].owner.privKey)) aBuilder = new P2WPKHTransactionBuilder(aProviders.fee, aProviders.prevout, aProviders.elliptic, RegTest) bProviders = await getProviders(bob.container) bProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[1].owner.privKey)) bBuilder = new P2WPKHTransactionBuilder(bProviders.fee, bProviders.prevout, bProviders.elliptic, RegTest) await setup() }) afterEach(async () => { await tGroup.stop() }) it('should paybackLoan', async () => { await alice.rpc.account.sendTokensToAddress({}, { [bobColAddr]: ['5@TSLA'] }) await alice.generate(1) await tGroup.waitForSync() { const interests = await bob.rpc.loan.getInterest('scheme') const height = await bob.container.getBlockCount() const tslaInterestPerBlock = new BigNumber((netInterest * 40) / (365 * blocksPerDay)).decimalPlaces(8, BigNumber.ROUND_CEIL) // netInterest * loanAmt / 365 * blocksPerDay const tslaInterestTotal = tslaInterestPerBlock.multipliedBy(height - tslaLoanHeight + 1) expect(interests[0].interestPerBlock.toFixed(8)).toStrictEqual(tslaInterestPerBlock.toString()) expect(interests[0].totalInterest.toFixed(8)).toStrictEqual(tslaInterestTotal.toFixed(8)) } const vaultBefore = await bob.container.call('getvault', [bobVaultId]) expect(vaultBefore.loanAmounts).toStrictEqual(['40.00004568@TSLA']) expect(vaultBefore.loanValue).toStrictEqual(80.00009136) expect(vaultBefore.interestAmounts).toStrictEqual(['0.00004568@TSLA']) expect(vaultBefore.interestValue).toStrictEqual(0.00009136) expect(vaultBefore.collateralRatio).toStrictEqual(18750) expect(vaultBefore.informativeRatio).toStrictEqual(18749.97858752) const bobColAccBefore = await bob.rpc.account.getAccount(bobColAddr) expect(bobColAccBefore).toStrictEqual(['45.00000000@TSLA']) await fundEllipticPair(bob.container, bProviders.ellipticPair, 10) const bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(45) }] // try pay over loan amount }, bobColScript) // Ensure the created txn is correct const outs = await sendTransaction(bob.container, txn) expect(outs[0].value).toStrictEqual(0) expect(outs[1].value).toBeLessThan(10) expect(outs[1].value).toBeGreaterThan(9.999) expect(outs[1].scriptPubKey.addresses[0]).toStrictEqual(await bProviders.getAddress()) // Ensure you don't send all your balance away const prevouts = await bProviders.prevout.all() expect(prevouts.length).toStrictEqual(1) expect(prevouts[0].value.toNumber()).toBeLessThan(10) expect(prevouts[0].value.toNumber()).toBeGreaterThan(9.999) await bob.generate(1) const vaultAfter = await bob.container.call('getvault', [bobVaultId]) expect(vaultAfter.loanAmounts).toStrictEqual([]) expect(vaultAfter.interestAmounts).toStrictEqual([]) expect(vaultAfter.interestValue).toStrictEqual(0) expect(vaultAfter.loanValue).toStrictEqual(0) expect(vaultAfter.collateralRatio).toStrictEqual(-1) expect(vaultAfter.informativeRatio).toStrictEqual(-1) const bobColAccAfter = await bob.rpc.account.getAccount(bobColAddr) expect(bobColAccAfter).toStrictEqual(['4.99990864@TSLA']) }) it('should paybackLoan partially', async () => { const burnInfoBefore = await bob.container.call('getburninfo') expect(burnInfoBefore.paybackburn).toStrictEqual(undefined) const bobColAccBefore = await bob.container.call('getaccount', [bobColAddr]) expect(bobColAccBefore).toStrictEqual(['40.00000000@TSLA']) const vaultBefore = await bob.container.call('getvault', [bobVaultId]) expect(vaultBefore.collateralValue).toStrictEqual(15000) // DFI(10000) + BTC(1 * 10000 * 0.5) expect(vaultBefore.loanAmounts).toStrictEqual(['40.00002284@TSLA']) // 40 + totalInterest expect(vaultBefore.interestAmounts).toStrictEqual(['0.00002284@TSLA']) expect(vaultBefore.loanValue).toStrictEqual(80.00004568) // loanAmount * 2 (::1 TSLA = 2 USD) expect(vaultBefore.interestValue).toStrictEqual(0.00004568) expect(vaultBefore.collateralRatio).toStrictEqual(18750) expect(vaultBefore.informativeRatio).toStrictEqual(18749.98929375) // 15000 / 80.00004568 * 100 { const interests = await bob.rpc.loan.getInterest('scheme') const height = await bob.container.getBlockCount() const tslaInterestPerBlock = new BigNumber(netInterest * 40 / (365 * blocksPerDay)).decimalPlaces(8, BigNumber.ROUND_CEIL) // netInterest * loanAmt / 365 * blocksPerDay const tslaInterestTotal = tslaInterestPerBlock.multipliedBy(height - tslaLoanHeight + 1) expect(interests[0].interestPerBlock.toFixed(8)).toStrictEqual(tslaInterestPerBlock.toString()) expect(interests[0].totalInterest.toFixed(8)).toStrictEqual(tslaInterestTotal.toFixed(8)) } await fundEllipticPair(bob.container, bProviders.ellipticPair, 10) const bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(13) }] }, bobColScript) // Ensure the created txn is correct const outs = await sendTransaction(bob.container, txn) expect(outs[0].value).toStrictEqual(0) expect(outs[1].value).toBeLessThan(10) expect(outs[1].value).toBeGreaterThan(9.999) expect(outs[1].scriptPubKey.addresses[0]).toStrictEqual(await bProviders.getAddress()) // Ensure you don't send all your balance away const prevouts = await bProviders.prevout.all() expect(prevouts.length).toStrictEqual(1) expect(prevouts[0].value.toNumber()).toBeLessThan(10) expect(prevouts[0].value.toNumber()).toBeGreaterThan(9.999) await bob.generate(1) const bobColAccAfter = await bob.container.call('getaccount', [bobColAddr]) expect(bobColAccAfter).toStrictEqual(['27.00000000@TSLA']) // 40 - 13 = 27 const vaultAfter = await bob.container.call('getvault', [bobVaultId]) expect(vaultAfter.loanAmounts).toStrictEqual(['27.00009934@TSLA']) // 40.00004566 - 13 + totalInterest expect(vaultAfter.interestAmounts).toStrictEqual(['0.00003082@TSLA']) expect(vaultAfter.loanValue).toStrictEqual(54.00019868) // 27.00009934 * 2 (::1 TSLA = 2 USD) expect(vaultAfter.interestValue).toStrictEqual(0.00006164) expect(vaultAfter.collateralRatio).toStrictEqual(27778) // 15000 / 54.00009934 * 100 expect(vaultAfter.informativeRatio).toStrictEqual(27777.6755765) const burnInfoAfter = await bob.container.call('getburninfo') expect(burnInfoAfter.paybackburn).toStrictEqual(0.00001371) }) it('should paybackLoan by anyone', async () => { const loanAccBefore = await bob.container.call('getaccount', [aliceColAddr]) expect(loanAccBefore).toStrictEqual([ '4900.00000000@DFI', '9999.00000000@BTC', '100.00000000@TSLA', '400.00000000@UBER', '550.00000000@DUSD' ]) const vaultBefore = await bob.container.call('getvault', [bobVaultId]) expect(vaultBefore.collateralValue).toStrictEqual(15000) // DFI(10000) + BTC(1 * 10000 * 0.5) expect(vaultBefore.loanAmounts).toStrictEqual(['40.00002284@TSLA']) // 40 + totalInterest expect(vaultBefore.interestAmounts).toStrictEqual(['0.00002284@TSLA']) expect(vaultBefore.loanValue).toStrictEqual(80.00004568) // loanAmount * 2 (::1 TSLA = 2 USD) expect(vaultBefore.interestValue).toStrictEqual(0.00004568) expect(vaultBefore.collateralRatio).toStrictEqual(18750) // 15000 / 80.00004568 * 100 expect(vaultBefore.informativeRatio).toStrictEqual(18749.98929375) await fundEllipticPair(alice.container, aProviders.ellipticPair, 10) const aliceColScript = P2WPKH.fromAddress(RegTest, aliceColAddr, P2WPKH).getScript() const txn = await aBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: aliceColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(13) }] }, aliceColScript) // Ensure the created txn is correct const outs = await sendTransaction(alice.container, txn) expect(outs[0].value).toStrictEqual(0) expect(outs[1].value).toBeLessThan(10) expect(outs[1].value).toBeGreaterThan(9.999) expect(outs[1].scriptPubKey.addresses[0]).toStrictEqual(await aProviders.getAddress()) // Ensure you don't send all your balance away const prevouts = await aProviders.prevout.all() expect(prevouts.length).toStrictEqual(1) expect(prevouts[0].value.toNumber()).toBeLessThan(10) expect(prevouts[0].value.toNumber()).toBeGreaterThan(9.999) await alice.generate(1) const loanAccAfter = await bob.container.call('getaccount', [aliceColAddr]) expect(loanAccAfter).toStrictEqual([ '4900.00000000@DFI', '9999.00000000@BTC', '87.00000000@TSLA', '400.00000000@UBER', '550.00000000@DUSD' ]) const vaultAfter = await bob.container.call('getvault', [bobVaultId]) expect(vaultAfter.loanAmounts).toStrictEqual(['27.00009934@TSLA']) expect(vaultAfter.interestAmounts).toStrictEqual(['0.00003082@TSLA']) expect(vaultAfter.loanValue).toStrictEqual(54.00019868) // 27.00009934 * 2 (::1 TSLA = 2 USD) expect(vaultAfter.interestValue).toStrictEqual(0.00006164) expect(vaultAfter.collateralRatio).toStrictEqual(27778) // 15000 / 54.00019868 * 100 expect(vaultAfter.informativeRatio).toStrictEqual(27777.6755765) }) it('should paybackLoan more than one amount', async () => { const burnInfoBefore = await bob.container.call('getburninfo') expect(burnInfoBefore.paybackburn).toStrictEqual(undefined) await bob.rpc.loan.takeLoan({ vaultId: bobVaultId, amounts: ['15@AMZN'], to: bobColAddr }) const amznLoanHeight = await bob.container.getBlockCount() await bob.generate(1) const loanTokenAccBefore = await bob.container.call('getaccount', [bobColAddr]) expect(loanTokenAccBefore).toStrictEqual(['40.00000000@TSLA', '15.00000000@AMZN']) // first paybackLoan { const blockHeight = await bob.container.getBlockCount() const tslaTokenAmt = loanTokenAccBefore.find((amt: string) => amt.split('@')[1] === 'TSLA') const tslaAmt = Number(tslaTokenAmt.split('@')[0]) const amznTokenAmt = loanTokenAccBefore.find((amt: string) => amt.split('@')[1] === 'AMZN') const amznAmt = Number(amznTokenAmt.split('@')[0]) // tsla interest const tslaInterestPerBlock = new BigNumber(netInterest * tslaAmt / (365 * blocksPerDay)).decimalPlaces(8, BigNumber.ROUND_CEIL) // netInterest * loanAmt / 365 * blocksPerDay const tslaTotalInterest = tslaInterestPerBlock.multipliedBy(blockHeight - tslaLoanHeight + 1) // amzn interest const amznInterestPerBlock = new BigNumber(netInterest * amznAmt / (365 * blocksPerDay)).decimalPlaces(8, BigNumber.ROUND_CEIL) // netInterest * loanAmt / 365 * blocksPerDay const amznTotalInterest = amznInterestPerBlock.multipliedBy(blockHeight - amznLoanHeight) const interests = await bob.rpc.loan.getInterest('scheme') const tslaInterest = interests.find(i => i.token === 'TSLA') const tslaTotalInt = tslaInterest?.totalInterest.toFixed(8) expect(tslaTotalInt).toStrictEqual(tslaTotalInterest.toFixed(8)) const tslaInterestPerBlk = tslaInterest?.interestPerBlock.toFixed(8) expect(tslaInterestPerBlk).toStrictEqual(tslaInterestPerBlock.toFixed(8)) const amzInterest = interests.find(i => i.token === 'AMZN') const amzTotalInt = amzInterest?.totalInterest.toFixed(8) expect(amzTotalInt).toStrictEqual(amznTotalInterest.toFixed(8)) const amzInterestPerBlk = amzInterest?.interestPerBlock.toFixed(8) expect(amzInterestPerBlk).toStrictEqual(amznInterestPerBlock.toFixed(8)) const vaultBefore = await bob.container.call('getvault', [bobVaultId]) expect(vaultBefore.loanAmounts).toStrictEqual(['40.00004568@TSLA', '15.00000857@AMZN']) // eg: tslaTakeLoanAmt + tslaTotalInterest expect(vaultBefore.interestAmounts).toStrictEqual(['0.00004568@TSLA', '0.00000857@AMZN']) expect(vaultBefore.loanValue).toStrictEqual(140.00012564) // (40.00004568 * 2) + (15.00000857 * 4) expect(vaultBefore.collateralRatio).toStrictEqual(10714) // 15000 / 140.00012564 * 100 expect(vaultBefore.informativeRatio).toStrictEqual(10714.27609898) await fundEllipticPair(bob.container, bProviders.ellipticPair, 10) const bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(13) }, { token: 3, amount: new BigNumber(6) }] }, bobColScript) // Ensure the created txn is correct const outs = await sendTransaction(bob.container, txn) expect(outs[0].value).toStrictEqual(0) expect(outs[1].value).toBeLessThan(10) expect(outs[1].value).toBeGreaterThan(9.999) expect(outs[1].scriptPubKey.addresses[0]).toStrictEqual(await bProviders.getAddress()) // Ensure you don't send all your balance away const prevouts = await bProviders.prevout.all() expect(prevouts.length).toStrictEqual(1) expect(prevouts[0].value.toNumber()).toBeLessThan(10) expect(prevouts[0].value.toNumber()).toBeGreaterThan(9.999) await bob.generate(1) const vaultAfter = await bob.container.call('getvault', [bobVaultId]) expect(vaultAfter.loanAmounts).toStrictEqual(['27.00012218@TSLA', '9.00003599@AMZN']) expect(vaultAfter.interestAmounts).toStrictEqual(['0.00003082@TSLA', '0.00001028@AMZN']) expect(vaultAfter.loanValue).toStrictEqual(90.00038832) expect(vaultAfter.interestValue).toStrictEqual(0.00010276) expect(vaultAfter.collateralRatio).toStrictEqual(16667) expect(vaultAfter.informativeRatio).toStrictEqual(16666.59475586) const loanTokenAccAfter = await bob.container.call('getaccount', [bobColAddr]) expect(loanTokenAccAfter).toStrictEqual(['27.00000000@TSLA', '9.00000000@AMZN']) const burnInfoAfter = await bob.container.call('getburninfo') expect(burnInfoAfter.paybackburn).toStrictEqual(0.00002086) } // second paybackLoan { const bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(13) }, { token: 3, amount: new BigNumber(6) }] }, bobColScript) // Ensure the created txn is correct const outs = await sendTransaction(bob.container, txn) expect(outs[0].value).toStrictEqual(0) expect(outs[1].value).toBeLessThan(10) expect(outs[1].value).toBeGreaterThan(9.999) expect(outs[1].scriptPubKey.addresses[0]).toStrictEqual(await bProviders.getAddress()) // Ensure you don't send all your balance away const prevouts = await bProviders.prevout.all() expect(prevouts.length).toStrictEqual(1) expect(prevouts[0].value.toNumber()).toBeLessThan(10) expect(prevouts[0].value.toNumber()).toBeGreaterThan(9.999) const interests = await bob.rpc.loan.getInterest('scheme') const tslaInterest = interests.find(i => i.token === 'TSLA') const tslaTotalInterest = tslaInterest?.totalInterest.toFixed(8) expect(tslaTotalInterest).toStrictEqual('0.00000798') const tslaInterestPerBlk = tslaInterest?.interestPerBlock.toFixed(8) expect(tslaInterestPerBlk).toStrictEqual('0.00000798') const amzInterest = interests.find(i => i.token === 'AMZN') const amzTotalInterest = amzInterest?.totalInterest.toFixed(8) expect(amzTotalInterest).toStrictEqual('0.00000171') const amzInterestPerBlk = amzInterest?.interestPerBlock.toFixed(8) expect(amzInterestPerBlk).toStrictEqual('0.00000171') const vaultAfter = await bob.container.call('getvault', [bobVaultId]) expect(vaultAfter.loanAmounts).toStrictEqual(['14.00013016@TSLA', '3.00003770@AMZN']) expect(vaultAfter.interestAmounts).toStrictEqual(['0.00000798@TSLA', '0.00000171@AMZN']) expect(vaultAfter.loanValue).toStrictEqual(40.00041112) expect(vaultAfter.interestValue).toStrictEqual(0.0000228) expect(vaultAfter.collateralRatio).toStrictEqual(37500) expect(vaultAfter.informativeRatio).toStrictEqual(37499.61457896) const loanTokenAccAfter = await bob.container.call('getaccount', [bobColAddr]) expect(loanTokenAccAfter).toStrictEqual(['14.00000000@TSLA', '3.00000000@AMZN']) // (27 - 13), (9 - 6) const burnInfoAfter = await bob.container.call('getburninfo') expect(burnInfoAfter.paybackburn).toStrictEqual(0.00002806) } }) }) describe('paybackLoan failed', () => { beforeAll(async () => { await tGroup.start() await alice.container.waitForWalletCoinbaseMaturity() aProviders = await getProviders(alice.container) aProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[0].owner.privKey)) aBuilder = new P2WPKHTransactionBuilder(aProviders.fee, aProviders.prevout, aProviders.elliptic, RegTest) bProviders = await getProviders(bob.container) bProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[1].owner.privKey)) bBuilder = new P2WPKHTransactionBuilder(bProviders.fee, bProviders.prevout, bProviders.elliptic, RegTest) await setup() }) beforeEach(async () => { await fundEllipticPair(bob.container, bProviders.ellipticPair, 10) bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() }) afterAll(async () => { await tGroup.stop() }) it('should not paybackLoan on nonexistent vault', async () => { const txn = await bBuilder.loans.paybackLoan({ vaultId: '0'.repeat(64), from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow(`Cannot find existing vault with id ${'0'.repeat(64)}`) }) it('should not paybackLoan on nonexistent loan token', async () => { const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 1, amount: new BigNumber(1) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow('Loan token with id (1) does not exist!') }) it('should not paybackLoan as no loan on vault', async () => { const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId1, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow(`There are no loans on this vault (${bobVaultId1})`) }) it('should not paybackLoan as no token in this vault', async () => { const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 3, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow('There is no loan on token (AMZN) in this vault!') }) it('should not paybackLoan on empty vault', async () => { const emptyVaultId = await bob.rpc.loan.createVault({ ownerAddress: bobVaultAddr, loanSchemeId: 'scheme' }) await bob.generate(1) const txn = await bBuilder.loans.paybackLoan({ vaultId: emptyVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow(`Vault with id ${emptyVaultId} has no collaterals`) }) it('should not paybackLoan on liquidation vault', async () => { await bob.container.waitForVaultState(bobLiqVaultId, 'inLiquidation') const liqVault = await bob.container.call('getvault', [bobLiqVaultId]) expect(liqVault.state).toStrictEqual('inLiquidation') const txn = await bBuilder.loans.paybackLoan({ vaultId: bobLiqVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow('Cannot payback loan on vault under liquidation') }) it('should not paybackLoan with incorrect auth', async () => { await fundEllipticPair(alice.container, aProviders.ellipticPair, 10) const txn = await aBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(30) }] }, bobColScript) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow('tx must have at least one input from token owner') }) }) // move insufficient test case out to another scope for independent testing describe('paybackLoan failed #2', () => { beforeAll(async () => { await tGroup.start() await alice.container.waitForWalletCoinbaseMaturity() aProviders = await getProviders(alice.container) aProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[0].owner.privKey)) aBuilder = new P2WPKHTransactionBuilder(aProviders.fee, aProviders.prevout, aProviders.elliptic, RegTest) bProviders = await getProviders(bob.container) bProviders.setEllipticPair(WIF.asEllipticPair(RegTestGenesisKeys[1].owner.privKey)) bBuilder = new P2WPKHTransactionBuilder(bProviders.fee, bProviders.prevout, bProviders.elliptic, RegTest) await setup() }) afterAll(async () => { await tGroup.stop() }) it('should not paybackLoan while insufficient amount', async () => { const vault = await bob.rpc.loan.getVault(bobVaultId) as VaultActive expect(vault.loanAmounts).toStrictEqual(['40.00002284@TSLA']) const bobLoanAcc = await bob.rpc.account.getAccount(bobColAddr) expect(bobLoanAcc).toStrictEqual(['40.00000000@TSLA']) await fundEllipticPair(bob.container, bProviders.ellipticPair, 10) bobColScript = P2WPKH.fromAddress(RegTest, bobColAddr, P2WPKH).getScript() const script = await bProviders.elliptic.script() const txn = await bBuilder.loans.paybackLoan({ vaultId: bobVaultId, from: bobColScript, tokenAmounts: [{ token: 2, amount: new BigNumber(41) }] }, script) const promise = sendTransaction(bob.container, txn) await expect(promise).rejects.toThrow(DeFiDRpcError) await expect(promise).rejects.toThrow('amount 0.00000000 is less than 0.00006852') }) })
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const projectOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'project', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a project', }, { name: 'Delete', value: 'delete', description: 'Delete a project', }, { name: 'Get', value: 'get', description: 'Get a project', }, { name: 'Get All', value: 'getAll', description: 'Get all projects', }, { name: 'Update', value: 'update', description: 'Update a project', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const projectFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* project:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Project Name', name: 'name', type: 'string', required: true, default: '', description: 'Name of project being created.', displayOptions: { show: { resource: [ 'project', ], operation: [ 'create', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'create', ], resource: [ 'project', ], }, }, default: {}, options: [ { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Color', name: 'color', type: 'color', default: '#0000FF', }, { displayName: 'Client ID', name: 'clientId', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'workspaceId', ], loadOptionsMethod: 'loadClientsForWorkspace', }, default: '', }, { displayName: 'Estimate', name: 'estimateUi', placeholder: 'Add Estimate', type: 'fixedCollection', default: {}, typeOptions: { multipleValues: false, }, options: [ { displayName: 'Estimate', name: 'estimateValues', values: [ { displayName: 'Estimate', name: 'estimate', type: 'number', default: 0, }, { displayName: 'Type', name: 'type', type: 'options', options: [ { name: 'Auto', value: 'AUTO', }, { name: 'Manual', value: 'MANUAL', }, ], default: 'AUTO', }, ], }, ], }, { displayName: 'Is Public', name: 'isPublic', type: 'boolean', default: true, }, { displayName: 'Note', name: 'note', type: 'string', default: '', description: 'Note about the project', }, ], }, /* -------------------------------------------------------------------------- */ /* project:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Project ID', name: 'projectId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'project', ], operation: [ 'delete', ], }, }, }, /* -------------------------------------------------------------------------- */ /* project:get */ /* -------------------------------------------------------------------------- */ { displayName: 'Project ID', name: 'projectId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'project', ], operation: [ 'get', ], }, }, }, /* -------------------------------------------------------------------------- */ /* project:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'project', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'project', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 500, }, default: 100, description: 'How many results to return.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'project', ], }, }, default: {}, options: [ { displayName: 'Archived', name: 'archived', type: 'boolean', default: true, }, { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Client IDs', name: 'clients', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'workspaceId', ], loadOptionsMethod: 'loadClientsForWorkspace', }, default: [], }, { displayName: 'Contains Client', name: 'contains-client', type: 'boolean', default: false, description: 'If provided, projects will be filtered by whether they have a client.; ', }, { displayName: 'Client Status', name: 'client-status', type: 'options', options: [ { name: 'Active', value: 'ACTIVE', }, { name: 'Archived', value: 'ARCHIVED', }, ], default: '', description: 'If provided, projects will be filtered by whether they have a client.', }, { displayName: 'Contains User', name: 'contains-user', type: 'boolean', default: false, description: 'If provided, projects will be filtered by whether they have users.', }, { displayName: 'Is Template', name: 'is-template', type: 'boolean', default: false, description: 'If provided, projects will be filtered by whether they are used as a template.', }, { displayName: 'Name', name: 'name', type: 'string', default: '', }, { displayName: 'Sort Column', name: 'sort-column', type: 'options', options: [ { name: 'Name', value: 'NAME', }, { name: 'Client Name', value: 'CLIENT_NAME', }, { name: 'Duration', value: 'DURATION', }, ], default: '', }, { displayName: 'Sort Order', name: 'sort-order', type: 'options', options: [ { name: 'Ascending', value: 'ASCENDING', }, { name: 'Descending', value: 'DESCENDING', }, ], default: '', }, { displayName: 'User IDs', name: 'users', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'workspaceId', ], loadOptionsMethod: 'loadUsersForWorkspace', }, default: '', }, { displayName: 'User Status', name: 'user-status', type: 'options', options: [ { name: 'Active', value: 'ACTIVE', }, { name: 'Archived', value: 'ARCHIVED', }, ], default: '', description: 'If provided, projects will be filtered by whether they have a client.', }, ], }, /* -------------------------------------------------------------------------- */ /* project:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Project ID', name: 'projectId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'project', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'update', ], resource: [ 'project', ], }, }, default: {}, options: [ { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Color', name: 'color', type: 'color', default: '#0000FF', }, { displayName: 'Client ID', name: 'clientId', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'workspaceId', ], loadOptionsMethod: 'loadClientsForWorkspace', }, default: '', }, { displayName: 'Estimate', name: 'estimateUi', placeholder: 'Add Estimate', type: 'fixedCollection', default: {}, typeOptions: { multipleValues: false, }, options: [ { displayName: 'Estimate', name: 'estimateValues', values: [ { displayName: 'Estimate', name: 'estimate', type: 'number', default: 0, }, { displayName: 'Type', name: 'type', type: 'options', options: [ { name: 'Auto', value: 'AUTO', }, { name: 'Manual', value: 'MANUAL', }, ], default: 'AUTO', }, ], }, ], }, { displayName: 'Is Public', name: 'isPublic', type: 'boolean', default: false, }, { displayName: 'Name', name: 'name', type: 'string', default: '', }, { displayName: 'Note', name: 'note', type: 'string', default: '', description: 'Note about the project', }, ], }, ];
the_stack
import * as React from "react"; import * as CodeMirrorComp from 'react-codemirror2' import {getTimingFromString} from "../../data/utils"; import ChildCallbackHack from "../player/ChildCallbackHack"; const actions = ["blink", "cap", "bigcap", "count", "wait", "playAudio", "advance"]; export const tupleSetters = ["setBlinkDuration", "setBlinkDelay", "setBlinkGroupDelay", "setCaptionDuration", "setCaptionDelay", "setCountDuration", "setCountDelay", "setCountGroupDelay"]; export const singleSetters = ["setBlinkWaveRate", "setBlinkBPMMulti", "setBlinkDelayWaveRate", "setBlinkDelayBPMMulti", "setBlinkGroupDelayWaveRate", "setBlinkGroupDelayBPMMulti", "setBlinkOpacity", "setBlinkX", "setBlinkY", "setCaptionWaveRate", "setCaptionBPMMulti", "setCaptionDelayWaveRate", "setCaptionDelayBPMMulti", "setCaptionOpacity", "setCaptionX", "setCaptionY", "setBigCaptionX", "setBigCaptionY", "setCountWaveRate", "setCountBPMMulti", "setCountDelayWaveRate", "setCountDelayBPMMulti", "setCountGroupDelayWaveRate", "setCountGroupDelayBPMMulti", "setCountOpacity", "setCountX", "setCountY", "setCountProgressScale"]; export const stringSetters = ["setBlinkTF", "setBlinkDelayTF", "setBlinkGroupDelayTF", "setCaptionTF", "setCaptionDelayTF", "setCountTF", "setCountDelayTF", "setCountGroupDelayTF"]; export const booleanSetters = ["setShowCountProgress", "setCountProgressOffset", "setCountColorMatch"]; export const colorSetters = ["setCountProgressColor"] const storers = ["storephrase", "storePhrase", "storeAudio"]; const keywords = ["$RANDOM_PHRASE", "$TAG_PHRASE"]; export const timestampRegex = /^((\d?\d:)?\d?\d:\d\d(\.\d\d?\d?)?|\d?\d(\.\d\d?\d?)?)$/; (function(mod) { mod(require("codemirror/lib/codemirror")); })(function(CodeMirror: any) { CodeMirror.defineMode('flipflip', function() { let words: any = {}; function define(style: any, dict: any) { for(let i = 0; i < dict.length; i++) { words[dict[i]] = style; } } CodeMirror.registerHelper("hintWords", "flipflip", actions.concat(tupleSetters, singleSetters, stringSetters, booleanSetters, colorSetters, keywords, storers)); define('atom', tupleSetters); define('atom', singleSetters); define('atom', stringSetters); define('atom', booleanSetters); define('atom', colorSetters); define('variable', keywords); define('variable-3', storers); define('builtin', actions); function parse(stream: any, state: any) { if (stream.eatSpace()) return rt(null, state, stream); let sol = stream.sol(); const ch = stream.next(); if (ch === '#' && sol) { stream.skipToEnd(); return "comment"; } let command = null; let timestamp = false; if (state.tokens.length > 0) { if (timestampRegex.exec(state.tokens[0]) != null) { timestamp = true; if (state.tokens.length > 1) { command = state.tokens[1]; } else { sol = true; } } else { command = state.tokens[0]; } } if (ch === "/" && command == "blink") { state.tokens.push(ch); return rt("operator", state, stream); } if (ch === "\\" && !stream.eol() && /n/.test(stream.peek()) && !sol && (command == "blink" || command == "cap" || command == "bigcap")) { stream.next(); state.tokens.push(ch); return rt("operator", state, stream); } if (ch === "$" && command != null && command.toLowerCase() == "storephrase") { stream.next(); if(stream.eol() || /\s/.test(stream.peek())) { state.tokens.push(stream.current()); return rt("number", state, stream); } } if (/\d/.test(ch) && sol && !timestamp) { // Timestamp stream.eatWhile(/[\d:.]/); if(stream.eol() || !/\w/.test(stream.peek())) { const timestamp = stream.current(); state.tokens.push(timestamp); if (timestampRegex.exec(timestamp) != null) { return rt("number", state, stream); } else { return rt("error", state, stream); } } } if (/[-\d]/.test(ch) && (command == "count" || command == "wait" || tupleSetters.includes(command) || singleSetters.includes(command) || colorSetters.includes(command) || (command == "playAudio" && state.tokens.length == (timestamp ? 3 : 2)))) { // Number parameter stream.eatWhile(/\d/); if(stream.eol() || !/\w/.test(stream.peek())) { const cur = stream.current(); state.tokens.push(cur); if (command == "playAudio" && (cur > 100 || cur < 0)) { return rt("error", state, stream); } else if (((command == "count" || command == "playAudio" || tupleSetters.includes(command)) && state.tokens.length > (timestamp ? 4 : 3)) || ((command == "wait" || singleSetters.includes(command)) && state.tokens.length > (timestamp ? 3 : 2))) { return rt("error", state, stream); } return rt("number", state, stream); } } if (command == "storeAudio" && state.tokens.length == (timestamp ? 2 : 1)) { if (ch == "'") { stream.eatWhile(/[^']/); if (stream.eol() || !/'/.test(stream.peek())) { return rt("error", state, stream); } stream.next(); } else if (ch == "\"") { stream.eatWhile(/[^"]/); if (stream.eol() || !/"/.test(stream.peek())) { return rt("error", state, stream); } stream.next(); } else { stream.eatWhile(/[\d\w-]/); } } else { stream.eatWhile(/[\d\w-]/); } const cur = stream.current(); stream.eatSpace(); state.tokens.push(cur); if (command == "advance") { return rt("error", state, stream); } else if (sol && words.hasOwnProperty(cur) && !keywords.includes(cur)) { // Command at start of line return rt(words[cur], state, stream); } else if (!sol && command == "blink" && (keywords.includes(cur) || /^\$\d$/.exec(cur) != null)) { // Keyword in blink command if ((state.tokens.length == (timestamp ? 3 : 2) || state.tokens[state.tokens.length - 2] == "/") && (stream.eol() || /\//.test(stream.peek()))) { if (cur == "$RANDOM_PHRASE" && !state.storedPhrases.has(0)) { return rt("error", state, stream); } else { const registerRegex = /^\$(\d)$/.exec(cur); if (registerRegex != null) { if (!state.storedPhrases.has(parseInt(registerRegex[1]))) { return rt("error", state, stream); } else { return rt("variable", state, stream); } } } return rt(words[cur], state, stream); } else { return rt("string", state, stream); } } else if (!sol && (command == "cap" || command == "bigcap") && (keywords.includes(cur) || /^\$\d$/.exec(cur) != null)) { // Keyword in a cap or bigcap command if (state.tokens.length == (timestamp ? 3 : 2) && stream.eol()) { if (cur == "$RANDOM_PHRASE" && !state.storedPhrases.has(0)) { return rt("error", state, stream); } else { const registerRegex = /^\$(\d)$/.exec(cur); if (registerRegex != null) { if (!state.storedPhrases.has(parseInt(registerRegex[1]))) { return rt("error", state, stream); } else { return rt("variable", state, stream); } } } return rt(words[cur], state, stream); } else { return rt("string", state, stream); } } else if (!sol && state.tokens.length > 0) { // String Parameter if (command == "blink" && cur == "/") { return rt("operator", state, stream); } else if (command == "count" || command == "wait" || tupleSetters.includes(command) || singleSetters.includes(command)) { return rt("error", state, stream); } else if (stringSetters.includes(command)) { const tf = getTimingFromString(cur); return rt(tf == null ? "error" : "variable", state, stream); } else if (booleanSetters.includes(command)) { if (cur.toLowerCase() == "true" || cur.toLowerCase() == "t" || cur.toLowerCase() == "false" || cur.toLowerCase() == "f") { return rt("number", state, stream); } else { return rt("error", state, stream); } } else if (colorSetters.includes(command)) { const colorRegex = /^#([a-f0-9]{3}){1,2}$/i.exec(cur); if (colorRegex != null) { return rt("variable-3", state, stream); } else { return rt("error", state, stream); } } else if (command == "playAudio" && state.tokens.length > (timestamp ? 3 : 2)) { return rt("error", state, stream); } else if (command == "storeAudio" && state.tokens.length > (timestamp ? 4 : 3)) { return rt("error", state, stream); } return rt("string", state, stream); } else { return rt("error", state, stream); } } function rt(type: string, state: any, stream: any) { if (stream.eol()) { if (state.tokens.length > 0 && state.tokens[0].toLowerCase() == "storephrase") { const registerRegex = /^\$(\d)$/.exec(state.tokens[1]); if (registerRegex != null) { if (state.tokens.length > 1) { state.storedPhrases.set(parseInt(registerRegex[1]), true); state.storedPhrases.set(0, true); } } else { state.storedPhrases.set(0, true); } } state.tokens = new Array<string>(); } return type; } return { startState: function() {return {tokens: new Array<string>(), storedPhrases: new Map<number, boolean>()};}, token: function(stream: any, state: any) { return parse(stream, state); }, }; }); }); export default class CodeMirror extends React.Component { readonly props: { onGutterClick(editor: any, clickedLine: number): void onUpdateScript(text: string, changed?: boolean): void, addHack?: ChildCallbackHack, className?: string, overwriteHack?: ChildCallbackHack, } readonly state = { scriptText: "", cursor: {line: 0, ch: 0}, } render() { return ( <CodeMirrorComp.Controlled className={this.props.className} value={this.state.scriptText} autoScroll={false} options={{ mode: 'flipflip', theme: 'material', lineNumbers: true, lineWrapping: true, viewportMargin: Infinity, }} onBeforeChange={this.onBeforeChangeScript.bind(this)} onCursorActivity={this.onCursorActivity.bind(this)} onGutterClick={this.props.onGutterClick} /> ); } componentDidMount() { if (this.props.addHack) { this.props.addHack.listener = (args) => { let string: string = args[0]; const newLine: boolean = args[1]; let newValue = ""; if (newLine == true) { const lines = this.state.scriptText.split('\n'); for (let l = 0; l < lines.length; l++) { if (l == this.state.cursor.line + 1) { if (lines[l].length > 0) { newValue += "\n"; } newValue += string + "\n" + lines[l]; } else if (l == lines.length - 1) { newValue += "\n" + lines[l] + "\n" + string; } else { newValue += "\n" + lines[l]; } } } else { const lines = this.state.scriptText.split('\n'); for (let l = 0; l < lines.length; l++) { if (l == this.state.cursor.line) { let newLine = lines[l]; newLine = newLine.slice(0, this.state.cursor.ch) + string + newLine.slice(this.state.cursor.ch); newValue += "\n" + newLine; } else { newValue += "\n" + lines[l]; } } } newValue = newValue.trim(); this.onUpdateScript(newValue); } } if (this.props.overwriteHack) { this.props.overwriteHack.listener = (args) => { this.onUpdateScript(args[0]); } } } componentWillUnmount() { if (this.props.addHack) { this.props.addHack.listener = null; } if (this.props.overwriteHack) { this.props.overwriteHack.listener = null; } } _sendUpdate: NodeJS.Timeout = null; onBeforeChangeScript(editor: any, data: any, value: any) { if (this.state.scriptText != value) { this.onUpdateScript(value, editor, true); } } onCursorActivity(editor: any) { this.setState({cursor: editor.getDoc().getCursor()}); } onUpdateScript(scriptText: any, editor?: any, changed = false) { if (editor) { this.setState({scriptText: scriptText, cursor: editor.getDoc().getCursor()}); } else { this.setState({scriptText: scriptText}); } clearTimeout(this._sendUpdate); this._sendUpdate = setTimeout(this.props.onUpdateScript.bind(this, scriptText, changed), 500); } } (CodeMirror as any).displayName="CodeMirror";
the_stack
import { Arbitrary } from '../../../../src/check/arbitrary/definition/Arbitrary'; import { Shrinkable } from '../../../../src/check/arbitrary/definition/Shrinkable'; import { property } from '../../../../src/check/property/Property'; import { pre } from '../../../../src/check/precondition/Pre'; import { PreconditionFailure } from '../../../../src/check/precondition/PreconditionFailure'; import { configureGlobal, resetConfigureGlobal } from '../../../../src/check/runner/configuration/GlobalParameters'; import * as stubArb from '../../stubs/arbitraries'; import * as stubRng from '../../stubs/generators'; import { fakeNextArbitrary } from '../../arbitrary/__test-helpers__/NextArbitraryHelpers'; import { convertFromNext } from '../../../../src/check/arbitrary/definition/Converters'; import { convertToNextProperty } from '../../../../src/check/property/ConvertersProperty'; import { NextValue } from '../../../../src/check/arbitrary/definition/NextValue'; import { Stream } from '../../../../src/stream/Stream'; describe('Property', () => { afterEach(() => resetConfigureGlobal()); it('Should fail if predicate fails', () => { const p = property(stubArb.single(8), (_arg: number) => { return false; }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); // property fails }); it('Should fail if predicate throws', () => { const p = property(stubArb.single(8), (_arg: number) => { throw 'predicate throws'; }); const out = p.run(p.generate(stubRng.mutable.nocall()).value); expect(out).toEqual('predicate throws'); }); it('Should fail if predicate throws an Error', () => { const p = property(stubArb.single(8), (_arg: number) => { throw new Error('predicate throws'); }); const out = p.run(p.generate(stubRng.mutable.nocall()).value); expect(out).toContain('predicate throws'); expect(out).toContain('\n\nStack trace:'); }); it('Should forward failure of runs with failing precondition', async () => { let doNotResetThisValue = false; const p = property(stubArb.single(8), (_arg: number) => { pre(false); doNotResetThisValue = true; return false; }); const out = p.run(p.generate(stubRng.mutable.nocall()).value); expect(PreconditionFailure.isFailure(out)).toBe(true); expect(doNotResetThisValue).toBe(false); // does not run code after the failing precondition }); it('Should succeed if predicate is true', () => { const p = property(stubArb.single(8), (_arg: number) => { return true; }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should succeed if predicate does not return anything', () => { const p = property(stubArb.single(8), (_arg: number) => {}); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should call and forward arbitraries one time', () => { let oneCallToPredicate = false; const arbs: [ stubArb.SingleUseArbitrary<number>, stubArb.SingleUseArbitrary<string>, stubArb.SingleUseArbitrary<string> ] = [stubArb.single(3), stubArb.single('hello'), stubArb.single('world')]; const p = property(arbs[0], arbs[1], arbs[2], (arg1: number, _arb2: string, _arg3: string) => { if (oneCallToPredicate) { throw 'Predicate has already been evaluated once'; } oneCallToPredicate = true; return arg1 === arbs[0].id; }); expect(oneCallToPredicate).toBe(false); // property creation does not trigger call to predicate for (let idx = 0; idx !== arbs.length; ++idx) { expect(arbs[idx].calledOnce).toBe(false); // property creation does not trigger call to generator #${idx + 1} } expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(oneCallToPredicate).toBe(true); for (let idx = 0; idx !== arbs.length; ++idx) { expect(arbs[idx].calledOnce).toBe(true); // Generator #${idx + 1} called by run } }); it('Should throw on invalid arbitrary', () => expect(() => property(stubArb.single(8), stubArb.single(8), {} as Arbitrary<any>, () => {})).toThrowError()); it('Should use the unbiased arbitrary by default', () => { const p = property( new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(69); } withBias(): Arbitrary<number> { throw 'Should not call withBias if not forced to'; } })(), () => {} ); expect(p.generate(stubRng.mutable.nocall()).value).toEqual([69]); }); it('Should use the biased arbitrary when asked to', () => { const p = property( new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(69); } withBias(freq: number): Arbitrary<number> { if (typeof freq !== 'number' || freq < 2) { throw new Error(`freq atribute must always be superior or equal to 2, got: ${freq}`); } return new (class extends Arbitrary<number> { generate(): Shrinkable<number> { return new Shrinkable(42); } })(); } })(), () => {} ); expect(p.generate(stubRng.mutable.nocall(), 0).value).toEqual([42]); expect(p.generate(stubRng.mutable.nocall(), 2).value).toEqual([42]); }); it('Should always execute beforeEach before the test', () => { const prob = { beforeEachCalled: false }; const p = property(stubArb.single(8), (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }) .beforeEach((globalBeforeEach) => { prob.beforeEachCalled = false; globalBeforeEach(); }) .beforeEach((previousBeforeEach) => { previousBeforeEach(); prob.beforeEachCalled = true; }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('Should execute both global and local beforeEach hooks before the test', () => { const globalBeforeEach = jest.fn(); const prob = { beforeEachCalled: false }; configureGlobal({ beforeEach: globalBeforeEach, }); const p = property(stubArb.single(8), (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }).beforeEach((globalBeforeEach) => { prob.beforeEachCalled = true; globalBeforeEach(); }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(globalBeforeEach).toBeCalledTimes(1); }); it('Should use global beforeEach as default if specified', () => { const prob = { beforeEachCalled: false }; configureGlobal({ beforeEach: () => (prob.beforeEachCalled = true), }); const p = property(stubArb.single(8), (_arg: number) => { const beforeEachCalled = prob.beforeEachCalled; prob.beforeEachCalled = false; return beforeEachCalled; }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); }); it('should fail if global asyncBeforeEach has been set', () => { configureGlobal({ asyncBeforeEach: () => {}, }); expect(() => property(stubArb.single(8), (_arg: number) => {})).toThrowError( '"asyncBeforeEach" can\'t be set when running synchronous properties' ); }); it('Should execute afterEach after the test on success', () => { const callOrder: string[] = []; const p = property(stubArb.single(8), (_arg: number) => { callOrder.push('test'); return true; }) .afterEach((globalAfterEach) => { callOrder.push('afterEach'); globalAfterEach(); }) .afterEach((previousAfterEach) => { previousAfterEach(); callOrder.push('after afterEach'); }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(callOrder).toEqual(['test', 'afterEach', 'after afterEach']); }); it('Should execute afterEach after the test on failure', () => { const callOrder: string[] = []; const p = property(stubArb.single(8), (_arg: number) => { callOrder.push('test'); return false; }).afterEach(() => callOrder.push('afterEach')); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should execute afterEach after the test on uncaught exception', () => { const callOrder: string[] = []; const p = property(stubArb.single(8), (_arg: number) => { callOrder.push('test'); throw new Error('uncaught'); }).afterEach(() => callOrder.push('afterEach')); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should use global afterEach as default if specified', () => { const callOrder: string[] = []; configureGlobal({ afterEach: () => callOrder.push('afterEach'), }); const p = property(stubArb.single(8), (_arg: number) => { callOrder.push('test'); return false; }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).not.toBe(null); expect(callOrder).toEqual(['test', 'afterEach']); }); it('Should execute both global and local afterEach hooks', () => { const callOrder: string[] = []; configureGlobal({ afterEach: () => callOrder.push('globalAfterEach'), }); const p = property(stubArb.single(8), (_arg: number) => { callOrder.push('test'); return true; }).afterEach((globalAfterEach) => { callOrder.push('afterEach'); globalAfterEach(); }); expect(p.run(p.generate(stubRng.mutable.nocall()).value)).toBe(null); expect(callOrder).toEqual(['test', 'afterEach', 'globalAfterEach']); }); it('should fail if global asyncAfterEach has been set', () => { configureGlobal({ asyncAfterEach: () => {}, }); expect(() => property(stubArb.single(8), (_arg: number) => {})).toThrowError( '"asyncAfterEach" can\'t be set when running synchronous properties' ); }); it('should not call shrink on the arbitrary if no context and not unhandled value', () => { // Arrange const { instance: arb, shrink, canShrinkWithoutContext } = fakeNextArbitrary(); canShrinkWithoutContext.mockReturnValue(false); const value = Symbol(); // Act const p = convertToNextProperty(property(convertFromNext(arb), jest.fn())); const shrinks = p.shrink(new NextValue([value], undefined)); // context=undefined in the case of user defined values // Assert expect(canShrinkWithoutContext).toHaveBeenCalledWith(value); expect(canShrinkWithoutContext).toHaveBeenCalledTimes(1); expect(shrink).not.toHaveBeenCalled(); expect([...shrinks]).toEqual([]); }); it('should call shrink on the arbitrary if no context but properly handled value', () => { // Arrange const { instance: arb, shrink, canShrinkWithoutContext } = fakeNextArbitrary(); canShrinkWithoutContext.mockReturnValue(true); const s1 = Symbol(); const s2 = Symbol(); shrink.mockReturnValue(Stream.of(new NextValue<symbol>(s1, undefined), new NextValue(s2, undefined))); const value = Symbol(); // Act const p = convertToNextProperty(property(convertFromNext(arb), jest.fn())); const shrinks = p.shrink(new NextValue([value], undefined)); // context=undefined in the case of user defined values // Assert expect(canShrinkWithoutContext).toHaveBeenCalledWith(value); expect(canShrinkWithoutContext).toHaveBeenCalledTimes(1); expect(shrink).toHaveBeenCalledWith(value, undefined); expect(shrink).toHaveBeenCalledTimes(1); expect([...shrinks].map((s) => s.value_)).toEqual([[s1], [s2]]); }); });
the_stack
// tslint:disable:no-unused-expression // tslint:disable:max-func-body-length import * as assert from "assert"; import { ContainsBehavior, Issue, IssueKind, LineColPos, Span } from "../extension.bundle"; suite("Language", () => { suite("Span", () => { suite("constructor()", () => { function constructorTest(startIndex: number, length: number): void { test(`with [${startIndex},${length})`, () => { const span = new Span(startIndex, length); assert.deepStrictEqual(span.startIndex, startIndex); assert.deepStrictEqual(span.length, length); assert.deepStrictEqual(span.endIndex, startIndex + (length > 0 ? length - 1 : 0), "Wrong endIndex"); assert.deepStrictEqual(span.afterEndIndex, startIndex + length, "Wrong afterEndIndex"); }); } constructorTest(-1, 3); constructorTest(0, 3); constructorTest(10, -3); constructorTest(11, 0); constructorTest(21, 3); }); suite("contains()", () => { suite("ContainsBehavior.strict", () => { test("With index less than startIndex", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(2, ContainsBehavior.strict)); }); test("With index equal to startIndex", () => { assert(new Span(3, 4).contains(3, ContainsBehavior.strict)); }); test("With index between the start and end indexes", () => { assert(new Span(3, 4).contains(5, ContainsBehavior.strict)); }); test("With index equal to endIndex", () => { assert(new Span(3, 4).contains(6, ContainsBehavior.strict)); }); test("With index directly after end index", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(7, ContainsBehavior.strict)); }); }); suite("ContainsBehavior.extended", () => { test("With index less than startIndex", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(2, ContainsBehavior.extended)); }); test("With index equal to startIndex", () => { assert(new Span(3, 4).contains(3, ContainsBehavior.extended)); }); test("With index between the start and end indexes", () => { assert(new Span(3, 4).contains(5, ContainsBehavior.extended)); }); test("With index equal to endIndex", () => { assert(new Span(3, 4).contains(6, ContainsBehavior.extended)); }); test("With index directly after end index", () => { // Extended, so this should be true assert.deepStrictEqual(true, new Span(3, 4).contains(7, ContainsBehavior.extended)); }); test("With index two after end index", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(8, ContainsBehavior.extended)); }); }); suite("ContainsBehavior.enclosed", () => { test("With index less than startIndex", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(2, ContainsBehavior.enclosed)); }); test("With index equal to startIndex", () => { // With enclosed, this should be false assert.equal(new Span(3, 4).contains(3, ContainsBehavior.enclosed), false); }); test("With index between the start and end indexes", () => { assert(new Span(3, 4).contains(5, ContainsBehavior.enclosed)); }); test("With index equal to endIndex", () => { assert(new Span(3, 4).contains(6, ContainsBehavior.enclosed)); }); test("With index directly after end index", () => { assert.deepStrictEqual(false, new Span(3, 4).contains(7, ContainsBehavior.enclosed)); }); }); }); suite("union()", () => { test("With null", () => { let s = new Span(5, 7); assert.deepStrictEqual(s, s.union(undefined)); }); test("With same span", () => { let s = new Span(5, 7); assert.deepEqual(s, s.union(s)); }); test("With equal span", () => { let s = new Span(5, 7); assert.deepEqual(s, s.union(new Span(5, 7))); }); test("With subset span", () => { let s = new Span(5, 17); assert.deepEqual(s, s.union(new Span(10, 2))); }); }); suite("intersect()", () => { test("With null", () => { let s = Span.fromStartAndAfterEnd(5, 7); assert.deepStrictEqual(s.intersect(undefined), undefined); }); test("With same span", () => { let s = Span.fromStartAndAfterEnd(5, 7); assert.deepEqual(s, s.intersect(s)); }); test("With equal span", () => { let s = Span.fromStartAndAfterEnd(5, 7); assert.deepEqual(s, s.intersect(new Span(5, 7))); }); test("second span to left", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(Span.fromStartAndAfterEnd(0, 9)), undefined ); }); test("second touches the left", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(Span.fromStartAndAfterEnd(0, 10)), // Two results could be argued here: len 0 span at 10, or undefined // We'll go with the former until sometimes finds a reason why it should // be different new Span(10, 0) ); }); test("second span to left and overlap", () => { assert.deepEqual( new Span(10, 20).intersect(new Span(0, 11)), new Span(10, 1) ); }); test("second span is superset", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(Span.fromStartAndAfterEnd(0, 21)), Span.fromStartAndAfterEnd(10, 20) ); }); test("second span is subset", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(new Span(11, 8)), new Span(11, 8) ); }); test("second span is len 0 subset, touching on the left", () => { assert.deepEqual( new Span(10, 10).intersect(new Span(10, 0)), new Span(10, 0) ); }); test("second span is len 0 subset, touching on the right", () => { assert.deepEqual( new Span(10, 10).intersect(new Span(20, 0)), new Span(20, 0) ); }); test("second span to right and overlapping", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(new Span(19, 10)), new Span(19, 1) ); }); test("second span to right", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(new Span(21, 9)), undefined ); }); test("length 0", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(new Span(15, 0)), new Span(15, 0) ); }); test("length 1", () => { assert.deepEqual( Span.fromStartAndAfterEnd(10, 20).intersect(new Span(15, 1)), new Span(15, 1) ); }); }); suite("translate()", () => { test("with 0 movement", () => { const span = new Span(1, 2); assert.equal(span.translate(0), span); assert.deepStrictEqual(span.translate(0), new Span(1, 2)); }); test("with 1 movement", () => { const span = new Span(1, 2); assert.notEqual(span.translate(1), new Span(2, 2)); assert.deepStrictEqual(span.translate(1), new Span(2, 2)); }); test("with -1 movement", () => { const span = new Span(1, 2); assert.notEqual(span.translate(-1), new Span(0, 2)); assert.deepStrictEqual(span.translate(-1), new Span(0, 2)); }); }); test("toString()", () => { assert.deepStrictEqual(new Span(1, 2).toString(), "[1, 3)"); }); }); suite("Position", () => { suite("constructor(number,number)", () => { test("With null _line", () => { // tslint:disable-next-line:no-any assert.throws(() => { new LineColPos(<any>null, 3); }); }); test("With undefined _line", () => { // tslint:disable-next-line:no-any assert.throws(() => { new LineColPos(<any>undefined, 3); }); }); test("With negative _line", () => { assert.throws(() => { new LineColPos(-1, 3); }); }); test("With null _column", () => { // tslint:disable-next-line:no-any assert.throws(() => { new LineColPos(2, <any>null); }); }); test("With undefined _column", () => { // tslint:disable-next-line:no-any assert.throws(() => { new LineColPos(2, <any>undefined); }); }); test("With negative _column", () => { assert.throws(() => { new LineColPos(2, -3); }); }); test("With valid arguments", () => { const p = new LineColPos(2, 3); assert.deepStrictEqual(p.line, 2); assert.deepStrictEqual(p.column, 3); }); }); }); suite("Issue", () => { suite("constructor(Span,string)", () => { test("With null span", () => { // tslint:disable-next-line:no-any assert.throws(() => { new Issue(<any>null, "error message", IssueKind.tleSyntax); }); }); test("With undefined span", () => { // tslint:disable-next-line:no-any assert.throws(() => { new Issue(<any>undefined, "error message", IssueKind.tleSyntax); }); }); test("With null message", () => { // tslint:disable-next-line:no-any assert.throws(() => { new Issue(new Span(4, 1), <any>null, IssueKind.tleSyntax); }); }); test("With undefined message", () => { // tslint:disable-next-line:no-any assert.throws(() => { new Issue(new Span(4, 1), <any>undefined, IssueKind.tleSyntax); }); }); test("With empty message", () => { assert.throws(() => { new Issue(new Span(3, 2), "", IssueKind.tleSyntax); }); }); test("With valid arguments", () => { const issue = new Issue(new Span(2, 4), "error message", IssueKind.tleSyntax); assert.deepStrictEqual(issue.span, new Span(2, 4)); assert.deepStrictEqual(issue.message, "error message"); }); }); }); });
the_stack
import 'reflect-metadata'; import { createApplication, createModule, Injectable, Inject, InjectionToken, CONTEXT, MODULE_ID, Scope, gql, testkit, } from '../src'; import { execute } from 'graphql'; import { ExecutionContext } from '../src/di'; const Test = new InjectionToken<string>('test'); const posts = ['Foo', 'Bar']; const comments = ['Comment #1', 'Comment #2']; test('general test', async () => { const spies = { logger: jest.fn(), posts: { moduleId: jest.fn(), test: jest.fn(), postService: jest.fn(), eventService: jest.fn(), }, comments: { moduleId: jest.fn(), test: jest.fn(), commentsService: jest.fn(), }, }; @Injectable({ scope: Scope.Operation, }) class Logger { constructor() { spies.logger(); } log() {} } @Injectable({ scope: Scope.Operation, }) class Events { constructor() { spies.posts.eventService(); } emit() {} } @Injectable() class Posts { constructor() { spies.posts.postService(); } all() { return posts; } } @Injectable() class Comments { constructor() { spies.comments.commentsService(); } all() { return comments; } } // Child module const commonModule = createModule({ id: 'common', typeDefs: gql` type Query { _noop: String } `, }); // Child module const postsModule = createModule({ id: 'posts', providers: [ Posts, Events, { provide: Test, useValue: 'mod', }, ], typeDefs: gql` type Post { title: String! } extend type Query { posts: [Post!]! } `, resolvers: { Query: { posts( _parent: {}, __args: {}, { injector }: GraphQLModules.ModuleContext ) { spies.posts.moduleId(injector.get(MODULE_ID)); spies.posts.test(injector.get(Test)); injector.get(Events).emit(); injector.get(Logger).log(); return injector.get(Posts).all(); }, }, Post: { title: (title: any) => title, }, }, }); // Child module const commentsModule = createModule({ id: 'comments', providers: [Comments], typeDefs: gql` type Comment { text: String! } extend type Query { comments: [Comment!]! } `, resolvers: { Query: { comments( _parent: {}, __args: {}, { injector }: GraphQLModules.ModuleContext ) { spies.comments.moduleId(injector.get(MODULE_ID)); spies.comments.test(injector.get(Test)); injector.get(Logger).log(); return injector.get(Comments).all(); }, }, Comment: { text: (text: any) => text, }, }, }); // root module as application const appModule = createApplication({ modules: [commonModule, postsModule, commentsModule], providers: [ Logger, { provide: Test, useValue: 'app', }, ], }); const createContext = () => ({ request: {}, response: {} }); const document = gql` { comments { text } posts { title } } `; const result = await testkit.execute(appModule, { contextValue: createContext(), document, }); // Should resolve data correctly expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ comments: comments.map((text) => ({ text })), posts: posts.map((title) => ({ title })), }); // Child Injector has priority over Parent Injector expect(spies.posts.test).toHaveBeenCalledWith('mod'); expect(spies.comments.test).toHaveBeenCalledWith('app'); // Value of MODULE_ID according to module's resolver expect(spies.posts.moduleId).toHaveBeenCalledWith('posts'); expect(spies.comments.moduleId).toHaveBeenCalledWith('comments'); await testkit.execute(appModule, { contextValue: createContext(), document, }); // Singleton providers should be called once expect(spies.posts.postService).toHaveBeenCalledTimes(1); expect(spies.comments.commentsService).toHaveBeenCalledTimes(1); // Operation provider should be called twice expect(spies.posts.eventService).toHaveBeenCalledTimes(2); expect(spies.logger).toHaveBeenCalledTimes(2); }); test('useFactory with dependecies', async () => { const logSpy = jest.fn(); @Injectable({ scope: Scope.Singleton, }) class Posts { @ExecutionContext() context!: ExecutionContext; all() { const connection = this.context.injector.get(PostsConnection); return connection.all(); } } class PostsConnection { constructor(logger: Logger) { logger.log(); } all() { return posts; } } @Injectable() class Logger { log() { logSpy(); } } const postsModule = createModule({ id: 'posts', providers: [ Logger, Posts, { provide: PostsConnection, scope: Scope.Operation, useFactory(logger: Logger) { return new PostsConnection(logger); }, deps: [Logger], }, ], typeDefs: gql` type Post { title: String! } type Query { posts: [Post!]! } `, resolvers: { Query: { posts( _parent: {}, __args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Posts).all(); }, }, Post: { title: (title: any) => title, }, }, }); const app = createApplication({ modules: [postsModule], }); const createContext = () => ({ request: {}, response: {} }); const document = gql` { posts { title } } `; const data = { posts: posts.map((title) => ({ title })), }; const result1 = await testkit.execute(app, { contextValue: createContext(), document, }); expect(result1.data).toEqual(data); expect(logSpy).toHaveBeenCalledTimes(1); const result2 = await testkit.execute(app, { contextValue: createContext(), document, }); expect(result2.data).toEqual(data); expect(logSpy).toHaveBeenCalledTimes(2); }); test('Use @Inject decorator in constructor', async () => { const request = new Object(); const requestSpy = jest.fn(); @Injectable({ scope: Scope.Operation }) class Auth { constructor(@Inject(CONTEXT) private context: any) {} ping() { requestSpy(this.context.request); return 'pong'; } } const mod = createModule({ id: 'auth', providers: [Auth], typeDefs: gql` type Query { ping: String } `, resolvers: { Query: { ping(_: any, __: any, { injector }: GraphQLModules.ModuleContext) { return injector.get(Auth).ping(); }, }, }, }); const app = createApplication({ modules: [mod] }); const result = await testkit.execute(app, { contextValue: { request }, document: gql` { ping } `, }); expect(result.errors).not.toBeDefined(); expect(result.data).toEqual({ ping: 'pong' }); expect(requestSpy).toHaveBeenCalledWith(request); }); test('Use useFactory with deps', async () => { const request = new Object(); const requestSpy = jest.fn(); const REQUEST = new InjectionToken('request'); @Injectable({ scope: Scope.Operation }) class Auth { constructor(@Inject(REQUEST) private request: any) {} ping() { requestSpy(this.request); return 'pong'; } } const mod = createModule({ id: 'auth', providers: [ Auth, { provide: REQUEST, useFactory(ctx: any) { return ctx.request; }, deps: [CONTEXT], scope: Scope.Operation, }, ], typeDefs: gql` type Query { ping: String } `, resolvers: { Query: { ping(_: any, __: any, { injector }: GraphQLModules.ModuleContext) { return injector.get(Auth).ping(); }, }, }, }); const app = createApplication({ modules: [mod] }); const result = await testkit.execute(app, { contextValue: { request }, document: gql` { ping } `, }); expect(result.errors).not.toBeDefined(); expect(result.data).toEqual({ ping: 'pong' }); expect(requestSpy).toHaveBeenCalledWith(request); }); test('Application allows injector access', () => { @Injectable() class SomeProvider {} const { injector } = createApplication({ modules: [], providers: [SomeProvider], }); expect(injector.get(SomeProvider)).toBeInstanceOf(SomeProvider); }); test('Operation scoped provider should be created once per GraphQL Operation', async () => { const constructorSpy = jest.fn(); const loadSpy = jest.fn(); @Injectable({ scope: Scope.Operation, }) class Dataloader { constructor(@Inject(CONTEXT) context: GraphQLModules.GlobalContext) { constructorSpy(context); } load(id: number) { loadSpy(id); return { id, title: 'Sample Title', }; } } const postsModule = createModule({ id: 'posts', providers: [Dataloader], typeDefs: gql` type Post { id: Int! title: String! } type Query { post(id: Int!): Post! } `, resolvers: { Query: { post( _parent: {}, args: { id: number }, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Dataloader).load(args.id); }, }, }, }); const app = createApplication({ modules: [postsModule], }); const contextValue = { request: {}, response: {} }; const document = gql` { foo: post(id: 1) { id title } bar: post(id: 1) { id title } } `; const result = await testkit.execute(app, { contextValue, document, }); // Should resolve data correctly expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: { id: 1, title: 'Sample Title', }, bar: { id: 1, title: 'Sample Title', }, }); expect(constructorSpy).toHaveBeenCalledTimes(1); expect(constructorSpy).toHaveBeenCalledWith( expect.objectContaining(contextValue) ); expect(loadSpy).toHaveBeenCalledTimes(2); expect(loadSpy).toHaveBeenCalledWith(1); }); test('Operation scoped provider should be created once per GraphQL Operation (Apollo Server)', async () => { const constructorSpy = jest.fn(); const loadSpy = jest.fn(); @Injectable({ scope: Scope.Operation, }) class Dataloader { constructor(@Inject(CONTEXT) context: GraphQLModules.GlobalContext) { constructorSpy(context); } load(id: number) { loadSpy(id); return { id, title: 'Sample Title', }; } } const postsModule = createModule({ id: 'posts', providers: [Dataloader], typeDefs: gql` type Post { id: Int! title: String! } type Query { post(id: Int!): Post! } `, resolvers: { Query: { post( _parent: {}, args: { id: number }, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Dataloader).load(args.id); }, }, }, }); const app = createApplication({ modules: [postsModule], }); const schema = app.createSchemaForApollo(); const contextValue = { request: {}, response: {} }; const document = gql` { foo: post(id: 1) { id title } bar: post(id: 1) { id title } } `; const result = await execute({ schema, contextValue, document, }); // Should resolve data correctly expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: { id: 1, title: 'Sample Title', }, bar: { id: 1, title: 'Sample Title', }, }); expect(constructorSpy).toHaveBeenCalledTimes(1); expect(constructorSpy).toHaveBeenCalledWith( expect.objectContaining(contextValue) ); expect(loadSpy).toHaveBeenCalledTimes(2); expect(loadSpy).toHaveBeenCalledWith(1); }); test('Singleton scoped provider should be created once', async () => { const constructorSpy = jest.fn(); @Injectable({ scope: Scope.Singleton, }) class Data { constructor() { constructorSpy(); } lorem() { return 'ipsum'; } } const mod = createModule({ id: 'mod', // providers: [Data], typeDefs: gql` type Query { lorem: String! } `, resolvers: { Query: { lorem( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const app = createApplication({ modules: [mod], providers: [Data], }); const contextValue = { request: {}, response: {} }; const document = gql` { lorem } `; const execution = app.createExecution(); const result1 = await execution({ schema: app.schema, contextValue, document, }); expect(result1.errors).toBeUndefined(); expect(result1.data).toEqual({ lorem: 'ipsum', }); expect(constructorSpy).toHaveBeenCalledTimes(1); const result2 = await execution({ schema: app.schema, contextValue, document, }); expect(result2.errors).toBeUndefined(); expect(result2.data).toEqual({ lorem: 'ipsum', }); expect(constructorSpy).toHaveBeenCalledTimes(1); }); test('Global Token provided by one module should be accessible by other modules (operation)', async () => { @Injectable({ scope: Scope.Operation, global: true, }) class Data { lorem() { return 'ipsum'; } } const fooModule = createModule({ id: 'foo', providers: [Data], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const barModule = createModule({ id: 'bar', typeDefs: gql` extend type Query { bar: String! } `, resolvers: { Query: { bar( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const app = createApplication({ modules: [fooModule, barModule], }); const contextValue = { request: {}, response: {} }; const document = gql` { foo bar } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: 'ipsum', bar: 'ipsum', }); }); test('Global Token (module) should use other local tokens (operation)', async () => { const LogLevel = new InjectionToken<string>('log-level'); const logger = jest.fn(); @Injectable({ scope: Scope.Operation, global: true, }) class Data { constructor(@Inject(LogLevel) private logLevel: string) {} lorem() { logger(this.logLevel); return 'ipsum'; } } @Injectable({ scope: Scope.Operation, }) class AppData { constructor(private data: Data) {} ispum() { return this.data.lorem(); } } const fooModule = createModule({ id: 'foo', providers: [Data, { provide: LogLevel, useValue: 'info' }], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const barModule = createModule({ id: 'bar', providers: [ { provide: LogLevel, useValue: 'error', scope: Scope.Operation, }, ], typeDefs: gql` extend type Query { bar: String! } `, resolvers: { Query: { bar( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const app = createApplication({ modules: [fooModule, barModule], providers: [ AppData, { provide: LogLevel, useValue: 'verbose', scope: Scope.Operation, }, ], }); const contextValue = { request: {}, response: {} }; const document = gql` { foo bar } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: 'ipsum', bar: 'ipsum', }); expect(logger).toHaveBeenCalledTimes(2); expect(logger).toHaveBeenNthCalledWith(1, 'info'); expect(logger).toHaveBeenNthCalledWith(2, 'info'); }); test('Global Token provided by one module should be accessible by other modules (singleton)', async () => { @Injectable({ scope: Scope.Singleton, global: true, }) class Data { lorem() { return 'ipsum'; } } @Injectable({ scope: Scope.Singleton, }) class AppData { constructor(private data: Data) {} ispum() { return this.data.lorem(); } } const fooModule = createModule({ id: 'foo', providers: [Data], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const barModule = createModule({ id: 'bar', typeDefs: gql` extend type Query { bar: String! } `, resolvers: { Query: { bar( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const app = createApplication({ modules: [fooModule, barModule], providers: [AppData], }); const contextValue = { request: {}, response: {} }; const document = gql` { foo bar } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: 'ipsum', bar: 'ipsum', }); }); test('Global Token (module) should use other local tokens (singleton)', async () => { const LogLevel = new InjectionToken<string>('log-level'); const logger = jest.fn(); @Injectable({ scope: Scope.Singleton, global: true, }) class Data { constructor(@Inject(LogLevel) private logLevel: string) {} lorem() { logger(this.logLevel); return 'ipsum'; } } @Injectable({ scope: Scope.Singleton, }) class AppData { constructor(private data: Data) {} ispum() { return this.data.lorem(); } } const fooModule = createModule({ id: 'foo', providers: [Data, { provide: LogLevel, useValue: 'info' }], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const barModule = createModule({ id: 'bar', providers: [ { provide: LogLevel, useValue: 'error', }, ], typeDefs: gql` extend type Query { bar: String! } `, resolvers: { Query: { bar( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).lorem(); }, }, }, }); const app = createApplication({ modules: [fooModule, barModule], providers: [ AppData, { provide: LogLevel, useValue: 'verbose', }, ], }); const contextValue = { request: {}, response: {} }; const document = gql` { foo bar } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: 'ipsum', bar: 'ipsum', }); expect(logger).toHaveBeenCalledTimes(2); expect(logger).toHaveBeenNthCalledWith(1, 'info'); expect(logger).toHaveBeenNthCalledWith(2, 'info'); }); test('instantiate all singleton providers', async () => { const spies = { logger: jest.fn(), data: jest.fn(), appData: jest.fn(), }; @Injectable() class MyLogger { constructor() { spies.logger(); } } @Injectable() class Data { constructor(logger: MyLogger) { spies.data(logger); } value() { return 'foo'; } } @Injectable() class AppData { constructor() { spies.appData(); } } const fooModule = createModule({ id: 'foo', providers: [Data], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).value(); }, }, }, }); const app = createApplication({ modules: [fooModule], providers: [AppData, MyLogger], }); // make sure all providers are instantiated expect(spies.logger).toBeCalledTimes(1); expect(spies.data).toBeCalledTimes(1); expect(spies.appData).toBeCalledTimes(1); const contextValue = { request: {}, response: {} }; const document = gql` { foo } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ foo: 'foo', }); // make sure no providers are instantiated again expect(spies.logger).toBeCalledTimes(1); expect(spies.data).toBeCalledTimes(1); expect(spies.appData).toBeCalledTimes(1); }); test('instantiate all singleton and global providers', async () => { const spies = { logger: jest.fn(), data: jest.fn(), appData: jest.fn(), }; @Injectable() class MyLogger { constructor() { spies.logger(); } } @Injectable({ global: true, }) class Data { constructor(logger: MyLogger) { spies.data(logger); } value() { return 'foo'; } } @Injectable() class AppData { constructor() { spies.appData(); } } const fooModule = createModule({ id: 'foo', providers: [Data], typeDefs: gql` type Query { foo: String! } `, resolvers: { Query: { foo() {}, }, }, }); const barModule = createModule({ id: 'bar', typeDefs: gql` extend type Query { bar: String! } `, resolvers: { Query: { bar( _parent: {}, _args: {}, { injector }: GraphQLModules.ModuleContext ) { return injector.get(Data).value(); }, }, }, }); const app = createApplication({ modules: [fooModule, barModule], providers: [AppData, MyLogger], }); // make sure all providers are instantiated expect(spies.logger).toBeCalledTimes(1); expect(spies.data).toBeCalledTimes(1); expect(spies.appData).toBeCalledTimes(1); const contextValue = { request: {}, response: {} }; const document = gql` { bar } `; const result = await testkit.execute(app, { contextValue, document, }); expect(result.errors).toBeUndefined(); expect(result.data).toEqual({ bar: 'foo', }); // make sure no providers are instantiated again expect(spies.logger).toBeCalledTimes(1); expect(spies.data).toBeCalledTimes(1); expect(spies.appData).toBeCalledTimes(1); });
the_stack
import React from 'react' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { RequiredField } from '@island.is/judicial-system-web/src/types' import { CaseTransition, CaseGender } from '@island.is/judicial-system/types' import { getShortGender, isDirty, isNextDisabled } from './stepHelper' import { validate } from './validate' import * as formatters from './formatters' describe('Formatters utils', () => { describe('Parse array', () => { test('given a property name and an array of strings should parse correctly into JSON', () => { // Arrange const property = 'test' const array = ['lorem', 'ipsum'] // Act const parsedArray = formatters.parseArray(property, array) // Assert expect(parsedArray).not.toEqual(null) expect(parsedArray).toEqual({ test: ['lorem', 'ipsum'] }) }) }) describe('Parse string', () => { test('given a property name and a value should parse correctly into JSON', () => { // Arrange const property = 'test' const value = 'lorem' // Act const parsedString = formatters.parseString(property, value) // Assert expect(parsedString).toEqual({ test: 'lorem' }) }) test('given a value with special characters should parse correctly into JSON', () => { //Arrange const property = 'test' const value = `lorem ipsum` // Act const parsedString = formatters.parseString(property, value) // Assert expect(parsedString).toEqual({ test: 'lorem\nipsum', }) }) }) describe('Parse transition', () => { test('given a last modified timestamp and a transition should parse correnctly into JSON', () => { // Arrange const modified = 'timestamp' const transition = CaseTransition.SUBMIT // Act const parsedTransition = formatters.parseTransition(modified, transition) // Assert expect(parsedTransition).toEqual({ modified: 'timestamp', transition: CaseTransition.SUBMIT, }) }) }) describe('Parse time', () => { test('should return a valid date with time given a valid date and time', () => { // Arrange const date = '2020-10-24T12:25:00Z' const time = '13:37' // Act const d = formatters.parseTime(date, time) // Assert expect(d).toEqual('2020-10-24T13:37:00Z') }) test('should return the date given a valid date and an invalid time', () => { // Arrange const date = '2020-10-24T12:25:00Z' const time = '99:00' const time2 = '' // Act const d = formatters.parseTime(date, time) const dd = formatters.parseTime(date, time2) // Assert expect(d).toEqual('2020-10-24') expect(dd).toEqual('2020-10-24') }) }) describe('padTimeWithZero', () => { test('should pad a time with single hour value with a zero', () => { // Arrange const val = '1:15' // Act const result = formatters.padTimeWithZero(val) // Assert expect(result).toEqual('01:15') }) test('should return the input value if the value is of lenght 5', () => { // Arrange const val = '01:15' // Act const result = formatters.padTimeWithZero(val) // Assert expect(result).toEqual('01:15') }) }) describe('replaceTabsOnChange', () => { test('should not call replaceTabs if called with a string that does not have a tab character', async () => { // Arrange const spy = jest.spyOn(formatters, 'replaceTabs') render(<input onChange={(evt) => formatters.replaceTabsOnChange(evt)} />) // Act userEvent.type(await screen.findByRole('textbox'), 'Lorem ipsum') // Assert expect(spy).not.toBeCalled() }) }) }) describe('Validation', () => { describe('Validate police casenumber format', () => { test('should fail if not in correct form', () => { // Arrange const LOKE = 'INCORRECT FORMAT' // Act const r = validate(LOKE, 'police-casenumber-format') // Assert expect(r.isValid).toEqual(false) expect(r.errorMessage).toEqual('Dæmi: 012-3456-7890') }) }) describe('Validate time format', () => { test('should fail if time is not within the 24 hour clock', () => { // Arrange const time = '99:00' // Act const r = validate(time, 'time-format') // Assert expect(r.isValid).toEqual(false) expect(r.errorMessage).toEqual('Dæmi: 12:34 eða 1:23') }) test('should be valid if with the hour part is one digit within the 24 hour clock', () => { // Arrange const time = '1:00' // Act const r = validate(time, 'time-format') // Assert expect(r.isValid).toEqual(true) }) }) describe('Validate national id format', () => { test('should be valid if all digits filled in', () => { // Arrange const nid = '999999-9999' // Act const r = validate(nid, 'national-id') // Assert expect(r.isValid).toEqual(true) }) test('should be valid given just the first six digits', () => { // Arrange const nid = '010101' // Act const r = validate(nid, 'national-id') // Assert expect(r.isValid).toEqual(true) expect(r.errorMessage).toEqual('') }) test('should not be valid given too few digits', () => { // Arrange const nid = '99120' // Act const r = validate(nid, 'national-id') // Assert expect(r.isValid).toEqual(false) expect(r.errorMessage).toEqual('Dæmi: 000000-0000') }) test('should not be valid given invalid number of digits', () => { // Arrange const nid = '991201-22' // Act const r = validate(nid, 'national-id') // Assert expect(r.isValid).toEqual(false) expect(r.errorMessage).toEqual('Dæmi: 000000-0000') }) }) describe('Validate email format', () => { test('should not be valid if @ is missing', () => { // Arrange const invalidEmail = 'testATtest.is' // Act const validation = validate(invalidEmail, 'email-format') // Assert expect(validation.isValid).toEqual(false) expect(validation.errorMessage).toEqual('Netfang ekki á réttu formi') }) test('should not be valid if the ending is less than two characters', () => { // Arrange const invalidEmail = 'testATtest.i' // Act const validation = validate(invalidEmail, 'email-format') // Assert expect(validation.isValid).toEqual(false) expect(validation.errorMessage).toEqual('Netfang ekki á réttu formi') }) test('should be valid if email is empty', () => { // Arrange // Act const validation = validate('', 'email-format') // Assert expect(validation.isValid).toEqual(true) }) test('should be valid if email contains - and . characters', () => { // Arrange const validEmail = 'garfield.lasagne-lover@garfield.io' // Act const validation = validate(validEmail, 'email-format') // Assert expect(validation.isValid).toEqual(true) }) test('should be valid if email is valid', () => { // Arrange const validEmail = 'garfield@garfield.io' // Act const validation = validate(validEmail, 'email-format') // Assert expect(validation.isValid).toEqual(true) }) }) describe('Validate phonenumber format', () => { test('should fail if not in correct form', () => { // Arrange const phonenumber = '00292' // Act const r = validate(phonenumber, 'phonenumber') // Assert expect(r.isValid).toEqual(false) expect(r.errorMessage).toEqual('Dæmi: 555-5555') }) test('should pass if in correct form', () => { // Arrange const phonenumber = '555-5555' // Act const r = validate(phonenumber, 'phonenumber') // Assert expect(r.isValid).toEqual(true) }) }) }) describe('Step helper', () => { describe('insertAt', () => { test('should insert a string at a certain position into another string', () => { // Arrange const str = 'Lorem ipsum dolum kara' const insertion = ' lara' // Act const result = formatters.insertAt(str, insertion, 5) // Assert expect(result).toEqual('Lorem lara ipsum dolum kara') }) }) describe('isNextDisabled', () => { test('should return true if the only validation does not pass', () => { // Arrange const rf: RequiredField[] = [{ value: '', validations: ['empty'] }] // Act const ind = isNextDisabled(rf) // Assert expect(ind).toEqual(true) }) test('should return true if the one validation does not pass and another one does', () => { // Arrange const rf: RequiredField[] = [ { value: '', validations: ['empty'] }, { value: '13:37', validations: ['empty', 'time-format'] }, ] // Act const ind = isNextDisabled(rf) // Assert expect(ind).toEqual(true) }) test('should return false if the all validations pass', () => { // Arrange const rf: RequiredField[] = [ { value: 'Lorem ipsum', validations: ['empty'] }, { value: '13:37', validations: ['empty', 'time-format'] }, ] // Act const ind = isNextDisabled(rf) // Assert expect(ind).toEqual(false) }) }) describe('removeTabs', () => { test('should replace a single tab with a single space', () => { // Arrange const str = '\t' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual(' ') }) test('should replace multiple consecutive tabs with a single space', () => { // Arrange const str = '\t\t\t' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual(' ') }) test('should remove multiple consecutive tabs with a leading space', () => { // Arrange const str = ' \t\t\t' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual(' ') }) test('should remove multiple consecutive tabs with a trailing space', () => { // Arrange const str = '\t\t\t ' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual(' ') }) test('should process a complicated string with tabs', () => { // Arrange const str = 'Lorem\t ipsum dolor \t\tsit amet,\t\t\t\tconsectetur \t\t\t adipiscing elit.' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', ) }) test('should handle undefined', () => { // Arrange // Act const res = formatters.replaceTabs((undefined as unknown) as string) // Assert expect(res).toBeUndefined() }) test('should handle string with no tabs', () => { // Arrange const str = '020-0202-2929' // Act const res = formatters.replaceTabs(str) // Assert expect(res).toEqual('020-0202-2929') }) }) describe('isDirty', () => { test('should return true if value is an empty string', () => { // Arrange const emptyString = '' // Act const result = isDirty(emptyString) // Assert expect(result).toEqual(true) }) test('should return true if value is a non empty string', () => { // Arrange const str = 'test' // Act const result = isDirty(str) // Assert expect(result).toEqual(true) }) test('should return false if value is undefined or null', () => { // Arrange const und = undefined const n = null // Act const resultUnd = isDirty(und) const resultN = isDirty(n) // Assert expect(resultUnd).toEqual(false) expect(resultN).toEqual(false) }) }) describe('getShortGender', () => { test('should return short genders given a valid gender', () => { // Arrange const male = CaseGender.MALE const female = CaseGender.FEMALE const other = CaseGender.OTHER // Act const resultM = getShortGender(male) const resultF = getShortGender(female) const resultO = getShortGender(other) // Assert expect(resultM).toEqual('kk') expect(resultF).toEqual('kvk') expect(resultO).toEqual('annað') }) test('should return an empty string when not given a gender', () => { // Arrange const str = undefined // Act const res = getShortGender(str) // Assert expect(res).toEqual('') }) }) })
the_stack
import { intersection } from '../../util/Utils'; import Point from '../geometry/Point'; import { DIRECTION_EAST, DIRECTION_NORTH, DIRECTION_SOUTH, DIRECTION_WEST, } from '../../util/Constants'; import Rectangle from '../geometry/Rectangle'; import CellState from '../cell/datatypes/CellState'; import { CellStateStyles } from '../../types'; /** * @class Perimeter * * Provides various perimeter functions to be used in a style * as the value of {@link mxConstants.STYLE_PERIMETER}. Perimeters for * rectangle, circle, rhombus and triangle are available. * * ### Example * * @example * ```javascript * <add as="perimeter">mxPerimeter.RectanglePerimeter</add> * ``` * * ### Or programmatically * * @example * ```javascript * style.perimiter = mxPerimeter.RectanglePerimeter; * ``` * * When adding new perimeter functions, it is recommended to use the * mxPerimeter-namespace as follows: * * @example * ```javascript * mxPerimeter.CustomPerimeter = function (bounds, vertex, next, orthogonal) * { * var x = 0; // Calculate x-coordinate * var y = 0; // Calculate y-coordainte * * return new mxPoint(x, y); * } * ``` * * #### The new perimeter should then be registered in the {@link mxStyleRegistry} as follows * @example * ```javascript * mxStyleRegistry.putValue('customPerimeter', mxPerimeter.CustomPerimeter); * ``` * * #### The custom perimeter above can now be used in a specific vertex as follows: * * @example * ```javascript * model.setStyle(vertex, 'perimeter=customPerimeter'); * ``` * * Note that the key of the {@link mxStyleRegistry} entry for the function should * be used in string values, unless {@link view.allowEval} is true, in * which case you can also use mxPerimeter.CustomPerimeter for the value in * the cell style above. * * #### Or it can be used for all vertices in the graph as follows: * * @example * ```javascript * var style = graph.getStylesheet().getDefaultVertexStyle(); * style.perimiter = mxPerimeter.CustomPerimeter; * ``` * * Note that the object can be used directly when programmatically setting * the value, but the key in the {@link mxStyleRegistry} should be used when * setting the value via a key, value pair in a cell style. * * The parameters are explained in {@link RectanglePerimeter}. */ class Perimeter { /** * Describes a rectangular perimeter for the given bounds. * * @param bounds {@link mxRectangle} that represents the absolute bounds of the * vertex. * @param vertex {@link mxCellState} that represents the vertex. * @param next {@link mxPoint} that represents the nearest neighbour point on the * given edge. * @param orthogonal Boolean that specifies if the orthogonal projection onto * the perimeter should be returned. If this is false then the intersection * of the perimeter and the line between the next and the center point is * returned. */ static RectanglePerimeter( bounds: Rectangle, vertex: CellState, next: Point, orthogonal: boolean = false ): Point { const cx = bounds.getCenterX(); const cy = bounds.getCenterY(); const dx = next.x - cx; const dy = next.y - cy; const alpha = Math.atan2(dy, dx); const p = new Point(0, 0); const pi = Math.PI; const pi2 = Math.PI / 2; const beta = pi2 - alpha; const t = Math.atan2(bounds.height, bounds.width); if (alpha < -pi + t || alpha > pi - t) { // Left edge p.x = bounds.x; p.y = cy - (bounds.width * Math.tan(alpha)) / 2; } else if (alpha < -t) { // Top Edge p.y = bounds.y; p.x = cx - (bounds.height * Math.tan(beta)) / 2; } else if (alpha < t) { // Right Edge p.x = bounds.x + bounds.width; p.y = cy + (bounds.width * Math.tan(alpha)) / 2; } else { // Bottom Edge p.y = bounds.y + bounds.height; p.x = cx + (bounds.height * Math.tan(beta)) / 2; } if (orthogonal) { if (next.x >= bounds.x && next.x <= bounds.x + bounds.width) { p.x = next.x; } else if (next.y >= bounds.y && next.y <= bounds.y + bounds.height) { p.y = next.y; } if (next.x < bounds.x) { p.x = bounds.x; } else if (next.x > bounds.x + bounds.width) { p.x = bounds.x + bounds.width; } if (next.y < bounds.y) { p.y = bounds.y; } else if (next.y > bounds.y + bounds.height) { p.y = bounds.y + bounds.height; } } return p; } /** * Describes an elliptic perimeter. See {@link RectanglePerimeter} * for a description of the parameters. */ static EllipsePerimeter( bounds: Rectangle, vertex: CellState, next: Point, orthogonal: boolean = false ): Point { const { x } = bounds; const { y } = bounds; const a = bounds.width / 2; const b = bounds.height / 2; const cx = x + a; const cy = y + b; const px = next.x; const py = next.y; // Calculates straight line equation through // point and ellipse center y = d * x + h const dx = parseInt(String(px - cx)); const dy = parseInt(String(py - cy)); if (dx === 0 && dy !== 0) { return new Point(cx, cy + (b * dy) / Math.abs(dy)); } if (dx === 0 && dy === 0) { return new Point(px, py); } if (orthogonal) { if (py >= y && py <= y + bounds.height) { const ty = py - cy; let tx = Math.sqrt(a * a * (1 - (ty * ty) / (b * b))) || 0; if (px <= x) { tx = -tx; } return new Point(cx + tx, py); } if (px >= x && px <= x + bounds.width) { const tx = px - cx; let ty = Math.sqrt(b * b * (1 - (tx * tx) / (a * a))) || 0; if (py <= y) { ty = -ty; } return new Point(px, cy + ty); } } // Calculates intersection const d = dy / dx; const h = cy - d * cx; const e = a * a * d * d + b * b; const f = -2 * cx * e; const g = a * a * d * d * cx * cx + b * b * cx * cx - a * a * b * b; const det = Math.sqrt(f * f - 4 * e * g); // Two solutions (perimeter points) const xout1 = (-f + det) / (2 * e); const xout2 = (-f - det) / (2 * e); const yout1 = d * xout1 + h; const yout2 = d * xout2 + h; const dist1 = Math.sqrt(Math.pow(xout1 - px, 2) + Math.pow(yout1 - py, 2)); const dist2 = Math.sqrt(Math.pow(xout2 - px, 2) + Math.pow(yout2 - py, 2)); // Correct solution let xout = 0; let yout = 0; if (dist1 < dist2) { xout = xout1; yout = yout1; } else { xout = xout2; yout = yout2; } return new Point(xout, yout); } /** * Describes a rhombus (aka diamond) perimeter. See {@link RectanglePerimeter} * for a description of the parameters. */ static RhombusPerimeter( bounds: Rectangle, vertex: CellState, next: Point, orthogonal: boolean = false ): Point | null { const { x } = bounds; const { y } = bounds; const w = bounds.width; const h = bounds.height; const cx = x + w / 2; const cy = y + h / 2; const px = next.x; const py = next.y; // Special case for intersecting the diamond's corners if (cx === px) { if (cy > py) { return new Point(cx, y); // top } return new Point(cx, y + h); // bottom } if (cy === py) { if (cx > px) { return new Point(x, cy); // left } return new Point(x + w, cy); // right } let tx = cx; let ty = cy; if (orthogonal) { if (px >= x && px <= x + w) { tx = px; } else if (py >= y && py <= y + h) { ty = py; } } // In which quadrant will the intersection be? // set the slope and offset of the border line accordingly if (px < cx) { if (py < cy) { return intersection(px, py, tx, ty, cx, y, x, cy); } return intersection(px, py, tx, ty, cx, y + h, x, cy); } if (py < cy) { return intersection(px, py, tx, ty, cx, y, x + w, cy); } return intersection(px, py, tx, ty, cx, y + h, x + w, cy); } /** * Describes a triangle perimeter. See {@link RectanglePerimeter} * for a description of the parameters. */ static TrianglePerimeter( bounds: Rectangle, vertex: CellState, next: Point, orthogonal: boolean = false ): Point | null { const direction = vertex != null ? vertex.style.direction : null; const vertical = direction === DIRECTION_NORTH || direction === DIRECTION_SOUTH; const { x } = bounds; const { y } = bounds; const w = bounds.width; const h = bounds.height; let cx = x + w / 2; let cy = y + h / 2; let start = new Point(x, y); let corner = new Point(x + w, cy); let end = new Point(x, y + h); if (direction === DIRECTION_NORTH) { start = end; corner = new Point(cx, y); end = new Point(x + w, y + h); } else if (direction === DIRECTION_SOUTH) { corner = new Point(cx, y + h); end = new Point(x + w, y); } else if (direction === DIRECTION_WEST) { start = new Point(x + w, y); corner = new Point(x, cy); end = new Point(x + w, y + h); } let dx = next.x - cx; let dy = next.y - cy; const alpha = vertical ? Math.atan2(dx, dy) : Math.atan2(dy, dx); const t = vertical ? Math.atan2(w, h) : Math.atan2(h, w); let base = false; if (direction === DIRECTION_NORTH || direction === DIRECTION_WEST) { base = alpha > -t && alpha < t; } else { base = alpha < -Math.PI + t || alpha > Math.PI - t; } let result = null; if (base) { if ( orthogonal && ((vertical && next.x >= start.x && next.x <= end.x) || (!vertical && next.y >= start.y && next.y <= end.y)) ) { if (vertical) { result = new Point(next.x, start.y); } else { result = new Point(start.x, next.y); } } else if (direction === DIRECTION_NORTH) { result = new Point(x + w / 2 + (h * Math.tan(alpha)) / 2, y + h); } else if (direction === DIRECTION_SOUTH) { result = new Point(x + w / 2 - (h * Math.tan(alpha)) / 2, y); } else if (direction === DIRECTION_WEST) { result = new Point(x + w, y + h / 2 + (w * Math.tan(alpha)) / 2); } else { result = new Point(x, y + h / 2 - (w * Math.tan(alpha)) / 2); } } else { if (orthogonal) { const pt = new Point(cx, cy); if (next.y >= y && next.y <= y + h) { pt.x = vertical ? cx : direction === DIRECTION_WEST ? x + w : x; pt.y = next.y; } else if (next.x >= x && next.x <= x + w) { pt.x = next.x; pt.y = !vertical ? cy : direction === DIRECTION_NORTH ? y + h : y; } // Compute angle dx = next.x - pt.x; dy = next.y - pt.y; cx = pt.x; cy = pt.y; } if ((vertical && next.x <= x + w / 2) || (!vertical && next.y <= y + h / 2)) { result = intersection( next.x, next.y, cx, cy, start.x, start.y, corner.x, corner.y ); } else { result = intersection(next.x, next.y, cx, cy, corner.x, corner.y, end.x, end.y); } } if (result == null) { result = new Point(cx, cy); } return result; } /** * Describes a hexagon perimeter. See {@link RectanglePerimeter} * for a description of the parameters. */ static HexagonPerimeter( bounds: Rectangle, vertex: CellState, next: Point, orthogonal: boolean = false ): Point | null { const { x } = bounds; const { y } = bounds; const w = bounds.width; const h = bounds.height; const cx = bounds.getCenterX(); const cy = bounds.getCenterY(); const px = next.x; const py = next.y; const dx = px - cx; const dy = py - cy; const alpha = -Math.atan2(dy, dx); const pi = Math.PI; const pi2 = Math.PI / 2; let result: Point | null = new Point(cx, cy); const direction = vertex != null ? Perimeter.getValue(vertex.style, 'direction', DIRECTION_EAST) : DIRECTION_EAST; const vertical = direction === DIRECTION_NORTH || direction === DIRECTION_SOUTH; let a = new Point(); let b = new Point(); // Only consider corrects quadrants for the orthogonal case. if ( (px < x && py < y) || (px < x && py > y + h) || (px > x + w && py < y) || (px > x + w && py > y + h) ) { orthogonal = false; } if (orthogonal) { if (vertical) { // Special cases where intersects with hexagon corners if (px === cx) { if (py <= y) { return new Point(cx, y); } if (py >= y + h) { return new Point(cx, y + h); } } else if (px < x) { if (py === y + h / 4) { return new Point(x, y + h / 4); } if (py === y + (3 * h) / 4) { return new Point(x, y + (3 * h) / 4); } } else if (px > x + w) { if (py === y + h / 4) { return new Point(x + w, y + h / 4); } if (py === y + (3 * h) / 4) { return new Point(x + w, y + (3 * h) / 4); } } else if (px === x) { if (py < cy) { return new Point(x, y + h / 4); } if (py > cy) { return new Point(x, y + (3 * h) / 4); } } else if (px === x + w) { if (py < cy) { return new Point(x + w, y + h / 4); } if (py > cy) { return new Point(x + w, y + (3 * h) / 4); } } if (py === y) { return new Point(cx, y); } if (py === y + h) { return new Point(cx, y + h); } if (px < cx) { if (py > y + h / 4 && py < y + (3 * h) / 4) { a = new Point(x, y); b = new Point(x, y + h); } else if (py < y + h / 4) { a = new Point(x - Math.floor(0.5 * w), y + Math.floor(0.5 * h)); b = new Point(x + w, y - Math.floor(0.25 * h)); } else if (py > y + (3 * h) / 4) { a = new Point(x - Math.floor(0.5 * w), y + Math.floor(0.5 * h)); b = new Point(x + w, y + Math.floor(1.25 * h)); } } else if (px > cx) { if (py > y + h / 4 && py < y + (3 * h) / 4) { a = new Point(x + w, y); b = new Point(x + w, y + h); } else if (py < y + h / 4) { a = new Point(x, y - Math.floor(0.25 * h)); b = new Point(x + Math.floor(1.5 * w), y + Math.floor(0.5 * h)); } else if (py > y + (3 * h) / 4) { a = new Point(x + Math.floor(1.5 * w), y + Math.floor(0.5 * h)); b = new Point(x, y + Math.floor(1.25 * h)); } } } else { // Special cases where intersects with hexagon corners if (py === cy) { if (px <= x) { return new Point(x, y + h / 2); } if (px >= x + w) { return new Point(x + w, y + h / 2); } } else if (py < y) { if (px === x + w / 4) { return new Point(x + w / 4, y); } if (px === x + (3 * w) / 4) { return new Point(x + (3 * w) / 4, y); } } else if (py > y + h) { if (px === x + w / 4) { return new Point(x + w / 4, y + h); } if (px === x + (3 * w) / 4) { return new Point(x + (3 * w) / 4, y + h); } } else if (py === y) { if (px < cx) { return new Point(x + w / 4, y); } if (px > cx) { return new Point(x + (3 * w) / 4, y); } } else if (py === y + h) { if (px < cx) { return new Point(x + w / 4, y + h); } if (py > cy) { return new Point(x + (3 * w) / 4, y + h); } } if (px === x) { return new Point(x, cy); } if (px === x + w) { return new Point(x + w, cy); } if (py < cy) { if (px > x + w / 4 && px < x + (3 * w) / 4) { a = new Point(x, y); b = new Point(x + w, y); } else if (px < x + w / 4) { a = new Point(x - Math.floor(0.25 * w), y + h); b = new Point(x + Math.floor(0.5 * w), y - Math.floor(0.5 * h)); } else if (px > x + (3 * w) / 4) { a = new Point(x + Math.floor(0.5 * w), y - Math.floor(0.5 * h)); b = new Point(x + Math.floor(1.25 * w), y + h); } } else if (py > cy) { if (px > x + w / 4 && px < x + (3 * w) / 4) { a = new Point(x, y + h); b = new Point(x + w, y + h); } else if (px < x + w / 4) { a = new Point(x - Math.floor(0.25 * w), y); b = new Point(x + Math.floor(0.5 * w), y + Math.floor(1.5 * h)); } else if (px > x + (3 * w) / 4) { a = new Point(x + Math.floor(0.5 * w), y + Math.floor(1.5 * h)); b = new Point(x + Math.floor(1.25 * w), y); } } } let tx = cx; let ty = cy; if (px >= x && px <= x + w) { tx = px; if (py < cy) { ty = y + h; } else { ty = y; } } else if (py >= y && py <= y + h) { ty = py; if (px < cx) { tx = x + w; } else { tx = x; } } result = intersection(tx, ty, next.x, next.y, a.x, a.y, b.x, b.y); } else { if (vertical) { const beta = Math.atan2(h / 4, w / 2); // Special cases where intersects with hexagon corners if (alpha === beta) { return new Point(x + w, y + Math.floor(0.25 * h)); } if (alpha === pi2) { return new Point(x + Math.floor(0.5 * w), y); } if (alpha === pi - beta) { return new Point(x, y + Math.floor(0.25 * h)); } if (alpha === -beta) { return new Point(x + w, y + Math.floor(0.75 * h)); } if (alpha === -pi2) { return new Point(x + Math.floor(0.5 * w), y + h); } if (alpha === -pi + beta) { return new Point(x, y + Math.floor(0.75 * h)); } if (alpha < beta && alpha > -beta) { a = new Point(x + w, y); b = new Point(x + w, y + h); } else if (alpha > beta && alpha < pi2) { a = new Point(x, y - Math.floor(0.25 * h)); b = new Point(x + Math.floor(1.5 * w), y + Math.floor(0.5 * h)); } else if (alpha > pi2 && alpha < pi - beta) { a = new Point(x - Math.floor(0.5 * w), y + Math.floor(0.5 * h)); b = new Point(x + w, y - Math.floor(0.25 * h)); } else if ( (alpha > pi - beta && alpha <= pi) || (alpha < -pi + beta && alpha >= -pi) ) { a = new Point(x, y); b = new Point(x, y + h); } else if (alpha < -beta && alpha > -pi2) { a = new Point(x + Math.floor(1.5 * w), y + Math.floor(0.5 * h)); b = new Point(x, y + Math.floor(1.25 * h)); } else if (alpha < -pi2 && alpha > -pi + beta) { a = new Point(x - Math.floor(0.5 * w), y + Math.floor(0.5 * h)); b = new Point(x + w, y + Math.floor(1.25 * h)); } } else { const beta = Math.atan2(h / 2, w / 4); // Special cases where intersects with hexagon corners if (alpha === beta) { return new Point(x + Math.floor(0.75 * w), y); } if (alpha === pi - beta) { return new Point(x + Math.floor(0.25 * w), y); } if (alpha === pi || alpha === -pi) { return new Point(x, y + Math.floor(0.5 * h)); } if (alpha === 0) { return new Point(x + w, y + Math.floor(0.5 * h)); } if (alpha === -beta) { return new Point(x + Math.floor(0.75 * w), y + h); } if (alpha === -pi + beta) { return new Point(x + Math.floor(0.25 * w), y + h); } if (alpha > 0 && alpha < beta) { a = new Point(x + Math.floor(0.5 * w), y - Math.floor(0.5 * h)); b = new Point(x + Math.floor(1.25 * w), y + h); } else if (alpha > beta && alpha < pi - beta) { a = new Point(x, y); b = new Point(x + w, y); } else if (alpha > pi - beta && alpha < pi) { a = new Point(x - Math.floor(0.25 * w), y + h); b = new Point(x + Math.floor(0.5 * w), y - Math.floor(0.5 * h)); } else if (alpha < 0 && alpha > -beta) { a = new Point(x + Math.floor(0.5 * w), y + Math.floor(1.5 * h)); b = new Point(x + Math.floor(1.25 * w), y); } else if (alpha < -beta && alpha > -pi + beta) { a = new Point(x, y + h); b = new Point(x + w, y + h); } else if (alpha < -pi + beta && alpha > -pi) { a = new Point(x - Math.floor(0.25 * w), y); b = new Point(x + Math.floor(0.5 * w), y + Math.floor(1.5 * h)); } } result = intersection(cx, cy, next.x, next.y, a.x, a.y, b.x, b.y); } if (result == null) { return new Point(cx, cy); } return result; } private static getValue( style: CellStateStyles, direction: string, DIRECTION_EAST: string ) { return ''; } } export default Perimeter;
the_stack
// Query cache is an optional alternate cache that is used for any non-operational // purposes, namely customer-facing user interface components like the set of // orgs the user is a member of, the teams they are a member of, or the respos // they work with. // The original implementation of this open source portal worked off of an exclusive // proxy to the GitHub API, caching heavily in Redis, but after scaling past 10,000 // members and repos, it is no longer scaling appropriately, so this is an attempt // to address key issues there by leveraging the entity provider setup and other // jobs. import Debug from 'debug'; import { MassagePermissionsToGitHubRepositoryPermission } from '../transitional'; import { OrganizationMemberCacheEntity } from '../entities/organizationMemberCache/organizationMemberCache'; import { Operations } from './operations'; import { TeamMemberCacheEntity } from '../entities/teamMemberCache/teamMemberCache'; import { GitHubRepositoryPermission } from '../entities/repositoryMetadata/repositoryMetadata'; import { TeamCacheEntity } from '../entities/teamCache/teamCache'; import { RepositoryTeamCacheEntity } from '../entities/repositoryTeamCache/repositoryTeamCache'; import { RepositoryCacheEntity } from '../entities/repositoryCache/repositoryCache'; import { RepositoryCollaboratorCacheEntity } from '../entities/repositoryCollaboratorCache/repositoryCollaboratorCache'; import { Repository } from '.'; import { IProviders, IQueryCacheTeamMembership, QueryCacheOperation, GitHubTeamRole, IQueryCacheRepository, IQueryCacheTeam, IQueryCacheTeamRepositoryPermission, IQueryCacheRepositoryCollaborator, GitHubCollaboratorType, OrganizationMembershipRole, IQueryCacheOrganizationMembership } from '../interfaces'; const debug = Debug('querycache'); export default class QueryCache { private _providers: IProviders; constructor(providers: IProviders) { this._providers = providers; } get operations(): Operations { return this._providers.operations; } // -- Major removal function for when an organization is deleted or unmanaged async removeOrganizationById(organizationId: string): Promise<void> { try { if (this.supportsOrganizationMembership) { await this._providers.organizationMemberCacheProvider.deleteByOrganizationId(organizationId); } if (this.supportsRepositories) { await this._providers.repositoryCacheProvider.deleteByOrganizationId(organizationId); } if (this.supportsRepositoryCollaborators) { await this._providers.repositoryCollaboratorCacheProvider.deleteByOrganizationId(organizationId); } if (this.supportsTeamPermissions) { await this._providers.repositoryTeamCacheProvider.deleteByOrganizationId(organizationId); } if (this.supportsTeams) { await this._providers.teamCacheProvider.deleteByOrganizationId(organizationId); } } catch (groupError) { console.dir(groupError); throw groupError; } console.log('removed organization cache for ' + organizationId); } // -- Team Members get supportsTeamMembership(): boolean { const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; return !!teamMemberCacheProvider; } async userTeams(githubId: string): Promise<IQueryCacheTeamMembership[]> { if (!this.supportsTeamMembership) { this.throwMethodNotSupported('userTeams', 'teamMemberCacheProvider'); } const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; const rawEntities = await teamMemberCacheProvider.queryTeamMembersByUserId(githubId); return rawEntities.map(cacheEntity => this.hydrateTeamMember(cacheEntity)).filter(real => real); } async teamMembers(teamId: string): Promise<IQueryCacheTeamMembership[]> { if (!this.supportsTeamMembership) { this.throwMethodNotSupported('teamMembers', 'teamMemberCacheProvider'); } const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; const rawEntities = await teamMemberCacheProvider.queryTeamMembersByTeamId(teamId); return rawEntities.map(cacheEntity => this.hydrateTeamMember(cacheEntity)).filter(real => real); } private hydrateTeamMember(entity: TeamMemberCacheEntity): IQueryCacheTeamMembership { try { const organization = this.operations.getOrganizationById(Number(entity.organizationId)); const team = organization.team(Number(entity.teamId)); return { team, cacheEntity: entity, role: entity.teamRole, userId: entity.userId, login: entity.login, } } catch (noConfiguredOrganization) { console.dir(noConfiguredOrganization); return; } } async removeOrganizationTeamMembershipsForUser(organizationId: string, userId: string): Promise<QueryCacheOperation[]> { if (!this.supportsTeamMembership) { throw new Error('removeOrganizationTeamMembershipsForUser not supported'); } const operations = []; const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; const existingEntries = await teamMemberCacheProvider.queryTeamMembersByOrganizationIdAndUserId(organizationId, userId); debug(`removeOrganizationTeamMembershipsForUser: ${existingEntries.length} team memberships to remove in the organization id=${organizationId} and user id=${userId}`); for (const existing of existingEntries) { try { debug(`Removing team membership for organization id=${organizationId} user id=${userId}`); await teamMemberCacheProvider.deleteTeamMemberCache(existing); operations.push(QueryCacheOperation.Delete); } catch (ignored) {} } return operations; } async removeTeamMember(organizationId: string, teamId: string, userId: string): Promise<QueryCacheOperation> { if (!this.supportsTeamMembership) { throw new Error('removeTeamMember not supported'); } const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; let cache: TeamMemberCacheEntity = null; try { cache = await teamMemberCacheProvider.getTeamMemberCacheByUserId(organizationId, teamId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await teamMemberCacheProvider.deleteTeamMemberCache(cache); debug(`Removed team member user id=${userId} from team id=${teamId} in organization id=${organizationId}`); outcome = QueryCacheOperation.Delete; } return outcome; } async removeOrganizationTeamMembershipsForTeam(organizationId: string, teamId: string): Promise<QueryCacheOperation[]> { if (!this.supportsTeamMembership) { throw new Error('removeOrganizationTeamMembershipsForTeam not supported'); } const operations = []; const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; const existingEntries = await teamMemberCacheProvider.queryTeamMembersByTeamId(teamId); debug(`removeOrganizationTeamMembershipsForTeam: ${existingEntries.length} team memberships to remove in the organization id=${organizationId} and team id=${teamId}`); for (const existing of existingEntries) { try { debug(`Removing team membership for organization id=${organizationId} team id=${teamId} user id=${existing.userId}`); await teamMemberCacheProvider.deleteTeamMemberCache(existing); operations.push(QueryCacheOperation.Delete); } catch (ignored) {} } return operations; } async addOrUpdateTeamMember(organizationId: string, teamId: string, userId: string, role: GitHubTeamRole, login: string, avatar: string): Promise<QueryCacheOperation> { if (!this.supportsTeamMembership) { throw new Error('addOrUpdateTeamMember not supported'); } const teamMemberCacheProvider = this._providers.teamMemberCacheProvider; let outcome: QueryCacheOperation = null; let memberCache: TeamMemberCacheEntity = null; try { memberCache = await teamMemberCacheProvider.getTeamMemberCacheByUserId(organizationId, teamId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (memberCache) { const update = memberCache.teamRole !== role || memberCache.avatar !== avatar || memberCache.login !== login; if (update) { memberCache.cacheUpdated = new Date(); memberCache.teamRole = role; memberCache.login = login; memberCache.avatar = avatar; await teamMemberCacheProvider.updateTeamMemberCache(memberCache); debug(`Updated team member id=${userId} login=${login} with role=${role} for team=${teamId}`); outcome = QueryCacheOperation.Update; } } else { memberCache = new TeamMemberCacheEntity(); memberCache.uniqueId = TeamMemberCacheEntity.GenerateIdentifier(organizationId, teamId, userId); memberCache.organizationId = organizationId; memberCache.userId = userId; memberCache.teamId = teamId; memberCache.teamRole = role; memberCache.login = login; memberCache.avatar = avatar; await teamMemberCacheProvider.createTeamMemberCache(memberCache); debug(`Saved team member id=${userId} login=${login} with role=${role} for team=${teamId}`); outcome = QueryCacheOperation.New; } return outcome; } // -- Repositories get supportsRepositories(): boolean { const repositoryCacheProvider = this._providers.repositoryCacheProvider; return !!repositoryCacheProvider; } repositoryCacheOrganizationIds(): Promise<string[]> { if (!this.supportsRepositories) { this.throwMethodNotSupported('repositoryCacheOrganizationIds', 'repositoryCacheProvider'); } return this._providers.repositoryCacheProvider.queryAllOrganizationIds(); } async addOrUpdateRepository(organizationId: string, repositoryId: string, repositoryDetails: any): Promise<QueryCacheOperation> { if (!this.supportsRepositories) { throw new Error('addOrUpdateRepository not supported'); } const repositoryFieldsToCache = [ 'name', 'private', 'description', 'fork', 'created_at', 'updated_at', 'pushed_at', 'homepage', 'size', 'stargazers_count', 'watchers_count', 'language', 'forks_count', 'archived', 'disabled', 'open_issues_count', 'license', 'forks', 'watchers', 'network_count', 'subscribers_count', ]; let outcome: QueryCacheOperation = null; const repositoryCacheProvider = this._providers.repositoryCacheProvider; const clonedDetails = {}; repositoryFieldsToCache.forEach(key => clonedDetails[key] = repositoryDetails[key]); let repositoryCache: RepositoryCacheEntity = null; try { repositoryCache = await repositoryCacheProvider.getRepository(repositoryId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (repositoryCache) { const update = ( !repositoryCache.organizationId || !repositoryCache.repositoryDetails || !repositoryCache.repositoryDetails.updated_at || repositoryCache.repositoryDetails.updated_at !== repositoryDetails.updated_at); if (update) { repositoryCache.cacheUpdated = new Date(); repositoryCache.organizationId = organizationId; repositoryCache.repositoryName = repositoryDetails.name; repositoryCache.repositoryDetails = clonedDetails; await repositoryCacheProvider.updateRepositoryCache(repositoryCache); outcome = QueryCacheOperation.Update; } } else { repositoryCache = new RepositoryCacheEntity(); repositoryCache.repositoryId = repositoryId; repositoryCache.organizationId = organizationId; repositoryCache.repositoryName = repositoryDetails.name; repositoryCache.repositoryDetails = clonedDetails; await repositoryCacheProvider.createRepositoryCache(repositoryCache); outcome = QueryCacheOperation.New; } return outcome; } async organizationRepositories(organizationId: string): Promise<IQueryCacheRepository[]> { if (!this.supportsRepositories) { this.throwMethodNotSupported('organizationRepositories', 'repositoryCacheProvider'); } const repositoryCacheProvider = this._providers.repositoryCacheProvider; const entities = await repositoryCacheProvider.queryRepositoriesByOrganizationId(organizationId); return entities.map(cacheEntity => this.hydrateRepository(cacheEntity)).filter(exists => exists); } async allRepositories(): Promise<IQueryCacheRepository[]> { if (!this.supportsRepositories) { this.throwMethodNotSupported('allRepositories', 'repositoryCacheProvider'); } const repositoryCacheProvider = this._providers.repositoryCacheProvider; const entities = await repositoryCacheProvider.queryAllRepositories(); return entities.map(cacheEntity => this.hydrateRepository(cacheEntity)).filter(exists => exists); } private hydrateRepository(cacheEntity: RepositoryCacheEntity): IQueryCacheRepository { try { const operations = this.operations; const repository = cacheEntity.hydrateToInstance(operations); return { repository, cacheEntity, }; } catch (noConfiguredOrganization) { console.dir(noConfiguredOrganization); return; } } async removeRepository(organizationId: string, repositoryId: string): Promise<QueryCacheOperation> { if (!this.supportsRepositories) { throw new Error('removeRepository not supported'); } const repositoryCacheProvider = this._providers.repositoryCacheProvider; let cache: RepositoryCacheEntity = null; try { cache = await repositoryCacheProvider.getRepository(repositoryId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await repositoryCacheProvider.deleteRepositoryCache(cache); debug(`Removed organization id=${organizationId} repository id=${repositoryId}`); outcome = QueryCacheOperation.Delete; } // Remove all team memberships for this repository ID as well if (this.supportsTeamPermissions) { await this.removeAllTeamPermissionsForRepository(organizationId, repositoryId); } // Remove all collaborators from this repository ID if (this.supportsRepositoryCollaborators) { await this.removeAllCollaboratorsForRepository(repositoryId); } return outcome; } // -- Teams get supportsTeams(): boolean { const teamCacheProvider = this._providers.teamCacheProvider; return !!teamCacheProvider; } async organizationTeams(organizationId: string): Promise<IQueryCacheTeam[]> { if (!this.supportsTeams) { this.throwMethodNotSupported('organizationTeams', 'teamCacheProvider'); } const teamCacheProvider = this._providers.teamCacheProvider; const entities = await teamCacheProvider.queryTeamsByOrganizationId(organizationId); return entities.map(cacheEntity => this.hydrateTeam(cacheEntity)).filter(exists => exists); } private hydrateTeam(entity: TeamCacheEntity): IQueryCacheTeam { try { const organization = this.operations.getOrganizationById(Number(entity.organizationId)); const entityBasics = {...entity.teamDetails}; entityBasics.id = Number(entity.teamId); entityBasics.slug = entity.teamSlug; entityBasics.name = entity.teamName; entityBasics.description = entity.teamDescription; const team = organization.team(Number(entity.teamId), entityBasics); return { team, cacheEntity: entity, }; } catch (noConfiguredOrganization) { console.dir(noConfiguredOrganization); return; } } async addOrUpdateTeam(organizationId: string, teamId: string, teamDetails: any): Promise<QueryCacheOperation> { if (!this.supportsTeams) { throw new Error('addTeam not supported'); } let outcome: QueryCacheOperation = null; const teamCacheProvider = this._providers.teamCacheProvider; const clonedDetails = { privacy: teamDetails.privacy, created_at: teamDetails.created_at, updated_at: teamDetails.updated_at, repos_count: teamDetails.repos_count, members_count: teamDetails.members_count, }; let teamCache: TeamCacheEntity = null; try { teamCache = await teamCacheProvider.getTeam(teamId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (teamCache) { const update = ( teamCache.teamName !== teamDetails.name || teamCache.teamSlug !== teamDetails.slug || teamCache.teamDescription !== teamDetails.description || teamCache.teamDetails.updated_at !== teamDetails.updated_at || teamCache.teamDetails.privacy !== teamDetails.privacy || teamCache.teamDetails.created_at !== teamDetails.created_at || teamCache.teamDetails.repos_count !== teamDetails.repos_count || teamCache.teamDetails.members_count !== teamDetails.members_count ); if (update) { teamCache.cacheUpdated = new Date(); teamCache.teamName = teamDetails.name; teamCache.teamSlug = teamDetails.slug; teamCache.teamDescription = teamDetails.description; teamCache.teamDetails = clonedDetails; await teamCacheProvider.updateTeamCache(teamCache); debug(`team: updated cache for ${teamCache.teamSlug}`); outcome = QueryCacheOperation.Update; } } else { teamCache = new TeamCacheEntity(); teamCache.teamId = teamId; teamCache.organizationId = organizationId; teamCache.teamDescription = teamDetails.description; teamCache.teamName = teamDetails.name; teamCache.teamSlug = teamDetails.slug; teamCache.teamDetails = clonedDetails; await teamCacheProvider.createTeamCache(teamCache); debug(`team: new cache for ${teamCache.teamSlug}`); outcome = QueryCacheOperation.New; } return outcome; } async removeOrganizationTeam(organizationId: string, teamId: string): Promise<QueryCacheOperation> { if (!this.supportsTeams) { throw new Error('removeOrganizationTeam not supported'); } const teamCacheProvider = this._providers.teamCacheProvider; let cache: TeamCacheEntity = null; try { cache = await teamCacheProvider.getTeam(teamId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await teamCacheProvider.deleteTeamCache(cache); debug(`Removed organization id=${organizationId} team id=${teamId}`); outcome = QueryCacheOperation.Delete; } // Remove all team memberships for this team as well if (this.supportsTeamMembership) { await this.removeOrganizationTeamMembershipsForTeam(organizationId, teamId); } if (this.supportsTeamPermissions) { await this.removeAllRepositoryPermissionsForTeam(organizationId, teamId); } return outcome; } // -- Team permissions get supportsTeamPermissions(): boolean { const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; return !!repositoryTeamCacheProvider; } teamOrganizationIds(): Promise<string[]> { if (!this.supportsTeams) { this.throwMethodNotSupported('teamOrganizationIds', 'teamCacheProvider'); } return this._providers.teamCacheProvider.queryAllOrganizationIds(); } async addOrUpdateTeamsPermission(organizationId: string, repositoryId: string, repositoryPrivate: boolean, repositoryName: string, teamId: string, permission: GitHubRepositoryPermission): Promise<QueryCacheOperation> { if (!this.supportsTeamPermissions) { throw new Error('addOrUpdateTeamsPermission not supported'); } let outcome: QueryCacheOperation = null; const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; let cache: RepositoryTeamCacheEntity = null; try { cache = await repositoryTeamCacheProvider.getRepositoryTeamCacheByTeamId(organizationId, repositoryId, teamId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (cache) { const update = cache.permission !== permission || cache.repositoryName !== repositoryName || cache.repositoryPrivate !== repositoryPrivate; if (update) { cache.cacheUpdated = new Date(); cache.repositoryName = repositoryName; cache.permission = permission; cache.repositoryPrivate = repositoryPrivate ? true : false; await repositoryTeamCacheProvider.updateRepositoryTeamCache(cache); console.log(`Updated repo ${repositoryName} to permission=${permission} team=${teamId}`); outcome = QueryCacheOperation.Update; } } else { cache = new RepositoryTeamCacheEntity(); cache.uniqueId = RepositoryTeamCacheEntity.GenerateIdentifier(organizationId, repositoryId, teamId); cache.organizationId = organizationId; cache.repositoryId = repositoryId; cache.repositoryName = repositoryName; cache.teamId = teamId; cache.permission = permission; cache.repositoryPrivate = repositoryPrivate ? true : false; await repositoryTeamCacheProvider.createRepositoryTeamCache(cache); console.log(`Saved repo ${repositoryName} permission ${permission} to team ${teamId}`); outcome = QueryCacheOperation.New; } return outcome; } async teamsPermissions(teamIds: string[]): Promise<IQueryCacheTeamRepositoryPermission[]> { if (!this.supportsTeamPermissions) { this.throwMethodNotSupported('teamsPermissions', 'repositoryTeamCacheProvider'); } if (teamIds.length === 0) { return []; } const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; const rawEntities = await repositoryTeamCacheProvider.queryByTeamIds(teamIds); return rawEntities.map(cacheEntity => this.hydrateTeamPermission(cacheEntity)).filter(exists => exists); } async removeRepositoryTeam(organizationId: string, repositoryId: string, teamId: string): Promise<QueryCacheOperation> { if (!this.supportsTeamPermissions) { throw new Error('removeRepositoryTeam not supported'); } const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; let cache: RepositoryTeamCacheEntity = null; try { cache = await repositoryTeamCacheProvider.getRepositoryTeamCacheByTeamId(organizationId, repositoryId, teamId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await repositoryTeamCacheProvider.deleteRepositoryTeamCache(cache); debug(`Removed permission for repo id=${repositoryId} from team id=${teamId}`); outcome = QueryCacheOperation.Delete; } return outcome; } repositoryTeamOrganizationIds(): Promise<string[]> { if (!this.supportsTeamPermissions) { this.throwMethodNotSupported('repositoryTeamOrganizationIds', 'repositoryTeamCacheProvider'); } return this._providers.repositoryTeamCacheProvider.queryAllOrganizationIds(); } async repositoryTeamPermissions(repositoryId: string): Promise<IQueryCacheTeamRepositoryPermission[]> { if (!this.supportsTeamPermissions) { this.throwMethodNotSupported('repositoryTeamPermissions', 'repositoryTeamCacheProvider'); } const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; const rawEntities = await repositoryTeamCacheProvider.queryByRepositoryId(repositoryId); return rawEntities.map(cacheEntity => this.hydrateTeamPermission(cacheEntity)).filter(exists => exists); } async allRepositoryTeamPermissions(): Promise<IQueryCacheTeamRepositoryPermission[]> { if (!this.supportsTeamPermissions) { this.throwMethodNotSupported('allRepositoryTeamPermissions', 'repositoryTeamCacheProvider'); } const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; const entities = await repositoryTeamCacheProvider.queryAllTeams(); return entities.map(cacheEntity => this.hydrateTeamPermission(cacheEntity)).filter(exists => exists); } private hydrateTeamPermission(cacheEntity: RepositoryTeamCacheEntity): IQueryCacheTeamRepositoryPermission { try { const organization = this.operations.getOrganizationById(Number(cacheEntity.organizationId)); const team = organization.team(Number(cacheEntity.teamId)); const iid = cacheEntity.repositoryId; const repository = organization.repository(cacheEntity.repositoryName, { id: cacheEntity.repositoryId, // a string version of repositoryId FYI private: cacheEntity.repositoryPrivate, }); return { repository, team, permission: cacheEntity.permission, cacheEntity, }; } catch (noConfiguredOrganization) { console.dir(noConfiguredOrganization); return; } } async removeAllRepositoryPermissionsForTeam(organizationId: string, teamId: string): Promise<QueryCacheOperation[]> { if (!this.supportsTeamPermissions) { throw new Error('removeRepositoryPermissionsForTeam not supported'); } const operations = []; const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; const existingEntries = await repositoryTeamCacheProvider.queryByTeamId(teamId); debug(`removeRepositoryPermissionsForTeam: ${existingEntries.length} repository permissions to remove in the organization id=${organizationId} for team id=${teamId}`); for (const existing of existingEntries) { try { debug(`Removing repository=${existing.repositoryName} permissions for organization id=${organizationId} team id=${teamId}`); await repositoryTeamCacheProvider.deleteRepositoryTeamCache(existing); operations.push(QueryCacheOperation.Delete); } catch (ignored) {} } return operations; } async removeAllTeamPermissionsForRepository(organizationId: string, repositoryId: string): Promise<QueryCacheOperation[]> { if (!this.supportsTeamPermissions) { throw new Error('removeRepositoryPermissionsForRepository not supported'); } const operations = []; const repositoryTeamCacheProvider = this._providers.repositoryTeamCacheProvider; const existingEntries = await repositoryTeamCacheProvider.queryByRepositoryId(repositoryId); debug(`removeRepositoryPermissionsForRepository: ${existingEntries.length} repository permissions to remove in the organization id=${organizationId} for repository id=${repositoryId}`); for (const existing of existingEntries) { try { debug(`Removing team permissions for organization id=${organizationId} repository id=${repositoryId}`); await repositoryTeamCacheProvider.deleteRepositoryTeamCache(existing); operations.push(QueryCacheOperation.Delete); } catch (ignored) {} } return operations; } // -- Repo collaboration get supportsRepositoryCollaborators(): boolean { const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; return !!repositoryCollaboratorCacheProvider; } async allRepositoryCollaborators(): Promise<IQueryCacheRepositoryCollaborator[]> { if (!this.supportsRepositoryCollaborators) { throw new Error('allRepositoryCollaborators not supported'); } const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; const entities = await repositoryCollaboratorCacheProvider.queryAllCollaborators(); return entities.map(cacheEntity => this.hydrateRepositoryCollaborator(cacheEntity)).filter(real => real); } async addOrUpdateCollaborator(organizationId: string, repositoryId: string, repository: Repository, repositoryName: string, userId: string, userLogin: string, userAvatar: string, permission: GitHubRepositoryPermission, collaboratorType: GitHubCollaboratorType): Promise<QueryCacheOperation> { if (!this.supportsRepositoryCollaborators) { throw new Error('addOrUpdateCollaborator not supported'); } const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; let outcome: QueryCacheOperation = null; let collaboratorCache: RepositoryCollaboratorCacheEntity = null; try { collaboratorCache = await repositoryCollaboratorCacheProvider.getRepositoryCollaboratorCacheByUserId(organizationId, repositoryId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (collaboratorCache) { const update = collaboratorCache.avatar !== userAvatar || collaboratorCache.collaboratorType !== collaboratorType || collaboratorCache.login !== userLogin || collaboratorCache.repositoryPrivate !== repository.private || collaboratorCache.repositoryName !== repositoryName || collaboratorCache.permission !== permission; if (update) { collaboratorCache.cacheUpdated = new Date(); collaboratorCache.avatar = userAvatar; collaboratorCache.repositoryName = repositoryName; collaboratorCache.repositoryPrivate = repository.private ? true : false; collaboratorCache.collaboratorType = collaboratorType; collaboratorCache.login = userLogin; collaboratorCache.permission = permission; await repositoryCollaboratorCacheProvider.updateRepositoryCollaboratorCache(collaboratorCache); console.log(`Updated collaborator login=${userLogin} id=${userId} with type=${collaboratorType}`); } } else { collaboratorCache = new RepositoryCollaboratorCacheEntity(); collaboratorCache.repositoryId = repositoryId; collaboratorCache.organizationId = organizationId; collaboratorCache.userId = userId; collaboratorCache.uniqueId = RepositoryCollaboratorCacheEntity.GenerateIdentifier(organizationId, repositoryId, userId); collaboratorCache.repositoryName = repositoryName; collaboratorCache.repositoryPrivate = repository.private ? true : false; collaboratorCache.avatar = userAvatar; collaboratorCache.collaboratorType = collaboratorType; collaboratorCache.login = userLogin; collaboratorCache.permission = permission; await repositoryCollaboratorCacheProvider.createRepositoryCollaboratorCache(collaboratorCache); console.log(`Saved collaborator login=${userLogin} id=${userId} with type=${collaboratorType}`); } return outcome; } async userCollaboratorRepositories(githubId: string): Promise<IQueryCacheRepositoryCollaborator[]> { if (!this.supportsRepositoryCollaborators) { this.throwMethodNotSupported('userCollaboratorRepositories', 'repositoryCollaboratorCacheProvider'); } const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; const rawEntities = await repositoryCollaboratorCacheProvider.queryCollaboratorsByUserId(githubId); return rawEntities.map(cacheEntity => this.hydrateRepositoryCollaborator(cacheEntity)).filter(real => real); } async repositoryCollaborators(repositoryId: string): Promise<IQueryCacheRepositoryCollaborator[]> { if (!this.supportsRepositoryCollaborators) { this.throwMethodNotSupported('repositoryCollaborators', 'repositoryCollaboratorCacheProvider'); } const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; const rawEntities = await repositoryCollaboratorCacheProvider.queryCollaboratorsByRepositoryId(repositoryId); return rawEntities.map(cacheEntity => this.hydrateRepositoryCollaborator(cacheEntity)).filter(real => real); } repositoryCollaboratorCacheOrganizationIds(): Promise<string[]> { if (!this.supportsRepositoryCollaborators) { this.throwMethodNotSupported('supportsRepositoryCollaborators', 'repositoryCollaboratorCacheProvider'); } return this._providers.repositoryCollaboratorCacheProvider.queryAllOrganizationIds(); } async removeAllCollaboratorsForRepository(repositoryId: string): Promise<QueryCacheOperation[]> { if (!this.supportsRepositoryCollaborators) { throw new Error('removeAllCollaboratorsForRepository not supported'); } const operations = []; const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; await repositoryCollaboratorCacheProvider.deleteByRepositoryId(repositoryId) return operations; } async removeRepositoryCollaborator(organizationId: string, repositoryId: string, userId: string): Promise<QueryCacheOperation> { if (!this.supportsRepositoryCollaborators) { throw new Error('removeRepositoryCollaborator not supported'); } const repositoryCollaboratorCacheProvider = this._providers.repositoryCollaboratorCacheProvider; let cache: RepositoryCollaboratorCacheEntity = null; try { cache = await repositoryCollaboratorCacheProvider.getRepositoryCollaboratorCacheByUserId(organizationId, repositoryId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await repositoryCollaboratorCacheProvider.deleteRepositoryCollaboratorCache(cache); debug(`Removed collaborator from repo id=${repositoryId} collaborator id=${userId}`); outcome = QueryCacheOperation.Delete; } return outcome; } private hydrateRepositoryCollaborator(cacheEntity: RepositoryCollaboratorCacheEntity): IQueryCacheRepositoryCollaborator { const organization = this.operations.getOrganizationById(Number(cacheEntity.organizationId)); const iid = cacheEntity.repositoryId; const repository = organization.repository(cacheEntity.repositoryName, { id: cacheEntity.repositoryId, private: cacheEntity.repositoryPrivate, }); // a string version of repositoryId FYI return { repository, affiliation: cacheEntity.collaboratorType, cacheEntity, userId: cacheEntity.userId, permission: MassagePermissionsToGitHubRepositoryPermission(cacheEntity.permission), }; } // -- Organization membership async addOrUpdateOrganizationMember(organizationId: string, role: OrganizationMembershipRole, userId: string): Promise<QueryCacheOperation> { if (!this.supportsOrganizationMembership) { throw new Error('addOrganizationMember not supported'); } let outcome: QueryCacheOperation = null; const organizationMemberCacheProvider = this._providers.organizationMemberCacheProvider; let cache: OrganizationMemberCacheEntity = null; try { cache = await organizationMemberCacheProvider.getOrganizationMemberCacheByUserId(organizationId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } if (cache) { const update = cache.role !== role; if (update) { cache.role = role; cache.cacheUpdated = new Date(); await organizationMemberCacheProvider.updateOrganizationMemberCache(cache); debug(`Updated organization id=${organizationId} member id=${userId} to role=${role}`); outcome = QueryCacheOperation.Update; } } else { cache = new OrganizationMemberCacheEntity(); cache.organizationId = organizationId; cache.userId = userId; cache.uniqueId = OrganizationMemberCacheEntity.GenerateIdentifier(organizationId, userId); cache.role = role; await organizationMemberCacheProvider.createOrganizationMemberCache(cache); debug(`Saved organization id=${organizationId} member id=${userId} with role=${role}`); outcome = QueryCacheOperation.New; } return outcome; } async removeOrganizationMember(organizationId: string, userId: string): Promise<QueryCacheOperation> { if (!this.supportsOrganizationMembership) { throw new Error('removeOrganizationMember not supported'); } const organizationMemberCacheProvider = this._providers.organizationMemberCacheProvider; let cache: OrganizationMemberCacheEntity = null; try { cache = await organizationMemberCacheProvider.getOrganizationMemberCacheByUserId(organizationId, userId); } catch (error) { if (!error.status || error.status !== 404) { throw error; } } let outcome: QueryCacheOperation = null; if (cache) { await organizationMemberCacheProvider.deleteOrganizationMemberCache(cache); debug(`Removed organization id=${organizationId} member id=${userId}`); outcome = QueryCacheOperation.Delete; } // Repository collaborators become outside collaborators, nothing to cleanup // Cleanup any team memberships if (this.supportsTeamMembership) { await this.removeOrganizationTeamMembershipsForUser(organizationId, userId); } return outcome; } get supportsOrganizationMembership(): boolean { const organizationMemberCacheProvider = this._providers.organizationMemberCacheProvider; return !!organizationMemberCacheProvider; } async organizationMembers(organizationId: string): Promise<IQueryCacheOrganizationMembership[]> { if (!this.supportsOrganizationMembership) { this.throwMethodNotSupported('organizationMembers', 'organizationMemberCacheProvider'); } const organizationMemberCacheProvider = this._providers.organizationMemberCacheProvider; const rawEntities = await organizationMemberCacheProvider.queryOrganizationMembersByOrganizationId(organizationId); return this.hydrateOrganizationMembers(rawEntities); } private hydrateOrganizationMembers(rawEntities: OrganizationMemberCacheEntity[]): IQueryCacheOrganizationMembership[] { return rawEntities.map(cacheEntity => { try { return { organization: this.operations.getOrganizationById(Number(cacheEntity.organizationId)), role: cacheEntity.role, cacheEntity, userId: cacheEntity.userId, } } catch (noConfiguredOrganization) { return; } }).filter(exists => exists); } organizationMemberCacheOrganizationIds(): Promise<string[]> { if (!this.supportsOrganizationMembership) { this.throwMethodNotSupported('organizationMemberCacheOrganizationIds', 'organizationMemberCacheProvider'); } return this._providers.organizationMemberCacheProvider.queryAllOrganizationIds(); } async userOrganizations(githubId: string): Promise<IQueryCacheOrganizationMembership[]> { if (!this.supportsOrganizationMembership) { this.throwMethodNotSupported('userOrganizations', 'organizationMemberCacheProvider'); } const organizationMemberCacheProvider = this._providers.organizationMemberCacheProvider; const rawEntities = await organizationMemberCacheProvider.queryOrganizationMembersByUserId(githubId); return this.hydrateOrganizationMembers(rawEntities); } private throwMethodNotSupported(name: string, providerName: string) { throw new Error(`${name} is not supported by QueryCache, the ${providerName} is not configured`); } }
the_stack
import { AddressSpace, AttributeIds, ClientSession, ClientSidePublishEngine, ClientSubscription, DataChangeNotification, DataType, DataValue, ExtensionObject, MonitoredItemNotification, MonitoringMode, MonitoringParametersOptions, Namespace, NodeId, NodeIdLike, NotificationData, NotificationMessage, NumericRange, OPCUAClient, OPCUAClientOptions, ReadValueIdOptions, SetMonitoringModeRequest, SetMonitoringModeRequestOptions, SetMonitoringModeResponse, StatusCode, TimestampsToReturn, UInt32, VariantArrayType } from "node-opcua"; import sinon = require("sinon"); import should = require("should"); import { make_debugLog, checkDebugFlag } from "node-opcua-debug"; import { itemsToMonitor1 } from "./_helpers_items_to_monitor"; const debugLog = make_debugLog("TEST"); const doDebug = checkDebugFlag("TEST"); interface ClientSidePublishEnginePrivate extends ClientSidePublishEngine { internalSendPublishRequest(): void; suspend(suspend: boolean): void; } function getInternalPublishEngine(session: ClientSession): ClientSidePublishEnginePrivate { const s: ClientSidePublishEnginePrivate = (session as any).getPublishEngine(); return s; } export function t(test: any) { const options: OPCUAClientOptions = { requestedSessionTimeout: 1000000 }; async function createSession() { const client = OPCUAClient.create(options); const endpointUrl = test.endpointUrl; await client.connect(endpointUrl); const session = await client.createSession(); const publishEngine = getInternalPublishEngine(session); publishEngine.timeoutHint = 1000000; // for debugging with ease ! // make sure we control how PublishRequest are send publishEngine.suspend(true); // create a subscriptions const subscription = ClientSubscription.create(session, { publishingEnabled: true, requestedLifetimeCount: 200000, requestedMaxKeepAliveCount: 4, maxNotificationsPerPublish: 2, requestedPublishingInterval: 250 }); return { client, session, subscription, publishEngine }; } interface Connection { client: OPCUAClient; session: ClientSession; subscription: ClientSubscription; publishEngine: ClientSidePublishEnginePrivate; } let s: Connection; async function waitForRawNotifications(): Promise<NotificationData[]> { const { publishEngine, subscription } = s; publishEngine.internalSendPublishRequest(); return await new Promise((resolve: (result: NotificationData[]) => void) => { // wait for fist notification subscription.once("raw_notification", (notificationMessage: any) => { // tslint:disable-next-line: no-console debugLog("got notification message ", notificationMessage.toString()); resolve(notificationMessage.notificationData); }); }); } async function waitForDataChangeNotification(): Promise<DataChangeNotification | null> { const rawNotification = await waitForRawNotifications(); if (!rawNotification || rawNotification.length === 0) { return null; } if (rawNotification[0] instanceof DataChangeNotification) { return rawNotification[0] as DataChangeNotification; } return null; } async function waitForNotificationsValues(): Promise<{ value: number; statusCode: StatusCode }[]> { while (true) { const notificationData1 = await waitForRawNotifications(); if (notificationData1.length > 0) { const dcn = notificationData1[0] as DataChangeNotification; const r = dcn.monitoredItems!.map((item: MonitoredItemNotification) => ({ statusCode: item.value.statusCode, value: item.value.value.value })); return r; } // tslint:disable-next-line: no-console debugLog(" ------- skipping empty publish response"); return []; } } const describe = require("node-opcua-leak-detector").describeWithLeakDetector; describe("Monitoring item tests", function (this: any) { this.timeout(Math.max(200000, this.timeout())); const items: NodeId[] = []; before(() => { const addressSpace = test.server.engine.addressSpace as AddressSpace; const namespace = test.server.engine.addressSpace.getOwnNamespace() as Namespace; for (let i = 0; i < 10; i++) { const v = namespace.addVariable({ browseName: `SomeVariableForTest${i}`, dataType: "UInt32" }); v.setValueFromSource({ dataType: DataType.UInt32, value: 0 }); items.push(v.nodeId); } }); beforeEach(async () => { const addressSpace = test.server.engine.addressSpace as AddressSpace; s = await createSession(); }); afterEach(async () => { await s.subscription.terminate(); await s.session.close(); await s.client.disconnect(); }); let counter = 0; async function increaseVariables(session: ClientSession) { counter += 1; await session.write( items.map((nodeId) => ({ nodeId, attributeId: AttributeIds.Value, value: new DataValue({ value: { dataType: DataType.UInt32, value: counter } }) })) ); } async function collectDataChange(memory: { [key: number]: DataValue }): Promise<number> { // wait one publishing cycle before calling publish let totalNumberOfDataChanges = 0; let dataChangeNotification = await waitForDataChangeNotification(); while (dataChangeNotification) { totalNumberOfDataChanges += dataChangeNotification.monitoredItems?.length || 0; for (const c of dataChangeNotification.monitoredItems || []) { memory[c.clientHandle] = c.value; } dataChangeNotification = await waitForDataChangeNotification(); } return totalNumberOfDataChanges; } it("deleteMonitoredItem should remove dangling notifications", async () => { // we create a starving subscription (no publish request) // ( with maxNotificationsPerPublish = 2 so that all pending notifications are not send at once ... ) // we create a monitoring item and make sure that the moninored Item change a lot // we delete the monitored item // we create the same monitored item // we send a publish request // we should verify that only one notification is recevied (for the only one valid monitored item ) const { session, subscription, publishEngine } = s; let itemToMonitorsAll: ReadValueIdOptions[] = items.map((nodeId) => ({ nodeId, attributeId: AttributeIds.Value })); const itemToMonitors1 = itemToMonitorsAll.slice(0, 5); const itemToMonitors2 = itemToMonitorsAll.slice(5); itemToMonitors1.length.should.eql(5); itemToMonitors2.length.should.eql(5); const requesterParameters: MonitoringParametersOptions = { discardOldest: true, queueSize: 100, samplingInterval: 0 }; await increaseVariables(session); const group = await subscription.monitorItems(itemToMonitors1, requesterParameters, TimestampsToReturn.Both); const change1 = await collectDataChange({}); change1.should.eql(5); await increaseVariables(session); await new Promise((resolve) => setTimeout(resolve, 20)); await increaseVariables(session); await new Promise((resolve) => setTimeout(resolve, 20)); await increaseVariables(session); await new Promise((resolve) => setTimeout(resolve, 20)); // get a partial notification , but do not go to completion let dataChangeNotification = await waitForDataChangeNotification(); dataChangeNotification?.monitoredItems!.length.should.eql(2); await group.terminate(); const group2 = await subscription.monitorItems(itemToMonitors2, requesterParameters, TimestampsToReturn.Both); const change2 = await collectDataChange({}); change2.should.eql(5); }); it("setMonitoringMode593011 wrong index range", async () => { // the test modifies the monitoring mode of 10 items (initial monitoring mode: reporting) // with multiple items being set to each of the three modes (Disabled, Reporting, Sampling) // calls publish before and after changing the mode and verifies that datachange notifications // are received only for the reporting items. const { session, subscription, publishEngine } = s; const itemsValues: { [key: number]: DataValue } = {}; let counter = 0; // The 10 items used for this test. The test can use the same NodeIds, await increaseVariables(session); let itemToMonitors: ReadValueIdOptions[] = items.map((nodeId) => ({ nodeId, attributeId: AttributeIds.Value })); const requesterParameters: MonitoringParametersOptions = { discardOldest: true, queueSize: 1, samplingInterval: 1 }; const group = await subscription.monitorItems(itemToMonitors, requesterParameters, TimestampsToReturn.Both); const totalNumberOfDataChanges = await collectDataChange(itemsValues); // Make sure we received datachange notification - should contain INITIAL values totalNumberOfDataChanges.should.eql(10); // Now change the monitoring mode as below: // Disabled: 3 (indices 0,4,6 in createMonitoredItemsResponse) // Sampling: 3 (indices 2,8,9 in createMonitoredItemsResponse) // Reporting: 4 (indices 1,3,5,7 in createMonitoredItemsResponse) console.log("Changing monitoring mode for the items."); const monitoredItems = await subscription.getMonitoredItems(); // i=0: DISABLED; i=1: SAMPLING; i=2: REPORTING for (let i = 0; i < 3; i++) { const setMonitoringModeRequest = new SetMonitoringModeRequest({ subscriptionId: subscription.subscriptionId, monitoringMode: MonitoringMode.Disabled, monitoredItemIds: [] }); if (!setMonitoringModeRequest.monitoredItemIds) { throw new Error("Internal"); } switch (i) { // DISABLED case 0: setMonitoringModeRequest.monitoringMode = MonitoringMode.Disabled; // Items setMonitoringModeRequest.monitoredItemIds[0] = monitoredItems.serverHandles[0]; setMonitoringModeRequest.monitoredItemIds[1] = monitoredItems.serverHandles[4]; setMonitoringModeRequest.monitoredItemIds[2] = monitoredItems.serverHandles[6]; break; // SAMPLING case 1: setMonitoringModeRequest.monitoringMode = MonitoringMode.Sampling; // Items setMonitoringModeRequest.monitoredItemIds[0] = monitoredItems.serverHandles[2]; setMonitoringModeRequest.monitoredItemIds[1] = monitoredItems.serverHandles[8]; setMonitoringModeRequest.monitoredItemIds[2] = monitoredItems.serverHandles[9]; break; // REPORTING case 2: setMonitoringModeRequest.monitoringMode = MonitoringMode.Reporting; // Items setMonitoringModeRequest.monitoredItemIds[0] = monitoredItems.serverHandles[1]; setMonitoringModeRequest.monitoredItemIds[1] = monitoredItems.serverHandles[3]; setMonitoringModeRequest.monitoredItemIds[2] = monitoredItems.serverHandles[5]; setMonitoringModeRequest.monitoredItemIds[3] = monitoredItems.serverHandles[7]; break; default: throw new Error( "Unexpected error. Unable to specify the monitoringMode request. Test script implementation problem!" ); } const setMonitoringModeResponse = (await (session as any).setMonitoringMode( setMonitoringModeRequest )) as SetMonitoringModeResponse; //xx checkSetMonitoringModeValidParameter( setMonitoringModeRequest, setMonitoringModeResponse ); switch (i) { // DISABLED case 0: console.log("Monitoring mode set to 'Disabled' successfully for 3 items."); break; // SAMPLING case 1: console.log("Monitoring mode set to 'Sampling' successfully for 3 items."); break; // REPORTING case 2: console.log("Monitoring mode set to 'Reporting' successfully for 4 items."); break; default: throw new Error("Unexpected error. Verification implementation problem in test-script."); } // Write to ALL items, incl. those that are disabled etc. for (let x = 0; x < items.length; x++) { // if( Assert.True( WriteHelper.Execute( { NodesToWrite: items } ), "This test requires the ability to Write to the Nodes in order to achieve a value change in the item so that the Publish call can receive a dataChange notification." ) ) { // // call Publish() again to verify that we receive datachange notification only for 4 items // // wait one publishing cycle before calling publish // PublishHelper.WaitInterval( { Items: items, Subscription: MonitorBasicSubscription } ); // addLog ( "Calling publish again. We should receivse NotificationData this time only for 4 items." ); // PublishHelper.Execute(); // // Make sure we received datachange notification // if( Assert.Equal( true, PublishHelper.CurrentlyContainsData(), "NotificationData not received (second publish call) when expected for the 4 'Reporting' monitored items", "Publish() #2 correctly received the dataChange notifications as expected." ) ) { // TotalNumberOfDataChanges = PublishHelper.CurrentDataChanges[0].MonitoredItems.length; // while (PublishHelper.Response.MoreNotifications == true) { // PublishHelper.Execute(); // TotalNumberOfDataChanges += PublishHelper.CurrentDataChanges[0].MonitoredItems.length; // } // // Check that notification was received only for 4 items // if( Assert.Equal( 4, TotalNumberOfDataChanges, ( "Datachange notification received for " + PublishHelper.CurrentDataChanges[0].MonitoredItems.length + " items when expected for 4 items" ), "Publish() #2 received the 4 dataChange notifications as expected, since the other 6 monitoredItems are set to Disabled/Sampling." ) ) // { // var expectedItems = [1, 3, 5, 7 ]; // for( x=0; x<expectedItems.length; x++ ) Assert.True( PublishHelper.HandleIsInCurrentDataChanges( items[expectedItems[x]].ClientHandle ), ( "Expected item[" + expectedItems[x] + "] (Node: " + items[expectedItems[x]].NodeSetting + ") to send an update." ), "Item[" + expectedItems[x] + "] successfully received a dataChange notification. Mode=" + MonitoringMode.toString( items[x].MonitoringMode ) ); // } // } // } } } }); it("createMonitoredItems591025 ", async () => { /* Specify an item of type array. Do this for all configured supported data types. Specify an IndexRange that equates to the last 3 elements of the array. Write values to each data-type within the index range specified and then call Publish(). We expect to receive data in the Publish response. Write to each data-type outside of the index range (e.g. elements 0 and 1) and then call Publish(). We do not expect to receive data in the Publish response. */ const { session, subscription, publishEngine } = s; const namespaceSimulationIndex = 2; const nodeId = `ns=${namespaceSimulationIndex};s=Static_Array_UInt32`; let valueRankDataValue = await session.read({ nodeId, attributeId: AttributeIds.ValueRank }); const valueRank = valueRankDataValue.value.value as number; valueRank.should.eql(1); let dataValue = await session.read({ nodeId, attributeId: AttributeIds.Value }); const nbElements = (dataValue.value.value as UInt32[]).length; const newValue = []; for (let i = 0; i < nbElements; i++) { newValue[i] = i; } dataValue.value.value = newValue; await session.write({ nodeId, attributeId: AttributeIds.Value, value: dataValue }); let itemsToMonitor: ReadValueIdOptions[] = [ { nodeId, attributeId: AttributeIds.Value, indexRange: new NumericRange(nbElements - 3, nbElements - 1) } ]; const requesterParameters: MonitoringParametersOptions = { discardOldest: true, queueSize: 100, samplingInterval: 0 }; const group = await subscription.monitorItems(itemsToMonitor, requesterParameters, TimestampsToReturn.Both); const d: any = {}; const change1 = await collectDataChange(d); change1.should.eql(1); console.log(d["1"].toString()); await session.write({ nodeId, attributeId: AttributeIds.Value, indexRange: new NumericRange(nbElements - 3, nbElements - 1), value: { value: { dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: [70,80,90] } } }); const change2 = await collectDataChange(d); change2.should.eql(1); await session.write({ nodeId, attributeId: AttributeIds.Value, indexRange: new NumericRange(0, 2), value: { value: { dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: [1000,10001, 10002] } } }); const change3 = await collectDataChange(d); change3.should.eql(0); dataValue = await session.read({ nodeId, attributeId: AttributeIds.Value }); console.log(dataValue.toString()); }); }); }
the_stack
import { guid } from "@atomist/automation-client/lib/internal/util/string"; import { NodeFsLocalProject } from "@atomist/automation-client/lib/project/local/NodeFsLocalProject"; import * as fs from "fs-extra"; import * as os from "os"; import * as path from "path"; import * as assert from "power-assert"; import { execPromise } from "../../../../lib/api-helper/misc/child_process"; import { fakePush } from "../../../../lib/api-helper/testsupport/fakePush"; import { ExecuteGoalResult } from "../../../../lib/api/goal/ExecuteGoalResult"; import { GoalInvocation } from "../../../../lib/api/goal/GoalInvocation"; import { Container, GoalContainer, } from "../../../../lib/core/goal/container/container"; import { containerDockerOptions, dockerTmpDir, executeDockerJob, } from "../../../../lib/core/goal/container/docker"; import { runningInK8s } from "../../../../lib/core/goal/container/util"; import { containerTestImage } from "./util"; /* tslint:disable:max-file-line-count */ describe("goal/container/docker", () => { describe("containerDockerOptions", () => { it("should return an empty array", () => { const c = { image: "townes/tecumseh-valley:4.55", name: "townes", }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = []; assert.deepStrictEqual(o, e); }); it("should handle command as entrypoint", () => { const c = { image: "townes/tecumseh-valley:4.55", name: "townes", command: ["daughter"], }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = ["--entrypoint=daughter"]; assert.deepStrictEqual(o, e); }); it("should move extra command elements to args", () => { const c: GoalContainer = { image: "townes/tecumseh-valley:4.55", name: "townes", command: ["daughter", "of", "a", "miner"], }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = ["--entrypoint=daughter"]; assert.deepStrictEqual(o, e); assert.deepStrictEqual(c.args, ["of", "a", "miner"]); }); it("should prepend extra command elements to args", () => { const c = { args: ["her", "ways", "were", "free"], image: "townes/tecumseh-valley:4.55", name: "townes", command: ["daughter", "of", "a", "miner"], }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = ["--entrypoint=daughter"]; assert.deepStrictEqual(o, e); assert.deepStrictEqual(c.args, ["of", "a", "miner", "her", "ways", "were", "free"]); }); it("should handle env", () => { const c = { image: "townes/tecumseh-valley:4.55", name: "townes", env: [ { name: "DAUGHTER", value: "miner", }, { name: "DAYS", value: "free", }, { name: "SUNSHINE", value: "walked beside her", }, ], }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = ["--env=DAUGHTER=miner", "--env=DAYS=free", "--env=SUNSHINE=walked beside her"]; assert.deepStrictEqual(o, e); }); it("should handle ports", () => { const c = { image: "townes/tecumseh-valley:4.55", name: "townes", ports: [ { containerPort: 1238, }, { containerPort: 2247, }, { containerPort: 4304, }, ], }; const r = { containers: [c], }; const o = containerDockerOptions(c, r); const e = ["-p=1238", "-p=2247", "-p=4304"]; assert.deepStrictEqual(o, e); }); it("should handle volumes", () => { const c = { image: "townes/tecumseh-valley:4.55", name: "townes", volumeMounts: [ { mountPath: "/like/a/summer/thursday", name: "Thursday", }, { mountPath: "/our/mother/the/mountain", name: "mountain", }, ], }; const r = { containers: [c], volumes: [ { hostPath: { path: "/home/mountain", }, name: "mountain", }, { hostPath: { path: "/mnt/thursday", }, name: "Thursday", }, ], }; const o = containerDockerOptions(c, r); const e = ["--volume=/mnt/thursday:/like/a/summer/thursday", "--volume=/home/mountain:/our/mother/the/mountain"]; assert.deepStrictEqual(o, e); }); }); describe("executeDockerJob", () => { const fakeId = fakePush().id; const goal = new Container(); const projectDir = path.join(dockerTmpDir(), "atomist-sdm-docker-test-" + guid()); let project: NodeFsLocalProject; const tmpDirs: string[] = []; let logData = ""; const logWrite = (d: string): void => { logData += d; }; const goalInvocation: GoalInvocation = { context: { graphClient: { query: () => ({ SdmVersion: [{ version: "3.1.3-20200220200220" }] }), }, }, configuration: { sdm: { projectLoader: { doWithProject: async (o, a) => { let p: NodeFsLocalProject; if (o && o.cloneDir) { await fs.ensureDir(o.cloneDir); tmpDirs.push(o.cloneDir); p = await NodeFsLocalProject.copy(project, o.cloneDir) as NodeFsLocalProject; } else { p = project; } return a(p); }, }, }, }, credentials: {}, goalEvent: { branch: fakeId.branch, goalSetId: "27c20de4-2c88-480a-b4e7-f6c6d5a1d623", push: { commits: [], }, repo: { name: fakeId.repo, owner: fakeId.owner, providerId: "album", }, sha: fakeId.sha, uniqueName: goal.definition.uniqueName, }, id: fakeId, progressLog: { write: logWrite, }, } as any; before(async function dockerCheckProjectSetup(this: Mocha.Context): Promise<void> { this.timeout(20000); if (runningInK8s() || (!process.env.DOCKER_HOST && !fs.existsSync("/var/run/docker.sock"))) { this.skip(); } try { await execPromise("docker", ["pull", containerTestImage], { timeout: 18000 }); } catch (e) { this.skip(); } await fs.ensureDir(projectDir); tmpDirs.push(projectDir); project = await NodeFsLocalProject.fromExistingDirectory(fakeId, projectDir) as any; }); beforeEach(() => { logData = ""; }); after(async function directoryCleanup(): Promise<void> { await Promise.all(tmpDirs.map(d => fs.remove(d))); }); it("should run a docker container", async () => { const r = { containers: [ { args: ["true"], image: containerTestImage, name: "alpine", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(10000); it("should throw an error if there are no containers", async () => { const r = { containers: [], }; const e = executeDockerJob(goal, r); try { await e(goalInvocation); assert.fail("execution of goal without containers should have thrown an error"); } catch (e) { assert(/No containers defined in GoalContainerSpec/.test(e.message)); } }); it("should report when the container fails", async () => { const r = { containers: [ { args: ["false"], image: containerTestImage, name: "alpine", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 1); assert(x.message.startsWith("Docker container 'sdm-alpine-27c20de-container' failed")); }).timeout(10000); it("should run multiple containers", async () => { const r = { containers: [ { args: ["true"], image: containerTestImage, name: "alpine0", }, { args: ["true"], image: containerTestImage, name: "alpine1", }, { args: ["true"], image: containerTestImage, name: "alpine2", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(15000); it("should report when main container fails", async () => { const r = { containers: [ { args: ["false"], image: containerTestImage, name: "alpine0", }, { args: ["true"], image: containerTestImage, name: "alpine1", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 1, logData); assert(x.message.startsWith("Docker container 'sdm-alpine0-27c20de-container' failed")); }).timeout(10000); it("should ignore when sidecar container fails", async () => { const r = { containers: [ { args: ["true"], image: containerTestImage, name: "alpine0", }, { args: ["false"], image: containerTestImage, name: "alpine1", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(10000); it("should only wait on main container", async () => { const r = { containers: [ { args: ["true"], image: containerTestImage, name: "alpine0", }, { args: ["sleep", "20"], image: containerTestImage, name: "alpine1", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(10000); it("should allow containers to communicate", async () => { const r = { containers: [ { args: ["sleep 1; ping -w 1 alpine1"], command: ["sh", "-c"], image: containerTestImage, name: "alpine0", }, { args: ["sleep", "20"], image: containerTestImage, name: "alpine1", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(15000); it("should use the registration callback", async () => { const r = { callback: async () => { return { containers: [ { args: ["true"], image: containerTestImage, name: "alpine", }, ], }; }, containers: [ { args: ["false"], image: containerTestImage, name: "alpine", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); }).timeout(10000); it("should persist changes to project", async () => { const tmpDir = path.join(os.tmpdir(), "atomist-sdm-docker-test-" + guid()); await fs.ensureDir(tmpDir); tmpDirs.push(tmpDir); const existingFile = `README.${guid()}`; let existingFilePath = path.join(tmpDir, existingFile); await fs.writeFile(existingFilePath, "# After Hours\n"); const changeFile = `pigeonCamera.${guid()}`; let changeFilePath = path.join(tmpDir, changeFile); await fs.writeFile(changeFilePath, "Where's my pigeon camera?\n"); const deleteFile = `ifyouclosethedoor_${guid()}`; let deleteFilePath = path.join(tmpDir, deleteFile); await fs.writeFile(deleteFilePath, "you won't see me\nyou won't see me\n"); const newFile = `project-test-0-${guid()}`; let newFilePath = path.join(tmpDir, newFile); const lid = fakePush().id; let lp = await NodeFsLocalProject.fromExistingDirectory(lid, tmpDir) as NodeFsLocalProject; const lgi: GoalInvocation = { context: { graphClient: { query: () => ({ SdmVersion: [{ version: "3.1.3-20200220200220" }] }), }, }, configuration: { sdm: { projectLoader: { doWithProject: async (o, a) => { if (o && o.cloneDir) { await fs.ensureDir(o.cloneDir); tmpDirs.push(o.cloneDir); lp = await NodeFsLocalProject.copy(lp, o.cloneDir) as NodeFsLocalProject; existingFilePath = existingFilePath.replace(tmpDir, o.cloneDir); changeFilePath = changeFilePath.replace(tmpDir, o.cloneDir); deleteFilePath = deleteFilePath.replace(tmpDir, o.cloneDir); newFilePath = newFilePath.replace(tmpDir, o.cloneDir); } return a(lp); }, }, }, }, credentials: {}, goalEvent: { branch: lid.branch, goalSetId: "27c20de4-2c88-480a-b4e7-f6c6d5a1d623", push: { commits: [], }, repo: { name: lid.repo, owner: lid.owner, providerId: "album", }, sha: lid.sha, uniqueName: goal.definition.uniqueName, }, id: lid, progressLog: { write: logWrite, }, } as any; const r = { containers: [ { args: [ `echo 'This is only a local test' > ${newFile}` + `; echo 'By now it could be anywhere.' >> ${changeFile}` + `; rm ${deleteFile}`, ], command: ["sh", "-c"], image: containerTestImage, name: "alpine0", }, ], }; const edj = executeDockerJob(goal, r); const egr = await edj(lgi); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); const t = await lp.getFile(newFile); assert(t, "file created in container does not exist"); const tc = await t.getContent(); assert(tc === "This is only a local test\n"); const tcf = await fs.readFile(newFilePath, "utf8"); assert(tcf === "This is only a local test\n"); const e = await lp.getFile(existingFile); assert(e, "file existing in project disappeared"); const ec = await e.getContent(); assert(ec === "# After Hours\n"); const ecf = await fs.readFile(existingFilePath, "utf8"); assert(ecf === "# After Hours\n"); const c = await lp.getFile(changeFile); assert(c, "file changed in project disappeared"); const cc = await c.getContent(); assert(cc === "Where's my pigeon camera?\nBy now it could be anywhere.\n"); const ccf = await fs.readFile(changeFilePath, "utf8"); assert(ccf === "Where's my pigeon camera?\nBy now it could be anywhere.\n"); assert(!await lp.getFile(deleteFile), "deleted file still exists in project"); assert(!fs.existsSync(deleteFilePath), "deleted file still exists on file system"); }).timeout(10000); it("should use volumes", async () => { const tmpDir = path.join(os.homedir(), ".atomist", "tmp", guid()); await fs.ensureDir(tmpDir); tmpDirs.push(tmpDir); const tmpFile = `volume-test-0-${guid()}`; const r = { containers: [ { args: [`echo 'This is only a test' > /test/vol0/${tmpFile}`], command: ["sh", "-c"], image: containerTestImage, name: "alpine0", volumeMounts: [ { mountPath: "/test/vol0", name: "test-volume", }, ], }, ], volumes: [ { hostPath: { path: tmpDir, }, name: "test-volume", }, ], }; const e = executeDockerJob(goal, r); const egr = await e(goalInvocation); assert(egr, "ExecuteGoal did not return a value"); const x = egr as ExecuteGoalResult; assert(x.code === 0, logData); assert(x.message === "Successfully completed container job"); const tmpFilePath = path.join(tmpDir, tmpFile); const tmpContent = await fs.readFile(tmpFilePath, "utf8"); assert(tmpContent === "This is only a test\n"); }).timeout(10000); }); });
the_stack
import { ChartLocation, ControlPoints } from '../../common/utils/helper'; import { extend, isNullOrUndefined } from '@syncfusion/ej2-base'; import { Chart } from '../chart'; import { Series, Points } from './chart-series'; import { IntervalType } from '../../chart/utils/enum'; import { LineBase } from './line-base'; import { AnimationModel } from '../../common/model/base-model'; /** * render Line series */ export class SplineBase extends LineBase { private splinePoints: number[] = []; private lowSplinePoints: number[] = []; /** @private */ constructor(chartModule?: Chart) { super(chartModule); } /** * To find the control points for spline. * * @returns {void} * @private */ public findSplinePoint(series: Series): void { let value: ControlPoints; let lowPoints: ControlPoints; let realPoints: Points[] = []; const points: Points[] = []; let point: Points; let pointIndex: number = 0; realPoints = this.filterEmptyPoints(series); for (let i: number = 0; i < realPoints.length; i++) { point = realPoints[i]; if (point.x === null || point.x === '') { continue; } else { point.index = pointIndex; pointIndex++; points.push(point); } } let isLow: boolean = false; this.splinePoints = this.findSplineCoefficients(points, series, isLow); if(series.type === "SplineRangeArea"){ isLow = !isLow this.lowSplinePoints = this.findSplineCoefficients(points, series, isLow); } if (points.length > 1) { series.drawPoints = []; series.lowDrawPoints= []; for (const point of points) { if (point.index !== 0) { const previous: number = this.getPreviousIndex(points, point.index - 1, series); if(series.type === "SplineRangeArea") { points[previous].yValue = points[previous].high > points[previous].low ? (points[previous].high as number) : (points[previous].low as number); point.yValue = point.high > point.low ? (point.high as number) : (point.low as number); } value = this.getControlPoints( points[previous], point, this.splinePoints[previous], this.splinePoints[point.index], series ); series.drawPoints.push(value); if(series.type === "SplineRangeArea"){ points[previous].yValue = points[previous].low < points[previous].high ? (points[previous].low as number) : (points[previous].high as number); point.yValue = point.low < point.high ? (point.low as number) : (point.high as number); lowPoints = this.getControlPoints( points[previous], point, this.lowSplinePoints[previous], this.lowSplinePoints[point.index], series ); series.lowDrawPoints.push(lowPoints); } // fix for Y-Axis of Spline chart not adjusting scale to suit dataSource issue const delta: number = series.yMax - series.yMin; if (point.yValue && value.controlPoint1.y && value.controlPoint2.y && delta > 1) { series.yMin = Math.min(series.yMin, point.yValue, value.controlPoint1.y, value.controlPoint2.y); series.yMax = Math.ceil(Math.max(series.yMax, point.yValue, value.controlPoint1.y, value.controlPoint2.y)); series.yMin = series.yAxis.valueType !== 'Logarithmic' ? Math.floor(series.yMin) : series.yMin; } } } if (series.chart.chartAreaType === 'PolarRadar' && series.isClosed) { value = this.getControlPoints( { xValue: points[points.length - 1].xValue, yValue: points[points.length - 1].yValue } as Points, { xValue: points[points.length - 1].xValue + 1, yValue: points[0].yValue } as Points, this.splinePoints[0], this.splinePoints[points[points.length - 1].index], series); series.drawPoints.push(value); } } } protected getPreviousIndex(points: Points[], i: number, series: Series): number { if (series.emptyPointSettings.mode !== 'Drop') { return i; } while (isNullOrUndefined(points[i]) && i > -1) { i = i - 1; } return i; } public getNextIndex(points: Points[], i: number, series: Series): number { if (series.emptyPointSettings.mode !== 'Drop') { return i; } while (isNullOrUndefined(points[i]) && i < points.length) { i = i + 1; } return i; } public filterEmptyPoints(series: Series, seriesPoints?: Points[]): Points[] { if (series.emptyPointSettings.mode !== 'Drop' && this.isPointInRange(series.points)) { return seriesPoints ? seriesPoints : series.points; } const points: Points[] = seriesPoints ? seriesPoints : extend([], series.points, null, true) as Points[]; for (let i: number = 0; i < points.length; i++) { points[i].index = i; if (points[i].isEmpty) { points[i].symbolLocations = []; points[i].regions = []; points.splice(i, 1); i--; } } return points; } /** * To find points in the range * * @private */ public isPointInRange(points: Points[]): boolean { for (const point of points) { if (!point.isPointInRange) { return false; } } return true; } /** * To find the natural spline. * * @returns {void} * @private */ public findSplineCoefficients(points: Points[], series: Series, isLow?: boolean): number[] { let ySpline: number[] = []; const ySplineDuplicate: number[] = []; let cardinalSplineTension: number = series.cardinalSplineTension ? series.cardinalSplineTension : 0.5; cardinalSplineTension = cardinalSplineTension < 0 ? 0 : cardinalSplineTension > 1 ? 1 : cardinalSplineTension; switch (series.splineType) { case 'Monotonic': ySpline = this.monotonicSplineCoefficients(points, series, isLow); break; case 'Cardinal': ySpline = this.cardinalSplineCofficients(points, series, isLow); break; default: if (series.splineType === 'Clamped') { ySpline = this.clampedSplineCofficients(points, series, isLow); } else { // assigning the first and last value as zero ySpline[0] = ySplineDuplicate[0] = 0; ySpline[points.length - 1] = 0; } ySpline = this.naturalSplineCoefficients(points, series, isLow); break; } return ySpline; } /** * To find Monotonic Spline Coefficients */ private monotonicSplineCoefficients(points: Points[], series: Series, isLow: boolean): number[] { const count: number = points.length; const ySpline: number[] = []; const dx: number[] = []; const dy: number[] = []; const slope: number[] = []; let interPoint: number; let slopeLength: number; for (let i: number = 0; i < count - 1; i++) { if (series.type === "SplineRangeArea") { if (!isLow) { points[i + 1].yValue = points[i + 1].high > points[i + 1].low ? (points[i + 1].high as number) : (points[i + 1].low as number); points[i].yValue = points[i].high > points[i].low ? (points[i].high as number) : (points[i].low as number); } if (isLow) { points[i + 1].yValue = points[i + 1].low < points[i + 1].high ? (points[i + 1].low as number) : (points[i + 1].high as number); points[i].yValue = points[i].low < points[i].high ? (points[i].low as number) : (points[i].high as number); } } dx[i] = points[i + 1].xValue - points[i].xValue; dy[i] = points[i + 1].yValue - points[i].yValue; slope[i] = dy[i] / dx[i]; } //interpolant points slopeLength = slope.length; // to find the first and last co-efficient value ySpline[0] = slope[0]; ySpline[count - 1] = slope[slopeLength - 1]; //to find the other co-efficient values for (let j: number = 0; j < dx.length; j++) { if (slopeLength > j + 1) { if (slope[j] * slope[j + 1] <= 0) { ySpline[j + 1] = 0; } else { interPoint = dx[j] + dx[j + 1]; ySpline[j + 1] = 3 * interPoint / ((interPoint + dx[j + 1]) / slope[j] + (interPoint + dx[j]) / slope[j + 1]); } } } return ySpline; } /** * To find Cardinal Spline Coefficients */ private cardinalSplineCofficients(points: Points[], series: Series, isLow: boolean): number[] { const count: number = points.length; const ySpline: number[] = []; let cardinalSplineTension: number = series.cardinalSplineTension ? series.cardinalSplineTension : 0.5; cardinalSplineTension = cardinalSplineTension < 0 ? 0 : cardinalSplineTension > 1 ? 1 : cardinalSplineTension; for (let i: number = 0; i < count; i++) { if (i === 0) { ySpline[i] = (count > 2) ? (cardinalSplineTension * (points[i + 2].xValue - points[i].xValue)) : 0; } else if (i === (count - 1)) { ySpline[i] = (count > 2) ? (cardinalSplineTension * (points[count - 1].xValue - points[count - 3].xValue)) : 0; } else { ySpline[i] = (cardinalSplineTension * (points[i + 1].xValue - points[i - 1].xValue)); } } return ySpline; } /** * To find Clamped Spline Coefficients */ private clampedSplineCofficients(points: Points[], series: Series, isLow: boolean): number[] { const count: number = points.length; const ySpline: number[] = []; const ySplineDuplicate: number[] = []; for (let i: number = 0; i < count - 1; i++) { if (series.type === "SplineRangeArea") { if (!isLow) { points[1].yValue = points[1].high > points[1].low ? (points[1].high as number) : (points[1].low as number); points[0].yValue = points[0].high > points[0].low ? (points[0].high as number) : (points[0].low as number); points[points.length - 1].yValue = points[points.length - 1].high > points[points.length - 1].low ? (points[points.length - 1].high as number) : (points[points.length - 1].low as number); points[points.length - 2].yValue = points[points.length - 2].high > points[points.length - 2].low ? (points[points.length - 2].high as number) : (points[points.length - 2].low as number); } if (isLow) { points[1].yValue = points[1].low < points[1].high ? (points[1].low as number) : (points[1].high as number); points[0].yValue = points[0].low < points[0].high ? (points[0].low as number) : (points[0].high as number); points[points.length - 1].yValue = points[points.length - 1].low < points[points.length - 1].high ? (points[points.length - 1].low as number) : (points[points.length - 1].high as number); points[points.length - 2].yValue = points[points.length - 2].low < points[points.length - 2].high ? (points[points.length - 2].low as number) : (points[points.length - 2].high as number); } } ySpline[0] = (3 * (points[1].yValue - points[0].yValue)) / (points[1].xValue - points[0].xValue) - 3; ySplineDuplicate[0] = 0.5; ySpline[points.length - 1] = (3 * (points[points.length - 1].yValue - points[points.length - 2].yValue)) / (points[points.length - 1].xValue - points[points.length - 2].xValue); ySpline[0] = ySplineDuplicate[0] = Math.abs(ySpline[0]) === Infinity ? 0 : ySpline[0]; ySpline[points.length - 1] = ySplineDuplicate[points.length - 1] = Math.abs(ySpline[points.length - 1]) === Infinity ? 0 : ySpline[points.length - 1]; } return ySpline; } /** * To find Natural Spline Coefficients */ private naturalSplineCoefficients(points: Points[], series: Series, isLow: boolean): number[] { const count: number = points.length; const ySpline: number[] = []; const ySplineDuplicate: number[] = []; let dy1: number; let dy2: number; let coefficient1: number; let coefficient2: number; let coefficient3: number; ySpline[0] = ySplineDuplicate[0] = 0; ySpline[points.length - 1] = 0; for (let i: number = 1; i < count - 1; i++) { if(series.type === "SplineRangeArea"){ if(!isLow){ points[i + 1].yValue = points[i + 1].low > points[i + 1].high ? (points[i + 1].low as number) : (points[i + 1].high as number); points[i].yValue = points[i].low > points[i].high ? (points[i].low as number) : (points[i].high as number); points[i - 1].yValue = points[i - 1].low > points[i - 1].high ? (points[i - 1].low as number) : (points[i - 1].high as number); } if(isLow){ points[i + 1].yValue = points[i + 1].high < points[i + 1].low ? (points[i + 1].high as number) : (points[i + 1].low as number); points[i].yValue = points[i].high < points[i].low ? (points[i].high as number) : (points[i].low as number); points[i - 1].yValue = points[i - 1].high < points[i - 1].low ? (points[i - 1].high as number) : (points[i - 1].low as number); } } coefficient1 = points[i].xValue - points[i - 1].xValue; coefficient2 = points[i + 1].xValue - points[i - 1].xValue; coefficient3 = points[i + 1].xValue - points[i].xValue; dy1 = points[i + 1].yValue - points[i].yValue || null; dy2 = points[i].yValue - points[i - 1].yValue || null; if (coefficient1 === 0 || coefficient2 === 0 || coefficient3 === 0) { ySpline[i] = 0; ySplineDuplicate[i] = 0; } else { const p: number = 1 / (coefficient1 * ySpline[i - 1] + 2 * coefficient2); ySpline[i] = -p * coefficient3; ySplineDuplicate[i] = p * (6 * (dy1 / coefficient3 - dy2 / coefficient1) - coefficient1 * ySplineDuplicate[i - 1]); } } for (let k: number = count - 2; k >= 0; k--) { ySpline[k] = ySpline[k] * ySpline[k + 1] + ySplineDuplicate[k]; } return ySpline; } /** * To find the control points for spline. * * @returns {void} * @private */ public getControlPoints(point1: Points, point2: Points, ySpline1: number, ySpline2: number, series: Series): ControlPoints { let controlPoint1: ChartLocation; let controlPoint2: ChartLocation; let point: ControlPoints; let ySplineDuplicate1: number = ySpline1; let ySplineDuplicate2: number = ySpline2; const xValue1: number = point1.xValue; const yValue1: number = point1.yValue; const xValue2: number = point2.xValue; const yValue2: number = point2.yValue; switch (series.splineType) { case 'Cardinal': if (series.xAxis.valueType === 'DateTime') { ySplineDuplicate1 = ySpline1 / this.dateTimeInterval(series); ySplineDuplicate2 = ySpline2 / this.dateTimeInterval(series); } controlPoint1 = new ChartLocation(xValue1 + ySpline1 / 3, yValue1 + ySplineDuplicate1 / 3); controlPoint2 = new ChartLocation(xValue2 - ySpline2 / 3, yValue2 - ySplineDuplicate2 / 3); point = new ControlPoints(controlPoint1, controlPoint2); break; case 'Monotonic': const value: number = (xValue2 - xValue1) / 3; controlPoint1 = new ChartLocation(xValue1 + value, yValue1 + ySpline1 * value); controlPoint2 = new ChartLocation(xValue2 - value, yValue2 - ySpline2 * value); point = new ControlPoints(controlPoint1, controlPoint2); break; default: const one3: number = 1 / 3.0; let deltaX2: number = (xValue2 - xValue1); deltaX2 = deltaX2 * deltaX2; const y1: number = one3 * (((2 * yValue1) + yValue2) - one3 * deltaX2 * (ySpline1 + 0.5 * ySpline2)); const y2: number = one3 * ((yValue1 + (2 * yValue2)) - one3 * deltaX2 * (0.5 * ySpline1 + ySpline2)); controlPoint1 = new ChartLocation((2 * (xValue1) + (xValue2)) * one3, y1); controlPoint2 = new ChartLocation(((xValue1) + 2 * (xValue2)) * one3, y2); point = new ControlPoints(controlPoint1, controlPoint2); break; } return point; } /** * calculate datetime interval in hours */ protected dateTimeInterval(series: Series): number { const interval: IntervalType = series.xAxis.actualIntervalType; let intervalInMilliseconds: number; if (interval === 'Years') { intervalInMilliseconds = 365 * 24 * 60 * 60 * 1000; } else if (interval === 'Months') { intervalInMilliseconds = 30 * 24 * 60 * 60 * 1000; } else if (interval === 'Days') { intervalInMilliseconds = 24 * 60 * 60 * 1000; } else if (interval === 'Hours') { intervalInMilliseconds = 60 * 60 * 1000; } else if (interval === 'Minutes') { intervalInMilliseconds = 60 * 1000; } else if (interval === 'Seconds') { intervalInMilliseconds = 1000; } else { intervalInMilliseconds = 30 * 24 * 60 * 60 * 1000; } return intervalInMilliseconds; } /** * Animates the series. * * @param {Series} series - Defines the series to animate. * @returns {void} */ public doAnimation(series: Series): void { const option: AnimationModel = series.animation; this.doLinearAnimation(series, option); } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [schemas](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoneventbridgeschemas.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Schemas extends PolicyStatement { public servicePrefix = 'schemas'; /** * Statement provider for service [schemas](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoneventbridgeschemas.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); } /** * Creates an event schema discoverer. Once created, your events will be automatically map into corresponding schema documents * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#CreateDiscoverer */ public toCreateDiscoverer() { return this.to('CreateDiscoverer'); } /** * Create a new schema registry in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname.html#CreateRegistry */ public toCreateRegistry() { return this.to('CreateRegistry'); } /** * Create a new schema in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname.html#CreateSchema */ public toCreateSchema() { return this.to('CreateSchema'); } /** * Deletes discoverer in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#DeleteDiscoverer */ public toDeleteDiscoverer() { return this.to('DeleteDiscoverer'); } /** * Deletes an existing registry in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname.html#DeleteRegistry */ public toDeleteRegistry() { return this.to('DeleteRegistry'); } /** * Delete the resource-based policy attached to a given registry. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-policy.html#DeleteResourcePolicy */ public toDeleteResourcePolicy() { return this.to('DeleteResourcePolicy'); } /** * Deletes an existing schema in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname.html#DeleteSchema */ public toDeleteSchema() { return this.to('DeleteSchema'); } /** * Deletes a specific version of schema in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname-version-schemaversion.html#DeleteSchemaVersion */ public toDeleteSchemaVersion() { return this.to('DeleteSchemaVersion'); } /** * Retrieves metadata for generated code for specific schema in your account. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname-language-language.html#DescribeCodeBinding */ public toDescribeCodeBinding() { return this.to('DescribeCodeBinding'); } /** * Retrieves discoverer metadata in your account. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#DescribeDiscoverer */ public toDescribeDiscoverer() { return this.to('DescribeDiscoverer'); } /** * Describes an existing registry metadata in your account. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname.html#DescribeRegistry */ public toDescribeRegistry() { return this.to('DescribeRegistry'); } /** * Retrieves an existing schema in your account. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname.html#DescribeSchema */ public toDescribeSchema() { return this.to('DescribeSchema'); } /** * Allows exporting AWS registry or discovered schemas in OpenAPI 3 format to JSONSchema format. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-policy.html#ExportSchema */ public toExportSchema() { return this.to('ExportSchema'); } /** * Retrieves metadata for generated code for specific schema in your account. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname-language-language-source.html#GetCodeBindingSource */ public toGetCodeBindingSource() { return this.to('GetCodeBindingSource'); } /** * Retrieves schema for the provided list of sample events. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discover.html#GetDiscoveredSchema */ public toGetDiscoveredSchema() { return this.to('GetDiscoveredSchema'); } /** * Retrieves the resource-based policy attached to a given registry. * * Access Level: Read * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-policy.html#GetResourcePolicy */ public toGetResourcePolicy() { return this.to('GetResourcePolicy'); } /** * Lists all the discoverers in your account. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers.html#ListDiscoverers */ public toListDiscoverers() { return this.to('ListDiscoverers'); } /** * List all discoverers in your account. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries.html#ListRegistries */ public toListRegistries() { return this.to('ListRegistries'); } /** * List all versions of a schema. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname-versions.html#ListSchemaVersions */ public toListSchemaVersions() { return this.to('ListSchemaVersions'); } /** * List all schemas. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas.html#ListSchemas */ public toListSchemas() { return this.to('ListSchemas'); } /** * This action lists tags for a resource. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/tags-resource-arn.html#ListTagsForResource */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Generates code for specific schema in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname-language-language.html#PutCodeBinding */ public toPutCodeBinding() { return this.to('PutCodeBinding'); } /** * Attach resource-based policy to the specific registry. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-policy.html#PutResourcePolicy */ public toPutResourcePolicy() { return this.to('PutResourcePolicy'); } /** * Searches schemas based on specified keywords in your account. * * Access Level: List * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-search.html#SearchSchemas */ public toSearchSchemas() { return this.to('SearchSchemas'); } /** * Starts the specified discoverer. Once started the discoverer will automatically register schemas for published events to configured source in your account * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#StartDiscoverer */ public toStartDiscoverer() { return this.to('StartDiscoverer'); } /** * Starts the specified discoverer. Once started the discoverer will automatically register schemas for published events to configured source in your account * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#StopDiscoverer */ public toStopDiscoverer() { return this.to('StopDiscoverer'); } /** * This action tags an resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/tags-resource-arn.html#TagResource */ public toTagResource() { return this.to('TagResource'); } /** * This action removes a tag from on a resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/tags-resource-arn.html#UntagResource */ public toUntagResource() { return this.to('UntagResource'); } /** * Updates an existing discoverer in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-discoverers-id-discovererid.html#UpdateDiscoverer */ public toUpdateDiscoverer() { return this.to('UpdateDiscoverer'); } /** * Updates an existing registry metadata in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname.html#UpdateRegistry */ public toUpdateRegistry() { return this.to('UpdateRegistry'); } /** * Updates an existing schema in your account. * * Access Level: Write * * https://docs.aws.amazon.com/eventbridge/latest/schema-reference/v1-registries-name-registryname-schemas-name-schemaname.html#UpdateSchema */ public toUpdateSchema() { return this.to('UpdateSchema'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateDiscoverer", "CreateRegistry", "CreateSchema", "DeleteDiscoverer", "DeleteRegistry", "DeleteResourcePolicy", "DeleteSchema", "DeleteSchemaVersion", "PutCodeBinding", "PutResourcePolicy", "StartDiscoverer", "StopDiscoverer", "UpdateDiscoverer", "UpdateRegistry", "UpdateSchema" ], "Read": [ "DescribeCodeBinding", "DescribeDiscoverer", "DescribeRegistry", "DescribeSchema", "ExportSchema", "GetCodeBindingSource", "GetDiscoveredSchema", "GetResourcePolicy" ], "List": [ "ListDiscoverers", "ListRegistries", "ListSchemaVersions", "ListSchemas", "ListTagsForResource", "SearchSchemas" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type discoverer to the statement * * https://docs.aws.amazon.com/eventbridge/latest/userguide/iam-identity-based-access-control-eventbridge.html * * @param discovererId - Identifier for the discovererId. * @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 onDiscoverer(discovererId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:schemas:${Region}:${Account}:discoverer/${DiscovererId}'; arn = arn.replace('${DiscovererId}', discovererId); 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 registry to the statement * * https://docs.aws.amazon.com/eventbridge/latest/userguide/iam-identity-based-access-control-eventbridge.html * * @param registryName - Identifier for the registryName. * @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 onRegistry(registryName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:schemas:${Region}:${Account}:registry/${RegistryName}'; arn = arn.replace('${RegistryName}', registryName); 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 schema to the statement * * https://docs.aws.amazon.com/eventbridge/latest/userguide/iam-identity-based-access-control-eventbridge.html * * @param registryName - Identifier for the registryName. * @param schemaName - Identifier for the schemaName. * @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 onSchema(registryName: string, schemaName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:schemas:${Region}:${Account}:schema/${RegistryName}/${SchemaName}'; arn = arn.replace('${RegistryName}', registryName); arn = arn.replace('${SchemaName}', schemaName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { VNode, VNodeChildren, VNodeData } from 'vue/types/vnode'; import { Component as VueComponent, RenderContext, AsyncComponent } from 'vue/types/options'; import { JsonSchema } from './jsonschema'; export interface Dict<T = unknown> extends Record<string, T> {} export type Scalar = boolean | number | null | string; export type SchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null'; export type ParserKind = SchemaType | 'enum' | 'list' | 'textarea' | 'image' | 'file' | 'password'; export type ScalarKind = 'string' | 'password' | 'number' | 'integer' | 'null' | 'boolean' | 'hidden' | 'textarea' | 'image' | 'file' | 'radio' | 'checkbox'; export type ItemKind = 'enum' | 'list'; export type FieldKind = SchemaType | ScalarKind | ItemKind; export type ComponentsType = 'form' | 'message' | 'button' | 'helper' | FieldKind; export type Component = string | VueComponent | AsyncComponent; export interface Attributes { id: string; name?: string; type?: string; readonly?: boolean; required?: boolean; disabled?: boolean; 'aria-required'?: 'true'; [key: string]: any; } export interface AriaAttributes extends Attributes { readonly 'aria-labelledby'?: string; readonly 'aria-describedby'?: string; } export interface LabelAttributes { id?: string; for: string; } export interface HelperAttributes { id?: string; } export interface InputAttributes extends Attributes { type: string; value: string; } export interface StateAttributes<Type extends string> extends InputAttributes { type: Type | 'radio'; checked: boolean; } export type RadioAttributes = StateAttributes<'radio'>; export type CheckboxAttributes = StateAttributes<'checkbox'>; export interface NumberAttributes extends InputAttributes { type: 'number' | 'radio'; min?: number; max?: number; step?: number; } export interface NullAttributes extends InputAttributes { type: 'hidden'; value: '\u0000'; } export interface StringAttributes extends InputAttributes { type: 'text' | 'date' | 'datetime-local' | 'email' | 'idn-email' | 'time' | 'url' | 'radio' | 'file'; minlength?: number; maxlength?: number; pattern?: string; accept?: string; } export enum MessageType { Info = 0, Success = 1, Warining = 2, Error = 3 } export interface Message { type?: MessageType; text: string; } interface GenericField<TModel = any> { id: string; key: string; name?: string; isRoot: boolean; schema: JsonSchema; required: boolean; hasChildren: boolean; initialValue: TModel; value: TModel; readonly messages: Required<Message>[]; clear(): void; // clear field reset(): void; // reset initial field value addMessage(message: string, type?: MessageType): void; clearMessages(recursive?: boolean): void; } export interface Field< TKind extends FieldKind, TDescriptor extends IUIDescriptor = IUIDescriptor, TAttributes extends Attributes = Attributes, TModel = any > extends GenericField<TModel> { kind: TKind; deep: number; parent?: Field<any>; root: Field<any>; attrs: TAttributes; descriptor: TDescriptor; readonly messages: Required<Message>[]; // Value setValue(value: TModel, emitChange?: boolean): void; commit(): void; // Rendering requestRender(): void; } export interface ScalarField< TKind extends ScalarKind = ScalarKind, TAttributes extends Attributes = Attributes, TModel extends Scalar | unknown = unknown > extends Field<ScalarKind, IScalarDescriptor, Attributes, Scalar> { hasChildren: false; } export interface BooleanField extends ScalarField<'boolean', CheckboxAttributes, boolean> { toggle: () => void; } export type CheckboxField = ScalarField<'checkbox', CheckboxAttributes, unknown>; export type NumberField = ScalarField<'number', NumberAttributes, number>; export type NullField = ScalarField<'null', NullAttributes, null>; export type StringField = ScalarField<'string', StringAttributes, string>; export type RadioField = ScalarField<'radio', RadioAttributes, string>; export type InputField = BooleanField | NumberField | NullField | StringField | RadioField; export type UnknowField = Field<any>; export interface SetField< TKind extends FieldKind, TSetDescriptor extends ISetDescriptor, TModel, TChildField extends UnknowField, TAttributes extends Attributes = Attributes, > extends Field<TKind, TSetDescriptor, TAttributes, TModel> { hasChildren: true; fields: Dict<TChildField>; children: TChildField[]; /** * @param {string} path - The path of the requested field. * It's formated as JavaScript property access * notation (e.g., ".userProp.addressesProp[1].nameProp") */ getField: (path: string) => UnknowField | null; } export type UnknowSetField = SetField<any, ISetDescriptor, unknown, any>; export interface EnumField extends SetField<'enum', IEnumDescriptor, unknown, RadioField> { } export interface ArrayItemField extends Field<any, IArrayDescriptor, Attributes> { buttons: { moveUp: ActionButton<ActionMoveTrigger>; moveDown: ActionButton<ActionMoveTrigger>; delete: ActionButton<ActionDeleteTrigger>; }; } export type ActionPushTrigger = () => void; export type ActionMoveTrigger = () => ArrayItemField | undefined; export type ActionDeleteTrigger = () => ArrayItemField | undefined; export interface ActionButton<T extends Function> { disabled: boolean; trigger: T; } export interface ArrayField extends SetField<'array', IArrayDescriptor, any[], ArrayItemField> { uniqueItems: boolean; sortable: boolean; pushButton: ActionButton<ActionPushTrigger>; minItems: number; // default value: Number.MAX_SAFE_INTEGER maxItems: number; // default value: 1 if the field is required, 0 otherwise /** * Add a new item value and return `true` if succeed, else return `false` */ addItemValue: (itemValue: any) => boolean; } export interface ListItemModel { value: string; selected: boolean; } export interface ListField extends Field<'enum', IListDescriptor, Attributes> { items: ListItemModel[]; hasChildren: false; } export interface ObjectFieldChild extends Field<any, IObjectDescriptor, Attributes> { property: string; } export interface ObjectField extends SetField<'object', IObjectDescriptor, Dict, ObjectFieldChild> { } export type ValidatorFunction<T = UnknowField> = (field: T) => Promise<boolean>; export interface ParserOptions< TModel, TField extends Field<any, any, any> = UnknowField, TDescriptor extends DescriptorDefinition = DescriptorDefinition > { kind?: FieldKind; readonly key?: string; readonly schema: JsonSchema; readonly model?: TModel; readonly name?: string; readonly id?: string; readonly required?: boolean; readonly descriptor?: TDescriptor; components?: IComponents; readonly bracketedObjectInputName?: boolean; onChange?: (value: TModel, field: TField) => void; validator?: ValidatorFunction<TField>; requestRender?: (updatedFields: Field<any, IUIDescriptor, any, TModel>[]) => void; } export type UnknowParser = IParser<any>; export interface IParser< TModel, TField extends Field<any> = any, TDescriptor extends DescriptorDefinition = DescriptorDefinition > { readonly id: string; readonly isRoot: boolean; readonly options: ParserOptions<TModel, TField, TDescriptor>; readonly parent?: UnknowParser; readonly root: UnknowParser; readonly initialValue: TModel | unknown; model: TModel; rawValue: TModel; readonly kind: string; readonly field: TField; readonly schema: JsonSchema; parse: () => void; reset: () => void; clear: () => void; isEmpty: (data?: TModel) => boolean; requestRender: (fields?: UnknowField[]) => void; } export interface ISetParser< TModel, TField extends SetField<any, ISetDescriptor, TModel, UnknowField>, TDescriptor extends DescriptorDefinition = DescriptorDefinition > extends IParser<TModel, TField, TDescriptor> { } export interface DescriptorProperties<TDescriptor extends DescriptorDefinition = DescriptorDefinition> { readonly labelAttrs: LabelAttributes; readonly helperAttrs: HelperAttributes; readonly components: IComponents; readonly definition: TDescriptor; } export interface IUIDescriptor< TDescriptor extends DescriptorDefinition = DescriptorDefinition > extends Required<DescriptorDefinition>, DescriptorProperties<TDescriptor> { } export interface IScalarDescriptor extends DescriptorProperties<ScalarDescriptor>, Required<ScalarDescriptor> {} export interface IObjectDescriptor extends DescriptorProperties<ObjectDescriptor>, Required<ObjectDescriptor> { readonly childrenGroups: IObjectGroupItem[]; } export interface IObjectChildDescriptor extends IUIDescriptor<ObjectFieldChild> {} export interface IObjectGroupItem { id: string; label?: string; children: ObjectFieldChild[]; } export interface IArrayChildDescriptor extends IUIDescriptor<ArrayItemField> { buttons: ArrayItemButton[]; } export interface IArrayDescriptor extends DescriptorProperties<ArrayDescriptor>, Required<ArrayDescriptor> { readonly children: IArrayChildDescriptor[]; readonly pushButton: PushButtonDescriptor; } export type IEnumItemDescriptor = IUIDescriptor<RadioField>; export type ISetDescriptor = IEnumDescriptor | IArrayDescriptor | IObjectDescriptor; export interface IItemsUIDescriptor< T extends Field<any, any>, S extends Field<any, any>, D extends DescriptorDefinition = DescriptorDefinition > extends IUIDescriptor<D> {} export interface IEnumDescriptor extends IItemsUIDescriptor<EnumField, RadioField> { readonly children: IEnumItemDescriptor[]; } export interface IListDescriptor extends IItemsUIDescriptor<ListField, UnknowField> { readonly options: ListFieldItemDescriptor[]; } export interface ListFieldItemDescriptor extends ListItemModel { label: string; } export type SetDescriptor = EnumDescriptor | ArrayDescriptor | ObjectDescriptor; export type DescriptorInstance = ScalarDescriptor | SetDescriptor | ListDescriptor; export interface DescriptorDefinition<TKind extends FieldKind = FieldKind> { kind?: TKind; label?: string; helper?: string; visible?: boolean; // by default true. If false, component will be ignored on rendering component?: Component; attrs?: { [attr: string]: string; }; props?: { [prop: string]: unknown; }; } /** * Describe scalar types like: string, password, number, integer, * boolean, null, hidden field, textarea element, image and file * inputs, radio and checkbox elements */ export interface ScalarDescriptor extends DescriptorDefinition<ScalarKind> { } /** * Use to describe grouped object properties */ export interface ObjectGroupDescriptor extends DescriptorDefinition { properties: string[]; } /** * Describe JSON Schema with type `object` */ export interface ObjectDescriptor extends DescriptorDefinition { layout?: Component; // default: 'fieldset' properties?: { [schemaProperty: string]: DescriptorInstance; }; order?: string[]; groups?: { [groupId: string]: ObjectGroupDescriptor; }; } /** * Describe JSON Schema with key `enum` */ export interface ItemsDescriptor<TKind extends ItemKind> extends DescriptorDefinition<TKind> { items?: { [itemValue: string]: ScalarDescriptor; }; } /** * Describe HTML Radio Elements */ export interface EnumDescriptor extends ItemsDescriptor<'enum'> { layout?: Component; // default: 'fieldset' } /** * Describe HTML Select Element */ export interface ListDescriptor extends ItemsDescriptor<'list'> { } /** * Describe buttons for array schema */ export interface ButtonDescriptor<T extends string, A extends Function> extends Partial<ActionButton<A>> { type: T; label: string; tooltip?: string; visible?: boolean; component?: Component; } export type PushButtonDescriptor = ButtonDescriptor<'push', ActionPushTrigger>; export type MoveUpButtonDescriptor = ButtonDescriptor<'moveUp', ActionPushTrigger>; export type MoveDownButtonDescriptor = ButtonDescriptor<'moveDown', ActionPushTrigger>; export type DeleteButtonDescriptor = ButtonDescriptor<'delete', ActionPushTrigger>; export type UnknownButtonDescriptor = ButtonDescriptor<string, ActionPushTrigger>; export type ArrayItemButton = MoveUpButtonDescriptor | MoveDownButtonDescriptor | DeleteButtonDescriptor | UnknownButtonDescriptor; /** * Describe JSON Schema with type `array` */ export interface ArrayDescriptor extends DescriptorDefinition { layout?: Component; // default: 'fieldset' items?: DescriptorInstance[] | DescriptorInstance; pushButton: PushButtonDescriptor | null; buttons: ArrayItemButton[]; } /** * Custom Components API */ export interface IComponents { set(kind: ComponentsType, component: Component): void; get(kind: ComponentsType, fallbackComponent?: Component): Component; } export declare class Components implements IComponents { set(kind: ComponentsType, component: Component): void; get(kind: ComponentsType, fallbackComponent?: Component): Component; } export declare class NativeComponents extends Components {} /** * FormSchema API */ export interface CreateElement { (tag?: Component, children?: VNodeChildren): VNode; (tag?: Component, data?: VNodeData, children?: VNodeChildren): VNode; } export interface ElementProps<T extends Field<any>> { field: T; } export interface SubmitEvent extends Event { field: UnknowField; } export interface ButtonElementProps extends ElementProps<UnknowField> { button: UnknownButtonDescriptor; } export interface FunctionalComponentOptions<Props> { name?: string; functional: true; render?(this: undefined, createElement: CreateElement, context: RenderContext<Props>): VNode | VNode[]; } export type ArrayButtonComponent = FunctionalComponentOptions<ButtonElementProps>; export type MessageComponent = FunctionalComponentOptions<Required<Message>>; export type ArrayComponent = FunctionalComponentOptions<ElementProps<ArrayField>>; export type BooleanComponent = FunctionalComponentOptions<ElementProps<BooleanField>>; export type InputComponent = FunctionalComponentOptions<ElementProps<InputField>>; export type StateComponent = FunctionalComponentOptions<ElementProps<CheckboxField>>; export type FieldComponent = FunctionalComponentOptions<ElementProps<UnknowField>>; export type FieldsetComponent = FunctionalComponentOptions<ElementProps<ObjectField>>; export type HelperComponent = FunctionalComponentOptions<ElementProps<UnknowField>>; export type ListComponent = FunctionalComponentOptions<ElementProps<ListField>>; export type TextareaComponent = FunctionalComponentOptions<ElementProps<StringField>>; export interface InputEvent extends Event { readonly target: any; }
the_stack