text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Input, NgModule, Output, Renderer2, Injector } from '@angular/core'; import {AbstractJigsawComponent} from "../../common/common"; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {CommonModule} from '@angular/common'; import {TranslateService} from '@ngx-translate/core'; import {Subscription} from 'rxjs'; import {TimeGr, TimeService, TimeUnit, TimeWeekStart} from "../../common/service/time.service"; import {Time, TimeWeekDay, WeekTime} from "../../common/service/time.types"; import {PopupService} from "../../common/service/popup.service"; import {TranslateHelper} from "../../common/core/utils/translate-helper"; import {RequireMarkForCheck} from "../../common/decorator/mark-for-check"; import {CommonUtils} from "../../common/core/utils/common-utils"; export type DayCell = { day: number; isToday?: boolean; isOwnPrevMonth?: boolean; isOwnNextMonth?: boolean; isSelected?: boolean, isDisabled?: boolean, mark?: { type: string, label?: string }, isInRange?: boolean }; export type MonthCell = { month: number, label: string, isSelected?: boolean, isDisabled?: boolean, }; export type YearCell = { year: number, isSelected: boolean, isDisabled?: boolean, isOwnPrevOrNext?: boolean }; export type MarkDate = { date: Time | Time[] | MarkRange, mark: MarkDateType, label?: string }; export type MarkRange = { from: Time, to: Time }; export type MarkDateType = 'none' | 'recommend' | 'warn' | 'error'; /** * 时间范围生成函数,用于生成自定义的时间范围 * * $demo = date-time-picker/gr-items */ export type TimeShortcutFunction = () => [WeekTime, WeekTime] /** * 表示一个自定义的时间范围,一般用于配合`JigsawRangeDateTimePicker.grItems`属性使用,用于设置某个粒度下快速时间范围选择。 */ export class Shortcut { /** * 国际化提示信息,将被直接显示在界面上 * $demo = date-time-picker/gr-items */ label: string; /** * 时间范围的起止时间点,可以给出固定值,也可以给一个产生起止时间点的函数 * $demo = date-time-picker/gr-items */ dateRange: [WeekTime, WeekTime] | TimeShortcutFunction; } /** * 一个时间粒度 */ export class GrItem { /** * 国际化提示信息,将被直接显示在界面上 */ label: string; /** * 粒度值 * * $demo = date-time-picker/gr-items * $demo = date-time-picker/gr */ value: TimeGr; /** * 配置当前粒度下,用户能够选择的最大时间跨度。当某些查询请求必须约束用户选择某个范围内的时间时,这个配置项将非常有用。 * 例如查询银行流水时,我们常常被约束最长只能查询3个月的流水等。 * * 支持时间宏。关于时间宏,请参考这里`TimeUnit`的说明。 * * $demo = date-time-picker/gr-items */ span?: string; /** * 给出一组预定义的时间范围,这样用户可以通过这些值快速的设置好待选的时间范围,提高易用性。 * 只在和`JigsawRangeDateTimePicker`配合使用时才有效 * * 支持时间宏。关于时间宏,请参考这里`TimeUnit`的说明。 * * $demo = date-time-picker/gr-items */ shortcuts?: Shortcut[]; } @Component({ selector: 'jigsaw-date-picker, j-date-picker', templateUrl: './date-picker.html', host: { '[class.jigsaw-date-picker]': 'true', '[class.jigsaw-date-picker-error]': '!valid', '[class.jigsaw-date-picker-disabled]': 'disabled', '[style.width]': 'width', '[style.height]': 'height', }, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawDatePicker), multi: true}, ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawDatePicker extends AbstractJigsawComponent implements ControlValueAccessor { constructor(private _el: ElementRef, private _renderer: Renderer2, private _popService: PopupService, private _translateService: TranslateService, private _changeDetectorRef: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); this._langChangeSubscriber = TranslateHelper.languageChangEvent.subscribe(langInfo => { TimeService.setLocale(langInfo.curLang); if (this.initialized) { this._createCalendar(this._$curYear, this._$curMonth.month); } }); const currentLang = _translateService.currentLang ? _translateService.currentLang : _translateService.getBrowserLang(); _translateService.setDefaultLang(currentLang); TimeService.setLocale(currentLang); } /** * @internal */ public _$curMonth: MonthCell; /** * @internal */ public _$monthList: MonthCell[][] = []; /** * @internal */ public _$curYear: number; /** * @internal */ public _$rangeYear: string; /** * @internal */ public _$yearList: YearCell[][] = []; /** * @internal */ public _$dayList: DayCell[][] = []; /** * @internal */ public _$weekList: string[] = []; /** * @internal */ public _$selectMode: 'day' | 'month' | 'year' = 'day'; /** * @internal * * 标记是否有过交互,当时间组件存在确认按钮时,只有在人为交互之后,才需要点击确认来更新时间 * 而有些自动操作,比如设置limit时间之后的自动修正,是不需要点击确认按钮直接更新的 */ public _$touched: boolean; private _langChangeSubscriber: Subscription; private _weekPos: number[]; private readonly _DAY_CAL_COL = 7; private readonly _DAY_CAL_ROW = 6; private readonly _MONTH_CAL_COL = 3; private readonly _MONTH_CAL_ROW = 4; private readonly _YEAR_CAL_COL = 3; private readonly _YEAR_CAL_ROW = 4; private _createCalendar(year?: number, month?: number) { if (!year || !month) { let date = TimeService.convertValue(this.date, TimeGr.date); // 没有date会生成当前时间 [year, month] = [TimeService.getYear(date), TimeService.getMonth(date)]; } this._updateHead(year, month); this._createMonthCal(year); this._createYearCal(year); this._createDayCal(year, month); this._changeDetectorRef.markForCheck(); } private _updateHead(year: number, month: number) { this._$curMonth = {month: month, label: TimeService.getMonthShort()[month - 1]}; this._$curYear = year; } private _createYearCal(year: number) { this._verifyLimit(); let startYear = year - year % 10 - 1; let endYear = startYear + (this._YEAR_CAL_COL * this._YEAR_CAL_ROW - 1); this._$yearList = this._createYearList(startYear, endYear); this._$rangeYear = `${startYear + 1} - ${endYear - 1}` } private _createYearList(startYear: number, endYear: number): YearCell[][] { let yearCount = startYear; return Array.from(new Array(this._YEAR_CAL_ROW).keys()).map(() => { let rowArr = []; let index = 0; while (index < this._YEAR_CAL_COL) { rowArr[index] = { year: yearCount, isSelected: this._isYearSelected(yearCount), isDisabled: this._isYearDisabled(yearCount), isOwnPrevOrNext: this._isYearOwnPrevOrNext(yearCount, startYear, endYear) }; index++; yearCount++; } return rowArr; }); } private _isYearSelected(year: number) { return this.date && TimeService.getYear(TimeService.convertValue(this.date, this._gr)) == year; } private _isYearDisabled(year: number) { return (this.limitStart && year < TimeService.getYear(this.limitStart)) || (this.limitEnd && year > TimeService.getYear(this.limitEnd)) } private _isYearOwnPrevOrNext(year: number, startYear: number, endYear: number): boolean { return year <= startYear || year >= endYear } /** * @internal */ public _$showYearList() { this._$selectMode = this._$selectMode != 'year' ? 'year' : this.gr == TimeGr.month ? 'month' : 'day'; } /** * @internal */ public _$selectYear(yearCell: YearCell) { if (yearCell.isDisabled) { return; } if (this.date) { let date = TimeService.getRealDateOfMonth(yearCell.year, this._$curMonth.month, TimeService.getDay(TimeService.convertValue(this.date, TimeGr.date))); this.writeValue(date); } else { this._createCalendar(yearCell.year, this._$curMonth.month); } this._$selectMode = this.gr == TimeGr.month ? 'month' : 'day'; this._$touched = true; } private _createMonthCal(year: number) { this._verifyLimit(); this._$monthList = this._createMonthList(year); this._$curYear = year; } private _createMonthList(year: number): MonthCell[][] { let monthList: MonthCell[] = TimeService.getMonthShort().map((m, i) => ({ month: i + 1, label: m, isSelected: this._isMonthSelected(i + 1, year), isDisabled: this._isMonthDisabled(i + 1, year) })); let monthIndex = 0; return Array.from(new Array(this._MONTH_CAL_ROW).keys()).map(() => { let rowArr = []; let index = 0; while (index < this._MONTH_CAL_COL) { rowArr[index] = monthList[monthIndex]; index++; monthIndex++; } return rowArr; }) } private _isMonthSelected(month: number, year: number): boolean { if (!this.date) return false; let date = TimeService.convertValue(this.date, this._gr); return TimeService.getYear(date) == year && TimeService.getMonth(date) == month; } private _isMonthDisabled(month: number, year: number) { return (this.limitStart && (year < TimeService.getYear(this.limitStart) || (year == TimeService.getYear(this.limitStart) && month < TimeService.getMonth(this.limitStart)))) || (this.limitEnd && (year > TimeService.getYear(this.limitEnd) || (year == TimeService.getYear(this.limitEnd) && month > TimeService.getMonth(this.limitEnd)))); } /** * @internal */ public _$showMonthList() { this._$selectMode = this._$selectMode != 'month' || this.gr == TimeGr.month ? 'month' : 'day'; } /** * @internal */ public _$selectMonth(monthCell: MonthCell) { if (monthCell.isDisabled) { return; } if (monthCell.isSelected && TimeGr[this._gr] === 'month') { this.clearDate(); return; } if (this.date || this.gr == TimeGr.month) { let date = TimeService.getRealDateOfMonth(this._$curYear, monthCell.month, TimeService.getDay(TimeService.convertValue(this.date, TimeGr.date))); this.writeValue(date); } else { this._createCalendar(this._$curYear, monthCell.month); } if (this.gr != TimeGr.month) { this._$selectMode = 'day'; } this._$touched = true; } private _createDayCal(year: number, month: number) { this._verifyLimit(); this._weekPos = this._getWeekPos(); this._$weekList = this._createWeekList(this._weekPos); this._$dayList = this._createDayList(this._weekPos, year, month); } private _getWeekPos(): number[] { const weekStart = TimeService.getWeekStart(); let week; return Array.from(new Array(this._DAY_CAL_COL).keys()).map(num => { week = num == 0 ? weekStart : week; let weekCur = week; week++; if (week > this._DAY_CAL_COL - 1) { week = 0; } return weekCur; }); } private _createWeekList(weekPos: number[]): string[] { const weekdays = TimeService.getWeekdaysMin(); return weekPos.map(pos => weekdays[pos]); } private _createDayList(weekPos: number[], year: number, month: number): DayCell[][] { const [firstDate, lastDate] = [TimeService.convertValue(TimeService.getFirstDateOfMonth(year, month), TimeGr.date), TimeService.convertValue(TimeService.getLastDateOfMonth(year, month), TimeGr.date)]; let [countDayNum, maxDayNum, countNextMonthDayNum] = [1, TimeService.getDay(TimeService.getLastDateOfMonth(year, month)), 1]; const firstDayWeek = new Date(firstDate).getDay(); const firstDayWeekPos = weekPos.findIndex(w => w === firstDayWeek); return Array.from(new Array(this._DAY_CAL_ROW).keys()).map(row => { let index = row == 0 ? firstDayWeekPos : 0; let rowArr: DayCell[] = Array.from(new Array(this._DAY_CAL_COL).keys()).map(num => ({day: -1})); while (index < rowArr.length && countDayNum <= maxDayNum) { rowArr[index] = this._getDayCell(year, month, countDayNum, 'cur'); index++; countDayNum++; } if (row == 0 && firstDayWeekPos > 0) { index = firstDayWeekPos - 1; let addDay = -1; while (index >= 0) { let date = TimeService.addDate(firstDate, addDay, TimeUnit.d); let [y, m, d] = [TimeService.getYear(date), TimeService.getMonth(date), TimeService.getDay(date)]; rowArr[index] = this._getDayCell(y, m, d, 'prev'); addDay--; index--; } } if (countDayNum > maxDayNum) { while (index < rowArr.length) { let date = TimeService.addDate(lastDate, countNextMonthDayNum, TimeUnit.d); let [y, m, d] = [TimeService.getYear(date), TimeService.getMonth(date), TimeService.getDay(date)]; rowArr[index] = this._getDayCell(y, m, d, 'next'); countNextMonthDayNum++; index++; } } return rowArr; }); } private _getDayCell(year: number, month: number, day: number, type: 'cur' | 'prev' | 'next'): DayCell { let dayCell: DayCell = { day: day, isSelected: this._isDaySelected(year, month, day), isDisabled: this._isDayDisabled(year, month, day), mark: this._getDayMark(year, month, day), }; if (type == 'cur') { dayCell.isToday = this._isToday(year, month, day); dayCell.isInRange = this._isDayInRange(year, month, day); } else if (type == 'prev') { dayCell.isOwnPrevMonth = true; } else if (type == 'next') { dayCell.isOwnNextMonth = true; } return dayCell; } private _isToday(year: number, month: number, day: number) { const date = new Date(`${year}/${month}/${day} 00:00:00`); const ts1 = +date, ts2 = +new Date; return ts1 < ts2 && ts2 - ts1 < 86400000; } private _isDaySelected(year: number, month: number, day: number): boolean { if (!this.date) { return false; } if (this.gr == TimeGr.week) { const date = TimeService.getWeekDate(`${year}-${month}-${day}`); return this._isSameWeek(<TimeWeekDay>this.date, date); } else { const date = TimeService.convertValue(this.date, TimeGr.date); return TimeService.getYear(date) == year && TimeService.getMonth(date) == month && TimeService.getDay(date) == day } } private _isDayDisabled(year: number, month: number, day: number) { const date = TimeService.convertValue(`${year}-${month}-${day}`, TimeGr.date); return (this.limitStart && date < this.limitStart) || (this.limitEnd && date > this.limitEnd) } private _getDayMark(year: number, month: number, day: number): { type: string, label?: string } { if (!(this.markDates instanceof Array)) { return {type: 'none', label: ''}; } const compareDate = TimeService.convertValue(`${year}-${month}-${day}`, TimeGr.date); let [mark, label] = ['none', '']; this.markDates.find(markDate => { let date: any = markDate.date; let founded; if (typeof date == 'object' && date.hasOwnProperty('from') && date.hasOwnProperty('to')) { let [start, end] = [TimeService.convertValue((<MarkRange>date).from, TimeGr.date), TimeService.convertValue((<MarkRange>date).to, TimeGr.date)]; founded = compareDate >= start && compareDate <= end; } else { date = date instanceof Array ? date : [date]; founded = !!date.find(d => TimeService.convertValue(d, TimeGr.date) == compareDate); } if (founded) { mark = markDate.mark; label = markDate.label; return true; } return false; }); return {type: mark, label: label}; } private _isDayInRange(year: number, month: number, day: number): boolean { if (!this.date || !this.rangeDate) return false; const date = TimeService.convertValue(`${year}-${month}-${day}`, TimeGr.date); const selectDate = TimeService.convertValue(this.date, TimeGr.date); const rangeDate = TimeService.convertValue(this.rangeDate, TimeGr.date); return (date > selectDate && date <= rangeDate) || (date >= rangeDate && date < selectDate) } /** * @internal */ public _$selectDay(dayCell: DayCell) { if (dayCell.isDisabled) { return; } if (dayCell.isSelected) { this.clearDate(); return; } let [year, month, day] = [this._$curYear, this._$curMonth.month, dayCell.day]; if (dayCell.isOwnPrevMonth || dayCell.isOwnNextMonth) { let date = TimeService.addDate(`${year}-${month}`, dayCell.isOwnPrevMonth ? -1 : 1, TimeUnit.M); [year, month] = [TimeService.getYear(date), TimeService.getMonth(date)]; } this.writeValue(`${year}-${month}-${day}`); this._$touched = true; } public clearDate() { let [year, month] = [this._$curYear, this._$curMonth.month]; this._date = ""; this.runMicrotask(() => { this.dateChange.emit(this._date); this._propagateChange(this._date); this._changeDetectorRef.markForCheck(); }); this._createCalendar(year, month); } /** * @internal */ public _$handleCtrlBar(num: number) { if (this._$selectMode == 'day') { const date = TimeService.convertValue(TimeService.addDate(`${this._$curYear}-${this._$curMonth.month}`, num, TimeUnit.M), TimeGr.month); this._createCalendar(TimeService.getYear(date), TimeService.getMonth(date)); } else if (this._$selectMode == 'month') { this._$curYear = this._$curYear + num; this._createMonthCal(this._$curYear); this._createYearCal(this._$curYear); } else if (this._$selectMode == 'year') { this._$curYear = this._$curYear + 10 * num; this._createYearCal(this._$curYear); } } /** * 参考`JigsawDateTimePicker.disabled` * * @NoMarkForCheckRequired * * $demo = date-time-picker/disabled */ @Input() public disabled: boolean; /** * 参考`JigsawDateTimePicker.valid` * * @NoMarkForCheckRequired * * $demo = date-time-picker/valid */ @Input() public valid: boolean = true; /** * 当前日期控件的粒度发生变化时,发出此事件 * $demo = date-picker/gr */ @Output() public grChange = new EventEmitter<TimeGr>(); private _gr: TimeGr = TimeGr.date; /** * 获取或者设置当前日期控件的粒度粒度 * * @NoMarkForCheckRequired * * $demo = date-picker/gr */ @Input() public get gr(): TimeGr | string { return this._gr; } public set gr(value: TimeGr | string) { if (typeof value === 'string') { value = TimeGr[value]; } if (<TimeGr>value != this._gr) { this._gr = <TimeGr>value; this._$selectMode = TimeGr[this._gr] == 'month' ? 'month' : 'day'; if (this.initialized) { if (this.date) { this.writeValue(TimeService.convertValue(this.date, this._gr)); } else { this._createCalendar(); } } } } private _date: WeekTime; /** * 获取或者设置当前日期控件的值 * * @NoMarkForCheckRequired * * $demo = date-picker/basic */ @Input() public get date(): WeekTime { return this._date; } public set date(newValue: WeekTime) { if (this.initialized) { this.writeValue(newValue); } else { this._date = newValue; } } /** * 当前日期控件的值发生变化时,发出此事件 * $demo = date-picker/basic */ @Output() public dateChange = new EventEmitter<WeekTime>(); private _limitStart: Time; /** * `limitStart` 和 `limitEnd` 用于设定起止可选时间 * $demo = date-picker/limit */ public get limitStart(): Time { return this._limitStart; } /** * @NoMarkForCheckRequired */ @Input() public set limitStart(value: Time) { this._limitStart = value ? TimeService.convertValue(value, <TimeGr>this.gr) : null; if (this.initialized && this.date) { this.writeValue(this.date); } } private _limitEnd: Time; /** * 参考 `limitStart` * $demo = date-picker/limit */ public get limitEnd(): Time { return this._limitEnd } /** * @NoMarkForCheckRequired */ @Input() public set limitEnd(value: Time) { this._limitEnd = value ? TimeService.convertValue(value, <TimeGr>this.gr) : null; if (this.initialized && this.date) { this.writeValue(this.date); } } /** * 设置时间控件所支持的粒度。如果你的场景只允许用户选择天、周,则设置了这2个粒度之后,用户无法选择其他的粒度。 * $demo = date-picker/gr */ @Input() @RequireMarkForCheck() public grItems: GrItem[]; private _markDates: MarkDate[]; /** * 对选定的日期做标记,用于提示用户这些日期具有特定含义 * $demo = date-picker/mark */ @Input() @RequireMarkForCheck() public get markDates(): MarkDate[] { return this._markDates; } public set markDates(newValue: MarkDate[]) { if (!newValue) { return; } this._markDates = newValue; if (this.initialized) { this._createCalendar(); } } private _rangeDate: string; /** * @NoMarkForCheckRequired * * @internal */ @Input() public get rangeDate(): string { return this._rangeDate } public set rangeDate(date: string) { if (date == this._rangeDate) return; this._rangeDate = date; this._createCalendar(); } private _handleLimit(value: Time): Time { this._verifyLimit(); if (this._limitStart && value < this.limitStart) { return this.limitStart; } if (this._limitEnd && value > this.limitEnd) { return this.limitEnd; } return value; } private _verifyLimit() { if(!this.limitStart || !this.limitEnd) return; if(this.limitEnd < this.limitStart) { this._limitEnd = this.limitStart; } } private _weekStart: TimeWeekStart; /** * 设置周开始日期,可选值 sun mon tue wed thu fri sat。 * * @NoMarkForCheckRequired * * $demo = date-picker/week-start */ @Input() public get weekStart(): string | TimeWeekStart { return this._weekStart; } public set weekStart(value: string | TimeWeekStart) { if(CommonUtils.isUndefined(value)) return; if (typeof value === 'string') { this._weekStart = TimeWeekStart[value]; } else { this._weekStart = value; } TimeService.setWeekStart(this._weekStart); if(this.initialized) { if(this.date && this.gr == TimeGr.week) { // weekStart/janX改变时,在跨年时之前的weekDate可能会无效,需要重新计算 this.date = TimeService.getDateByGr(this.date, this.gr) } this._createCalendar(); } } private _firstWeekMustContains: number; /** * 设置一年的第一周要包含一月几号 * * @NoMarkForCheckRequired * * $demo = date-picker/week-start */ @Input() public get firstWeekMustContains(): number { return this._firstWeekMustContains; } public set firstWeekMustContains(value: number) { if(CommonUtils.isUndefined(value)) return; value = isNaN(value) || Number(value) < 1 ? 1 : Number(value); this._firstWeekMustContains = value; TimeService.setFirstWeekOfYear(this._firstWeekMustContains); if(this.initialized) { if(this.date && this.gr == TimeGr.week) { // weekStart/janX改变时,在跨年时之前的weekDate可能会无效,需要重新计算 this.date = TimeService.getDateByGr(this.date, this.gr) } this._createCalendar(); } } /** * @internal */ public _$changeGr($event: GrItem) { if (!$event) { return; } this.gr = $event.value; this.grChange.emit(<TimeGr>this.gr); this._changeDetectorRef.markForCheck(); } private _isSameWeek(date1: TimeWeekDay, date2: TimeWeekDay): boolean { return date1.year == date2.year && date1.week == date2.week; } private _isValueChanged(newValue) { let changed = true; if (this.gr == TimeGr.week) { if (this._date && this._isSameWeek(<TimeWeekDay>this._date, newValue)) { changed = false } } else if (newValue == this._date) { changed = false } return changed; } private _getValidDate(newValue) { newValue = this._handleLimit(TimeService.convertValue(newValue, <TimeGr>this.gr)); newValue = this.gr == TimeGr.week ? TimeService.getWeekDate(newValue) : newValue; return newValue; } public writeValue(newValue: any): void { if (!newValue) { return; } newValue = this._getValidDate(newValue); if (this._isValueChanged(newValue)) { this._date = newValue; this.runMicrotask(() => { this.dateChange.emit(this._date); this._propagateChange(this._date); this._changeDetectorRef.markForCheck(); }); } // 根据this.date创建日历 this._createCalendar(); } private _propagateChange: any = () => { }; public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { } ngOnInit() { super.ngOnInit(); if (this.date) { this.writeValue(this.date); } else { this._createCalendar(); } } ngOnDestroy() { super.ngOnDestroy(); this._langChangeSubscriber.unsubscribe(); } } @NgModule({ imports: [CommonModule], declarations: [JigsawDatePicker], exports: [JigsawDatePicker] }) export class JigsawDatePickerModule { constructor() { TimeService.deFineZhLocale(); } }
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { UnreachableCode } from '../../../../../resources/not_reached'; import { callOverlayHandler } from '../../../../../resources/overlay_plugin_api'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { NetMatches } from '../../../../../types/net_matches'; import { TriggerSet } from '../../../../../types/trigger'; export interface Data extends RaidbossData { calledSeekerSwords?: boolean; seekerSwords?: string[]; splitterDist?: number; seenFeralHowl?: boolean; seenSecretsRevealed?: boolean; reversalOfForces?: boolean; weaveMiasmaCount?: number; avowedTemperature?: number; unseenIds?: number[]; unseenBadRows?: number[]; unseenBadCols?: number[]; seenHeavensWrath?: boolean; } // TODO: warnings for mines after bosses? const seekerCenterX = -0.01531982; const seekerCenterY = 277.9735; const avowedCenterX = -272; const avowedCenterY = -82; // TODO: promote something like this to Conditions? const tankBusterOnParty = (data: Data, matches: NetMatches['StartsUsing']) => { if (matches.target === data.me) return true; if (data.role !== 'healer') return false; return data.party.inParty(matches.target); }; const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.DelubrumReginae, timelineFile: 'delubrum_reginae.txt', triggers: [ // *** Trinity Seeker *** { id: 'Delubrum Seeker Verdant Tempest', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5AB6', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5AB6', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5AB6', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5AB6', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5AB6', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5AB6', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Seeker Sword Cleanup', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5B5D', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5B5D', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5B5D', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5B5D', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5B5D', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5B5D', capture: false }), run: (data) => { delete data.calledSeekerSwords; delete data.seekerSwords; }, }, { id: 'Delubrum Seeker Mercy Swords', type: 'GainsEffect', netRegex: NetRegexes.gainsEffect({ target: ['Trinity Seeker', 'Seeker Avatar'], effectId: '808' }), netRegexDe: NetRegexes.gainsEffect({ target: ['Trinität Der Sucher', 'Spaltteil Der Sucher'], effectId: '808' }), netRegexFr: NetRegexes.gainsEffect({ target: ['Trinité Soudée', 'Clone De La Trinité Soudée'], effectId: '808' }), netRegexJa: NetRegexes.gainsEffect({ target: ['トリニティ・シーカー', 'シーカーの分体'], effectId: '808' }), netRegexCn: NetRegexes.gainsEffect({ target: ['求道之三位一体', '求道之分身'], effectId: '808' }), netRegexKo: NetRegexes.gainsEffect({ target: ['탐구의 삼위일체', '탐구의 분열체'], effectId: '808' }), durationSeconds: 10, alertText: (data, matches, output) => { if (data.calledSeekerSwords) return; data.seekerSwords ??= []; data.seekerSwords.push(matches.count.toUpperCase()); if (data.seekerSwords.length <= 1) return; const cleaves = data.seekerSwords; // Seen two cleaves, is this enough information to call?? // If no, we will wait until we have seen the third. if (data.seekerSwords.length === 2) { // Named constants for readability. const dir = { north: 0, east: 1, south: 2, west: 3 }; // Find boss-relative safe zones. const cleavetoSafeZones: { [cleave: string]: number[] } = { // Front right cleave. F7: [dir.south, dir.west], // Back right cleave. F8: [dir.west, dir.north], // Front left cleave. F9: [dir.east, dir.south], // Back left cleave. FA: [dir.north, dir.east], }; const cleave0 = cleaves[0]; const cleave1 = cleaves[1]; if (cleave0 === undefined || cleave1 === undefined) throw new UnreachableCode(); const first = cleavetoSafeZones[cleave0]; const second = cleavetoSafeZones[cleave1]; if (first === undefined || second === undefined) throw new UnreachableCode(); const intersect = first.filter((safe) => second.includes(safe)); if (intersect.length === 2) { console.error(`Sword: weird intersect: ${JSON.stringify(data.seekerSwords)}`); return; } // This is a bad pattern. Need to wait for three swords. if (intersect.length === 0) return; data.calledSeekerSwords = true; const cardinal = intersect[0]; if (cardinal === dir.north) return output.double!({ dir1: output.north!(), dir2: output.south!() }); if (cardinal === dir.east) return output.double!({ dir1: output.east!(), dir2: output.west!() }); if (cardinal === dir.south) return output.double!({ dir1: output.south!(), dir2: output.north!() }); if (cardinal === dir.west) return output.double!({ dir1: output.west!(), dir2: output.east!() }); // Or not? data.calledSeekerSwords = false; return; } const cleaveToDirection: { [cleave: string]: string } = { // Front right cleave. F7: output.west!(), // Back right cleave. F8: output.west!(), // Front left cleave. F9: output.east!(), // Back left cleave. FA: output.east!(), }; // Seen three clones, which means we weren't able to call with two. // Try to call out something the best we can. // Find the cleave we're missing and add it to the list. const allCleaveKeys = Object.keys(cleaveToDirection); const finalCleaveList = allCleaveKeys.filter((id) => !cleaves.includes(id)); const finalCleave = finalCleaveList[0]; if (finalCleave === undefined || finalCleaveList.length !== 1) { console.error(`Swords: bad intersection ${JSON.stringify(data.seekerSwords)}`); return; } cleaves.push(finalCleave); data.calledSeekerSwords = true; const dirs = cleaves.map((id) => cleaveToDirection[id]); return output.quadruple!({ dir1: dirs[0], dir2: dirs[1], dir3: dirs[2], dir4: dirs[3] }); }, // Unlike savage mode, Trinity Seeker can be pretty much anywhere. // So, turn "absolute cardinal directions" into boss-relative strings. // The above function uses cardinal directions to be closer to the DRS code. outputStrings: { north: { en: 'Front', de: 'Vorne', fr: 'Devant', ja: '前', cn: '上', ko: '앞', }, east: { en: 'Right', de: 'Rechts', fr: 'À droite', ja: '右', cn: '右', ko: '오른쪽', }, south: { en: 'Back', de: 'Hinten', fr: 'Derrière', ja: '後ろ', cn: '下', ko: '뒤', }, west: { en: 'Left', de: 'Links', fr: 'À gauche', ja: '左', cn: '左', ko: '왼쪽', }, double: { en: '${dir1} > ${dir2}', de: '${dir1} > ${dir2}', fr: '${dir1} > ${dir2}', ja: '${dir1} > ${dir2}', cn: '${dir1} > ${dir2}', ko: '${dir1} > ${dir2}', }, quadruple: { en: '${dir1} > ${dir2} > ${dir3} > ${dir4}', de: '${dir1} > ${dir2} > ${dir3} > ${dir4}', fr: '${dir1} > ${dir2} > ${dir3} > ${dir4}', ja: '${dir1} > ${dir2} > ${dir3} > ${dir4}', cn: '${dir1} > ${dir2} > ${dir3} > ${dir4}', ko: '${dir1} > ${dir2} > ${dir3} > ${dir4}', }, }, }, { id: 'Delubrum Seeker Baleful Swath', type: 'StartsUsing', // This is an early warning for casters for Baleful Swath on the Verdant Path cast. netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5A98', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5A98', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5A98', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5A98', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5A98', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5A98', capture: false }), response: Responses.goFrontBack('info'), }, { id: 'Delubrum Seeker Baleful Blade Out', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5AA1', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5AA1', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5AA1', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5AA1', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5AA1', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5AA1', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Out Behind Barricade', de: 'Geh raus, hinter die Barrikaden', fr: 'À l\'extérieur, derrière la barricade', ja: '柵の後ろに', cn: '栅栏后躲避', ko: '울타리 뒤에 숨기', }, }, }, { id: 'Delubrum Seeker Baleful Blade Knockback', type: 'StartsUsing', // We could call this on Phantom Edge 5AA0, but maybe that's too early? netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5AA2', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5AA2', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5AA2', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5AA2', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5AA2', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5AA2', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Knocked Into Barricade', de: 'Rückstoß in die Barrikaden', fr: 'Faites-vous pousser contre la barricade', ja: '柵に吹き飛ばされる', cn: '击退到栅栏上', ko: '울타리로 넉백당하기', }, }, }, { // There is no castbar for 5AB7, only this headmarker. id: 'Delubrum Seeker Merciful Arc', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00F3' }), response: Responses.tankBuster(), }, { id: 'Delubrum Seeker Iron Impact', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5ADB', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5ADB', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5ADB', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5ADB', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5ADB', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5ADB', capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Line Stack', de: 'In einer Linie sammeln', fr: 'Package en ligne', ja: '直線頭割り', cn: '直线分摊', ko: '직선 쉐어', }, }, }, { id: 'Delubrum Seeker Iron Splitter', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Seeker', id: '5AA3' }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Sucher', id: '5AA3' }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Soudée', id: '5AA3' }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・シーカー', id: '5AA3' }), netRegexCn: NetRegexes.startsUsing({ source: '求道之三位一体', id: '5AA3' }), netRegexKo: NetRegexes.startsUsing({ source: '탐구의 삼위일체', id: '5AA3' }), promise: async (data, matches) => { const seekerData = await callOverlayHandler({ call: 'getCombatants', ids: [parseInt(matches.sourceId, 16)], }); if (seekerData === null) { console.error(`Iron Splitter: null data`); return; } if (!seekerData.combatants) { console.error(`Iron Splitter: null combatants`); return; } if (seekerData.combatants.length !== 1) { console.error(`Iron Splitter: expected 1, got ${seekerData.combatants.length}`); return; } const seeker = seekerData.combatants[0]; if (!seeker) throw new UnreachableCode(); const x = seeker.PosX - seekerCenterX; const y = seeker.PosY - seekerCenterY; data.splitterDist = Math.hypot(x, y); }, alertText: (data, _matches, output) => { if (data.splitterDist === undefined) return; // All 100 examples I've looked at only hit distance=10, or distance=~14 // Guessing at the other distances, if they exist. // // blue inner = 0? // white inner = 6? // blue middle = 10 // white middle = 14 // blue outer = 18? // white outer = 22? const isWhite = Math.floor(data.splitterDist / 4) % 2; return isWhite ? output.goBlue!() : output.goWhite!(); }, outputStrings: { goBlue: { en: 'Blue Stone', de: 'Blauer Stein', fr: 'Pierre bleue', ja: '青い床へ', cn: '去蓝色', ko: '파랑 장판으로', }, goWhite: { en: 'White Sand', de: 'Weißer Sand', fr: 'Sable blanc', ja: '白い床へ', cn: '去白色', ko: '모래 장판으로', }, }, }, { id: 'Delubrum Seeker Burning Chains', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00EE' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Chain on YOU', de: 'Kette auf DIR', fr: 'Chaîne sur VOUS', ja: '自分に鎖', cn: '锁链点名', ko: '사슬 대상자', }, }, }, { // TODO: the FFXIV parser plugin does not include this as a "gains effect" line. id: 'Delubrum Seeker Burning Chains Move', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00EE' }), condition: Conditions.targetIsYou(), delaySeconds: 4, response: Responses.breakChains(), }, { id: 'Delubrum Seeker Dead Iron', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00ED' }), condition: Conditions.targetIsYou(), response: Responses.earthshaker(), }, { id: 'Delubrum Seeker Merciful Moon', type: 'StartsUsing', // 3 second warning to match savage timings. netRegex: NetRegexes.startsUsing({ source: 'Aetherial Orb', id: '5AAC', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Magiekugel', id: '5AAC', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Amas D\'Éther Élémentaire', id: '5AAC', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: '魔力塊', id: '5AAC', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '魔力块', id: '5AAC', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '마력 덩어리', id: '5AAC', capture: false }), delaySeconds: 1, alertText: (_data, _matches, output) => output.lookAway!(), outputStrings: { lookAway: { en: 'Look Away From Orb', de: 'Schau weg vom Orb', fr: 'Ne regardez pas l\'orbe', ja: '玉に背を向ける', cn: '背对白球', ko: '구슬에게서 뒤돌기', }, }, }, { id: 'Delubrum Seeker Merciful Blooms', type: 'Ability', // Call this on the ability of Merciful Moon, it starts casting much earlier. netRegex: NetRegexes.ability({ source: 'Aetherial Orb', id: '5AAC', capture: false }), netRegexDe: NetRegexes.ability({ source: 'Magiekugel', id: '5AAC', capture: false }), netRegexFr: NetRegexes.ability({ source: 'Amas D\'Éther Élémentaire', id: '5AAC', capture: false }), netRegexJa: NetRegexes.ability({ source: '魔力塊', id: '5AAC', capture: false }), netRegexCn: NetRegexes.ability({ source: '魔力块', id: '5AAC', capture: false }), netRegexKo: NetRegexes.ability({ source: '마력 덩어리', id: '5AAC', capture: false }), suppressSeconds: 1, infoText: (_data, _matches, output) => output.awayFromPurple!(), outputStrings: { awayFromPurple: { en: 'Away From Purple', de: 'Schau weg von Lila', fr: 'Éloignez-vous du violet', ja: '花に避ける', cn: '远离紫花', ko: '꽃 장판에서 멀리 떨어지기', }, }, }, // *** Dahu *** { id: 'Delubrum Dahu Shockwave', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Dahu', id: ['5760', '5761', '5762', '5763'] }), netRegexDe: NetRegexes.startsUsing({ source: 'Dahu', id: ['5760', '5761', '5762', '5763'] }), netRegexFr: NetRegexes.startsUsing({ source: 'Dahu', id: ['5760', '5761', '5762', '5763'] }), netRegexJa: NetRegexes.startsUsing({ source: 'ダウー', id: ['5760', '5761', '5762', '5763'] }), netRegexCn: NetRegexes.startsUsing({ source: '大兀', id: ['5760', '5761', '5762', '5763'] }), netRegexKo: NetRegexes.startsUsing({ source: '다후', id: ['5760', '5761', '5762', '5763'] }), // There's a 3s slow windup on the first, then a 1s opposite cast. suppressSeconds: 10, alertText: (_data, matches, output) => { if (matches.id === '5761' || matches.id === '5763') return output.leftThenRight!(); return output.rightThenLeft!(); }, outputStrings: { leftThenRight: { en: 'Left, Then Right', de: 'Links, dann Rechts', fr: 'À gauche, puis à droite', ja: '左 => 右', cn: '左 => 右', ko: '왼쪽 => 오른쪽', }, rightThenLeft: { en: 'Right, Then Left', de: 'Rechts, dann Links', fr: 'À droite, puis à gauche', ja: '右 => 左', cn: '右 => 左', ko: '오른쪽 => 왼쪽', }, }, }, { // TODO: is this true if you see a Feral Howl #4 and onward? id: 'Delubrum Dahu Feral Howl', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Dahu', id: '5755', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Dahu', id: '5755', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Dahu', id: '5755', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ダウー', id: '5755', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '大兀', id: '5755', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '다후', id: '5755', capture: false }), alertText: (data, _matches, output) => { if (data.seenFeralHowl) return output.knockbackAvoid!(); return output.knockback!(); }, run: (data) => data.seenFeralHowl = true, outputStrings: { knockback: { en: 'Unavoidable Knockback', de: 'Unvermeidbarer Rückstoß', fr: 'Poussée inévitable', ja: '避けないノックバック', cn: '击退 (防击退无效)', ko: '넉백 방지 불가', }, knockbackAvoid: { // This is also unavoidable, but that's really wordy and hopefully // you figured that out the first time. en: 'Knockback (Avoid Adds)', de: 'Rückstoß (vermeide die Adds)', fr: 'Poussée (Évitez les adds)', ja: 'ノックバック (雑魚に触らない)', cn: '击退 (避开小怪)', ko: '넉백 (쫄 피하기)', }, }, }, { id: 'Delubrum Dahu Hot Charge', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Dahu', id: '5764', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Dahu', id: '5764', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Dahu', id: '5764', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ダウー', id: '5764', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '大兀', id: '5764', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '다후', id: '5764', capture: false }), // This happens twice in a row suppressSeconds: 10, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Follow Second Charge', de: 'Folge dem 2. Ansturm', fr: 'Suivez la deuxième charge', ja: '2回目の突進に追う', cn: '紧跟第二次冲锋', ko: '두번째 돌진 따라가기', }, }, }, { id: 'Delubrum Dahu Heat Breath', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Dahu', id: '5766' }), netRegexDe: NetRegexes.startsUsing({ source: 'Dahu', id: '5766' }), netRegexFr: NetRegexes.startsUsing({ source: 'Dahu', id: '5766' }), netRegexJa: NetRegexes.startsUsing({ source: 'ダウー', id: '5766' }), netRegexCn: NetRegexes.startsUsing({ source: '大兀', id: '5766' }), netRegexKo: NetRegexes.startsUsing({ source: '다후', id: '5766' }), response: Responses.tankCleave(), }, { id: 'Delubrum Dahu Ripper Claw', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Dahu', id: '575D', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Dahu', id: '575D', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Dahu', id: '575D', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ダウー', id: '575D', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '大兀', id: '575D', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '다후', id: '575D', capture: false }), response: Responses.awayFromFront(), }, // *** Queen's Guard *** { id: 'Delubrum Guard Secrets Revealed', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Soldier', id: '5B6E', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Soldat Der Königin', id: '5B6E', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Soldat De La Reine', id: '5B6E', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ソルジャー', id: '5B6E', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王士兵', id: '5B6E', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 병사', id: '5B6E', capture: false }), infoText: (data, _matches, output) => { if (data.seenSecretsRevealed) return output.followUntethered!(); return output.awayFromTethered!(); }, run: (data) => data.seenSecretsRevealed = true, outputStrings: { awayFromTethered: { en: 'Away from tethered adds', de: 'Weg von den verbundenen Adds', fr: 'Éloignez-vous des adds liés', ja: '線に繋がる雑魚から離れる', cn: '远离连线小怪', ko: '선 연결된 쫄에서 떨어지기', }, followUntethered: { en: 'Follow untethered adds', de: 'Folge den nicht verbundenen Adds', fr: 'Suivez les adds non liés', ja: '線に繋がらない雑魚から離れる', cn: '靠近无连线小怪', ko: '선 연결되지 않은 쫄 따라가기', }, }, }, { id: 'Delubrum Guard Rapid Sever Soldier', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Soldier', id: '5809' }), netRegexDe: NetRegexes.startsUsing({ source: 'Soldat Der Königin', id: '5809' }), netRegexFr: NetRegexes.startsUsing({ source: 'Soldat De La Reine', id: '5809' }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ソルジャー', id: '5809' }), netRegexCn: NetRegexes.startsUsing({ source: '女王士兵', id: '5809' }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 병사', id: '5809' }), condition: tankBusterOnParty, response: Responses.tankBuster(), }, { id: 'Delubrum Guard Blood And Bone Soldier', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Soldier', id: '5808', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Soldat Der Königin', id: '5808', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Soldat De La Reine', id: '5808', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ソルジャー', id: '5808', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王士兵', id: '5808', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 병사', id: '5808', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Guard Shot In The Dark', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Gunner', id: '5811' }), netRegexDe: NetRegexes.startsUsing({ source: 'Schütze Der Königin', id: '5811' }), netRegexFr: NetRegexes.startsUsing({ source: 'Fusilier De La Reine', id: '5811' }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ガンナー', id: '5811' }), netRegexCn: NetRegexes.startsUsing({ source: '女王枪手', id: '5811' }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 총사', id: '5811' }), condition: tankBusterOnParty, response: Responses.tankBuster(), }, { id: 'Delubrum Guard Automatic Turret', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Gunner', id: '580B', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Schütze Der Königin', id: '580B', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fusilier De La Reine', id: '580B', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ガンナー', id: '580B', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王枪手', id: '580B', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 총사', id: '580B', capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Avoid Laser Bounces', de: 'Weiche den abgelenken Lasern aus', fr: 'Évitez les rebonds de laser', ja: 'レーザーを避ける', cn: '躲避激光', ko: '레이저 피하기', }, }, }, { id: 'Delubrum Guard Queen\'s Shot', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Gunner', id: '5810', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Schütze Der Königin', id: '5810', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fusilier De La Reine', id: '5810', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ガンナー', id: '5810', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王枪手', id: '5810', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 총사', id: '5810', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Guard Reversal Of Forces', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Warrior', id: '57FF', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegerin Der Königin', id: '57FF', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Guerrière De La Reine', id: '57FF', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ウォリアー', id: '57FF', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王战士', id: '57FF', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 전사', id: '57FF', capture: false }), alertText: (_data, _matches, output) => output.text!(), run: (data) => data.reversalOfForces = true, outputStrings: { text: { en: 'Stand On Small Bomb', de: 'Auf kleinen Bomben stehen', fr: 'Placez-vous sur une petite bombe', ja: '小さい爆弾を踏む', cn: '站在小炸弹上', ko: '작은 폭탄 위에 서기', }, }, }, { id: 'Delubrum Guard Above Board', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Warrior', id: '57FC', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegerin Der Königin', id: '57FC', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Guerrière De La Reine', id: '57FC', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ウォリアー', id: '57FC', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王战士', id: '57FC', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 전사', id: '57FC', capture: false }), alertText: (data, _matches, output) => { if (data.reversalOfForces) return; return output.text!(); }, run: (data) => delete data.reversalOfForces, outputStrings: { text: { en: 'Stand On Large Bomb', de: 'Auf großen Bomben stehen', fr: 'Placez-vous sur une grosse bombe', ja: '大きい爆弾を踏む', cn: '站在大炸弹上', ko: '큰 폭탄 위에 서기', }, }, }, { id: 'Delubrum Guard Blood And Bone Warrior', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Warrior', id: '5800', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegerin Der Königin', id: '5800', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Guerrière De La Reine', id: '5800', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ウォリアー', id: '5800', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王战士', id: '5800', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 전사', id: '5800', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Guard Shield Omen', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '57F1', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '57F1', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '57F1', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '57F1', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '57F1', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '57F1', capture: false }), response: Responses.getUnder(), }, { id: 'Delubrum Guard Sword Omen', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '57F0', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '57F0', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '57F0', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '57F0', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '57F0', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '57F0', capture: false }), response: Responses.getOut(), }, { id: 'Delubrum Guard Rapid Sever Knight', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '57FB' }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '57FB' }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '57FB' }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '57FB' }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '57FB' }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '57FB' }), condition: tankBusterOnParty, response: Responses.tankBuster(), }, { id: 'Delubrum Guard Blood And Bone Knight', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '57FA', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '57FA', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '57FA', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '57FA', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '57FA', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '57FA', capture: false }), response: Responses.aoe(), }, // *** Bozjan Phantom { id: 'Delubrum Phantom Weave Miasma', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Bozjan Phantom', id: '57A3', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Bozja-Phantom', id: '57A3', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fantôme Bozjien', id: '57A3', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ボズヤ・ファントム', id: '57A3', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '博兹雅幻灵', id: '57A3', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '보즈야 유령', id: '57A3', capture: false }), preRun: (data) => data.weaveMiasmaCount = (data.weaveMiasmaCount || 0) + 1, delaySeconds: 3, infoText: (data, _matches, output) => { if (data.weaveMiasmaCount && data.weaveMiasmaCount >= 3) return output.weaveWithKnockback!(); return output.weaveNoKnockback!(); }, outputStrings: { weaveNoKnockback: { en: 'Go To North Circle', de: 'Geh zum Kreis im Norden', fr: 'Allez au cercle Nord', ja: '北のドーナツ範囲に入る', cn: '去上面(北面)月环', ko: '북쪽 원으로 이동', }, weaveWithKnockback: { en: 'Get Knocked Back To Circle', de: 'Lass dich zum Kreis im Norden zurückstoßen', fr: 'Faites-vous pousser dans le cercle', ja: '北のドーナツ範囲へ吹き飛ばされる', cn: '击退到上面(北面)月环中', ko: '원으로 넉백 당하기', }, }, }, { id: 'Delubrum Phantom Malediction Of Agony', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Bozjan Phantom', id: '57AF', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Bozja-Phantom', id: '57AF', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fantôme Bozjien', id: '57AF', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ボズヤ・ファントム', id: '57AF', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '博兹雅幻灵', id: '57AF', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '보즈야 유령', id: '57AF', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Phantom Undying Hatred', type: 'StartsUsing', // "57AB Summon" is used here to avoid an additional name to translate. // "57AC Undying Hatred" is from Stuffy Wraith. netRegex: NetRegexes.startsUsing({ source: 'Bozjan Phantom', id: '57AB', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Bozja-Phantom', id: '57AB', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fantôme Bozjien', id: '57AB', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ボズヤ・ファントム', id: '57AB', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '博兹雅幻灵', id: '57AB', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '보즈야 유령', id: '57AB', capture: false }), delaySeconds: 5, // This is covered by Weave Miasma after the first "learn how this works" action. suppressSeconds: 9999, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Unavoidable Knockback', de: 'Unvermeidbarer Rückstoß', fr: 'Poussée inévitable', ja: '避けないノックバック', cn: '击退 (防击退无效)', ko: '넉백 방지 불가', }, }, }, { id: 'Delubrum Phantom Excruciation', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Bozjan Phantom', id: '5809' }), netRegexDe: NetRegexes.startsUsing({ source: 'Bozja-Phantom', id: '5809' }), netRegexFr: NetRegexes.startsUsing({ source: 'Fantôme Bozjien', id: '5809' }), netRegexJa: NetRegexes.startsUsing({ source: 'ボズヤ・ファントム', id: '5809' }), netRegexCn: NetRegexes.startsUsing({ source: '博兹雅幻灵', id: '5809' }), netRegexKo: NetRegexes.startsUsing({ source: '보즈야 유령', id: '5809' }), condition: tankBusterOnParty, response: Responses.tankBuster(), }, // *** Trinity Avowed { id: 'Delubrum Avowed Wrath Of Bozja', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '5975' }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '5975' }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '5975' }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '5975' }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '5975' }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '5975' }), response: Responses.tankCleave('alert'), }, { id: 'Delubrum Avowed Glory Of Bozja', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '5976', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '5976', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '5976', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '5976', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '5976', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '5976', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Avowed Hot And Cold', type: 'GainsEffect', // 89D: Running Hot: +1 // 8A4: Running Hot: +2 // 8DC: Running Cold: -1 // 8E2: Running Cold: -2 netRegex: NetRegexes.gainsEffect({ effectId: ['89D', '8A4', '8DC', '8E2'] }), condition: Conditions.targetIsYou(), run: (data, matches) => { const tempMap: { [id: string]: number } = { '89D': 1, '8A4': 2, '8DC': -1, '8E2': -2, }; data.avowedTemperature = tempMap[matches.effectId.toUpperCase()]; }, }, { id: 'Delubrum Avowed Freedom Of Bozja', type: 'StartsUsing', // Arguably, the Elemental Impact (meteor falling) has different ids depending on orb type, // e.g. 5960, 5962, 4F55, 4556, 4F99, 4F9A. // So we could give directions here, but probably that's just more confusing. netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '597C', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '597C', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '597C', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '597C', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '597C', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '597C', capture: false }), delaySeconds: 10, alertText: (data, _matches, output) => { switch (data.avowedTemperature) { case 2: return output.minusTwo!(); case 1: return output.minusOne!(); case -1: return output.plusOne!(); case -2: return output.plusTwo!(); default: return output.unknownTemperature!(); } }, outputStrings: { plusTwo: { en: 'Go to +2 Heat Meteor', de: 'Geh zum +2 Heiß Meteor', fr: 'Allez au météore de chaleur +2', ja: '炎属性+2を踏む', cn: '踩火+2', ko: '+2 불 운석쪽으로', }, plusOne: { en: 'Go to +1 Heat Meteor', de: 'Geh zum +1 Heiß Meteor', fr: 'Allez au météore de chaleur +1', ja: '炎属性+1を踏む', cn: '踩火+1', ko: '+1 불 운석쪽으로', }, minusOne: { en: 'Go to -1 Cold Meteor', de: 'Geh zum -1 Kalt Meteor', fr: 'Allez au météore de froid -1', ja: '氷属性-1を踏む', cn: '踩冰-1', ko: '-1 얼음 운석쪽으로', }, minusTwo: { en: 'Go to -2 Cold Meteor', de: 'Geh zum -2 Kalt Meteor', fr: 'Allez au météore de froid -2', ja: '氷属性-2を踏む', cn: '踩冰-2', ko: '-2 얼음 운석쪽으로', }, unknownTemperature: { en: 'Stand In Opposite Meteor', de: 'Steh im entgegengesetztem Meteor', fr: 'Placez-vous au météore de l\'élément opposé', ja: '体温と逆のメテオを受ける', cn: '接相反温度的陨石', ko: '반대속성 운석에 서기', }, }, }, { id: 'Delubrum Avowed Shimmering Shot', type: 'StartsUsing', // See comments on Freedom Of Bozja above. netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '597F', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '597F', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '597F', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '597F', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '597F', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '597F', capture: false }), delaySeconds: 3, alertText: (data, _matches, output) => { switch (data.avowedTemperature) { case 2: return output.minusTwo!(); case 1: return output.minusOne!(); case -1: return output.plusOne!(); case -2: return output.plusTwo!(); default: return output.unknownTemperature!(); } }, outputStrings: { plusTwo: { en: 'Follow +2 Heat Arrow', de: 'Folge dem +2 Heiß Pfeilen', fr: 'Suivez la flèche de chaleur +2', ja: '炎属性+2に従う', cn: '接火+2', ko: '+2 불 화살쪽으로', }, plusOne: { en: 'Follow +1 Heat Arrow', de: 'Folge dem +1 Heiß Pfeilen', fr: 'Suivez la flèche de chaleur +1', ja: '炎属性+1に従う', cn: '接火+1', ko: '+1 불 화살쪽으로', }, minusOne: { en: 'Follow -1 Cold Arrow', de: 'Folge dem -1 Kalt Pfeilen', fr: 'Suivez la flèche de froid -1', ja: '氷属性-1に従う', cn: '接冰-1', ko: '-1 얼음 화살쪽으로', }, minusTwo: { en: 'Follow -2 Cold Arrow', de: 'Folge dem -2 Kalt Pfeilen', fr: 'Suivez la flèche de froid -2', ja: '氷属性-2に従う', cn: '接冰-2', ko: '-2 얼음 화살쪽으로', }, unknownTemperature: { en: 'Follow Opposite Arrow', de: 'Gehe in die entgegengesetzten Pfeile', fr: 'Suivez la flèche de l\'élément opposé', ja: '体温と逆のあみだに従う', cn: '接相反温度的线', ko: '반대속성 화살 맞기', }, }, }, { // 5B65 = right cleave, heat+2 // 5B66 = right cleave, cold+2 // 5B67 = left cleave, heat+2 // 5B68 = left cleave, cold+2 // 596D = right cleave, heat+1 // 596E = right cleave, cold+1 // 596F = left cleave, heat+1 // 5970 = left cleave, cold+1 id: 'Delubrum Avowed Hot And Cold Cleaves', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: ['5B6[5-8]', '596[DEF]', '5970'] }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: ['5B6[5-8]', '596[DEF]', '5970'] }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: ['5B6[5-8]', '596[DEF]', '5970'] }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: ['5B6[5-8]', '596[DEF]', '5970'] }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: ['5B6[5-8]', '596[DEF]', '5970'] }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: ['5B6[5-8]', '596[DEF]', '5970'] }), response: (data, matches, output) => { // cactbot-builtin-response output.responseOutputStrings = { left: { en: 'Left', de: 'Links', fr: 'À gauche', ja: '左', cn: '左', ko: '왼쪽', }, right: { en: 'Right', de: 'Rechts', fr: 'À droite', ja: '右', cn: '右', ko: '오른쪽', }, plusTwo: { en: 'Be in ${side} Cleave (+2 Hot)', de: 'Sei im ${side} Cleave (+2 Heiß)', fr: 'Soyez du ${side} Cleave (+2 chaud)', ja: '${side}側へ (炎属性+2)', cn: '去${side}侧 (火+2)', ko: '${side} 광역기 맞기 (+2 불속성)', }, plusOne: { en: 'Be in ${side} Cleave (+1 Hot)', de: 'Sei im ${side} Cleave (+1 Heiß)', fr: 'Soyez du ${side} Cleave (+1 chaud)', ja: '${side}側へ (炎属性+1)', cn: '去${side}侧 (火+1)', ko: '${side} 광역기 맞기 (+1 불속성)', }, minusOne: { en: 'Be in ${side} Cleave (-1 Cold)', de: 'Sei im ${side} Cleave (-1 Kalt)', fr: 'Soyez du ${side} Cleave (-1 froid)', ja: '${side}側へ (氷属性-1)', cn: '去${side}侧 (冰-1)', ko: '${side} 광역기 맞기 (-1 얼음속성)', }, minusTwo: { en: 'Be in ${side} Cleave (-2 Cold)', de: 'Sei im ${side} Cleave (-2 Kalt)', fr: 'Soyez du ${side} Cleave (-2 froid)', ja: '${side}側へ (氷属性-2)', cn: '去${side}侧 (冰-2)', ko: '${side} 광역기 맞기 (-2 얼음속성)', }, avoid: { en: 'Go ${side} (avoid!)', de: 'Gehe nach ${side} (ausweichen!)', fr: 'Allez à ${side} (évitez !)', ja: '${side}側へ (避ける!)', cn: '去${side}侧 (别吃顺劈!)', ko: '${side}으로 피하기!', }, }; const isLeft = ['5B67', '5B68', '596F', '5970'].includes(matches.id); const side = isLeft ? output.left!() : output.right!(); const safeSide = isLeft ? output.right!() : output.left!(); const avoidInfoText = { infoText: output.avoid!({ side: safeSide }) }; switch (matches.id) { case '5B66': case '5B68': if (data.avowedTemperature === 2) return { alertText: output.minusTwo!({ side: side }) }; return avoidInfoText; case '596E': case '5970': if (data.avowedTemperature === 1) return { alertText: output.minusOne!({ side: side }) }; return avoidInfoText; case '596D': case '596F': if (data.avowedTemperature === -1) return { alertText: output.plusOne!({ side: side }) }; return avoidInfoText; case '5B65': case '5B67': if (data.avowedTemperature === -2) return { alertText: output.plusTwo!({ side: side }) }; return avoidInfoText; } }, }, { id: 'Delubrum Avowed Gleaming Arrow Collect', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Avowed Avatar', id: '5974' }), netRegexDe: NetRegexes.startsUsing({ source: 'Spaltteil Der Eingeschworenen', id: '5974' }), netRegexFr: NetRegexes.startsUsing({ source: 'Clone De La Trinité Féale', id: '5974' }), netRegexJa: NetRegexes.startsUsing({ source: 'アヴァウドの分体', id: '5974' }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之分身', id: '5974' }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 분열체', id: '5974' }), run: (data, matches) => { data.unseenIds ??= []; data.unseenIds.push(parseInt(matches.sourceId, 16)); }, }, { id: 'Delubrum Avowed Gleaming Arrow', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Avowed Avatar', id: '5974', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Spaltteil Der Eingeschworenen', id: '5974', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Clone De La Trinité Féale', id: '5974', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'アヴァウドの分体', id: '5974', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之分身', id: '5974', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 분열체', id: '5974', capture: false }), delaySeconds: 0.5, suppressSeconds: 10, promise: async (data) => { const unseenIds = data.unseenIds; if (!unseenIds) return; const unseenData = await callOverlayHandler({ call: 'getCombatants', ids: unseenIds, }); if (unseenData === null) { console.error(`Gleaming Arrow: null data`); return; } if (!unseenData.combatants) { console.error(`Gleaming Arrow: null combatants`); return; } if (unseenData.combatants.length !== unseenIds.length) { console.error(`Gleaming Arrow: expected ${unseenIds.length}, got ${unseenData.combatants.length}`); return; } data.unseenBadRows = []; data.unseenBadCols = []; for (const avatar of unseenData.combatants) { const x = avatar.PosX - avowedCenterX; const y = avatar.PosY - avowedCenterY; // y=-107 = north side, x = -252, -262, -272, -282, -292 // x=-247 = left side, y = -62, -72, -82, -92, -102 // Thus, the possible deltas are -20, -10, 0, +10, +20. // The other coordinate is +/-25 from center. const maxDist = 22; if (Math.abs(x) < maxDist) { const col = Math.round((x + 20) / 10); data.unseenBadCols.push(col); } if (Math.abs(y) < maxDist) { const row = Math.round((y + 20) / 10); data.unseenBadRows.push(row); } } data.unseenBadRows.sort(); data.unseenBadCols.sort(); }, alertText: (data, _matches, output) => { delete data.unseenIds; if (!data.unseenBadRows || !data.unseenBadCols) return; // consider asserting that badCols are 0, 2, 4 here. if (data.unseenBadRows.includes(2)) return output.bowLight!(); return output.bowDark!(); }, outputStrings: { bowDark: { en: 'On Dark (E/W of center)', de: 'Auf Dunkel (O/W von der Mitte)', fr: 'Sur une foncée (E/O du centre)', ja: '闇へ (東西)', cn: '去黑色 (东西/左右)', ko: '어두운 타일 (맵 중앙의 왼/오른쪽)', }, bowLight: { en: 'On Light (diagonal from center)', de: 'Auf Licht (Diagonal von der Mitte)', fr: 'Sur une claire (diagonale du centre)', ja: '光へ (斜め)', cn: '去白色 (对角)', ko: '밝은 타일 (맵 중앙의 대각선)', }, }, }, { id: 'Delubrum Avowed Fury Of Bozja', type: 'StartsUsing', // Allegiant Arsenal 5987 = staff (out), followed up with Fury of Bozja 5973 netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '5987', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '5987', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '5987', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '5987', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '5987', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '5987', capture: false }), response: Responses.getOut(), }, { id: 'Delubrum Avowed Flashvane', type: 'StartsUsing', // Allegiant Arsenal 5986 = bow (get behind), followed up by Flashvane 5972 netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '5986', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '5986', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '5986', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '5986', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '5986', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '5986', capture: false }), response: Responses.getBehind(), }, { id: 'Delubrum Avowed Infernal Slash', type: 'StartsUsing', // Allegiant Arsenal 5985 = sword (get front), followed up by Infernal Slash 5971 netRegex: NetRegexes.startsUsing({ source: 'Trinity Avowed', id: '5985', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Trinität Der Eingeschworenen', id: '5985', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Trinité Féale', id: '5985', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'トリニティ・アヴァウド', id: '5985', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '誓约之三位一体', id: '5985', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '맹세의 삼위일체', id: '5985', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get In Front', de: 'Geh vor den Boss', fr: 'Soyez devant', ja: 'ボスの正面へ', cn: '去正面', ko: '정면에 서기', }, }, }, // *** The Queen { id: 'Delubrum Queen Empyrean Iniquity', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C8', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C8', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C8', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C8', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C8', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C8', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Queen Cleansing Slash', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C5' }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C5' }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C5' }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C5' }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C5' }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C5' }), condition: tankBusterOnParty, // Probably this is where you swap, but maybe that's not something you can // count on in an alliance raid, where there might not even be another tank. response: Responses.tankBuster(), }, { id: 'Delubrum Queen Cleansing Slash Bleed', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C5' }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C5' }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C5' }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C5' }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C5' }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C5' }), condition: (data) => data.CanCleanse(), delaySeconds: 5, infoText: (data, matches, output) => output.text!({ player: data.ShortName(matches.target) }), outputStrings: { text: { en: 'Esuna ${player}', de: 'Medica ${player}', fr: 'Guérison sur ${player}', ja: 'エスナ: ${player}', cn: '解除死亡宣告: ${player}', ko: '"${player}" 에스나', }, }, }, { id: 'Delubrum Queen Northswain\'s Glow', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C3', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C3', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C3', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C3', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C3', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C3', capture: false }), alertText: (_data, _matches, output) => output.text!(), // Technically, this is "away from where the moving lines intersect each other" // but "away from orbs" also will do the trick here. outputStrings: { text: { en: 'Away from Line Intersections', de: 'Geh weg von den Linienkreuzungen', fr: 'Éloignez-vous des intersections de ligne', ja: '十字から離れる', cn: '远离线的交点', ko: '선이 만나는 지점에서 떨어지기', }, }, }, { id: 'Delubrum Queen Automatic Turret', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Gunner', id: '59DE', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Schütze Der Königin', id: '59DE', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Fusilier De La Reine', id: '59DE', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ガンナー', id: '59DE', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王枪手', id: '59DE', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 총사', id: '59DE', capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Avoid Laser Bounces', de: 'Weiche den abgelenken Lasern aus', fr: 'Évitez les rebonds de laser', ja: 'レーザーを避ける', cn: '躲避激光', ko: '레이저 피하기', }, }, }, { id: 'Delubrum Queen Reversal Of Forces', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Warrior', id: '59D4', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegerin Der Königin', id: '59D4', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Guerrière De La Reine', id: '59D4', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ウォリアー', id: '59D4', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王战士', id: '59D4', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 전사', id: '59D4', capture: false }), run: (data) => data.reversalOfForces = true, }, { // Called during the knockback cast itself, not during the 59C6 Heaven's Wrath // where the knockback line appears. This is mostly because we don't know about // reversal at that point. id: 'Delubrum Queen Heaven\'s Wrath', type: 'StartsUsing', // This is used sometimes by The Queen and sometimes by The Queen's Gunner (?!). // This could just be stale parser data though, as the name changes for the actual usage. netRegex: NetRegexes.startsUsing({ id: '59C7', capture: false }), netRegexDe: NetRegexes.startsUsing({ id: '59C7', capture: false }), netRegexFr: NetRegexes.startsUsing({ id: '59C7', capture: false }), netRegexJa: NetRegexes.startsUsing({ id: '59C7', capture: false }), netRegexCn: NetRegexes.startsUsing({ id: '59C7', capture: false }), alertText: (data, _matches, output) => { if (!data.seenHeavensWrath) return output.getKnockedTowardsMiddle!(); if (data.reversalOfForces) return output.getKnockedToSmallBomb!(); return output.getKnockedToLargeBomb!(); }, run: (data) => { data.seenHeavensWrath = true; delete data.reversalOfForces; }, outputStrings: { getKnockedTowardsMiddle: { en: 'Get Knocked Towards Middle', de: 'Zur Mitte zurückstoßen lassen', fr: 'Faites-vous pousser vers le milieu', ja: '中へ吹き飛ばされる', cn: '击退到中间', ko: '중앙에서 넉백 당하기', }, getKnockedToSmallBomb: { en: 'Get Knocked To Small Bomb', de: 'Zu kleinen Bomben zurückstoßen lassen', fr: 'Faites-vous pousser sur une petite bombe', ja: '小さい爆弾へ吹き飛ばされる', cn: '击退到小炸弹', ko: '작은 폭탄으로 넉백당하기', }, getKnockedToLargeBomb: { en: 'Get Knocked To Large Bomb', de: 'Zu großen Bomben zurückstoßen lassen', fr: 'Faites-vous pousser sur une grosse bombe', ja: '大きい爆弾へ吹き飛ばされる', cn: '击退到大炸弹', ko: '큰 폭탄으로 넉백당하기', }, }, }, { id: 'Delubrum Queen Judgment Blade Right', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C2', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C2', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C2', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C2', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C2', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C2', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Find Charge, Dodge Right', de: 'Halte nach dem Ansturm ausschau, weiche nach rechts aus', fr: 'Repérez la charge, esquivez à droite', ja: '右へ、突進を避ける', cn: '去右侧躲避冲锋', ko: '돌진 찾고, 오른쪽 피하기', }, }, }, { id: 'Delubrum Queen Judgment Blade Left', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C1', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C1', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C1', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C1', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C1', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C1', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Find Charge, Dodge Left', de: 'Halte nach dem Ansturm ausschau, weiche nach links aus', fr: 'Repérez la charge, esquivez à gauche', ja: '左へ、突進を避ける', cn: '去左侧躲避冲锋', ko: '돌진 찾고, 왼쪽 피하기', }, }, }, { id: 'Delubrum Queen Gods Save The Queen', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Queen', id: '59C9', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Kriegsgöttin', id: '59C9', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Garde-La-Reine', id: '59C9', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'セイブ・ザ・クイーン', id: '59C9', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '天佑女王', id: '59C9', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '세이브 더 퀸', id: '59C9', capture: false }), response: Responses.aoe(), }, { id: 'Delubrum Queen Secrets Revealed', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Soldier', id: '5B8A', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Soldat Der Königin', id: '5B8A', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Soldat De La Reine', id: '5B8A', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ソルジャー', id: '5B8A', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王士兵', id: '5B8A', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 병사', id: '5B8A', capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Away from tethered adds', de: 'Weg von verbundenen Adds', fr: 'Éloignez-vous des adds liés', ja: '線に繋がる雑魚から離れる', cn: '远离连线小怪', ko: '선 연결된 쫄 피하기', }, }, }, { id: 'Delubrum Queen Shield Omen', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '59CB', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '59CB', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '59CB', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '59CB', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '59CB', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '59CB', capture: false }), delaySeconds: 2.5, response: Responses.getUnder('alarm'), }, { id: 'Delubrum Queen Sword Omen', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Queen\'s Knight', id: '59CA', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Ritter Der Königin', id: '59CA', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Chevalier De La Reine', id: '59CA', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'クイーンズ・ナイト', id: '59CA', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '女王骑士', id: '59CA', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '여왕의 기사', id: '59CA', capture: false }), delaySeconds: 2.5, response: Responses.getOut(), }, ], timelineReplace: [ { 'locale': 'en', 'replaceText': { 'Right-Sided Shockwave/Left-Sided Shockwave': 'Right/Left Shockwave', 'Left-Sided Shockwave/Right-Sided Shockwave': 'Left/Right Shockwave', 'Sword Omen/Shield Omen': 'Sword/Shield Omen', 'Shield Omen/Sword Omen': 'Shield/Sword Omen', }, }, { 'locale': 'de', 'replaceSync': { 'Seeker Avatar': 'Spaltteil Der Sucher', 'Aetherial Bolt': 'Magiegeschoss', 'Aetherial Burst': 'Magiebombe', 'Aetherial Orb': 'Magiekugel', 'Aetherial Ward': 'Magiewall', 'Automatic Turret': 'Selbstschuss-Gyrocopter', 'Avowed Avatar': 'Spaltteil der Eingeschworenen', 'Blazing Orb': 'Feuerball', 'Bozjan Phantom': 'Bozja-Phantom', 'Dahu': 'Dahu', 'Frost Arrow': 'Frostpfeil', 'Marchosias': 'Marchosias', 'Pride of the Lion': 'Saal des Löwen', 'Queen\'s Gunner': 'Schütze der Königin', 'Queen\'s Knight': 'Ritter der Königin', 'Queen\'s Soldier': 'Soldat der Königin', 'Queen\'s Warrior': 'Kriegerin der Königin', 'Queensheart': 'Saal der Dienerinnen', 'Soldier Avatar': 'Spaltteil des Soldaten', 'Stuffy Wraith': 'muffig(?:e|er|es|en) Schrecken', 'Swirling Orb': 'Eisball', 'Tempestuous Orb': 'groß(?:e|er|es|en) Eisball', 'The Hall of Hieromancy': 'Halle des Orakels', 'The Hall of Supplication': 'Große Gebetshalle', 'The Queen': 'Kriegsgöttin', 'The Theater of One': 'Einsame Arena', 'The Vault of Singing Crystal': 'Ort des Klingenden Kristalls', 'Trinity Avowed': 'Trinität der Eingeschworenen', 'Trinity Seeker': 'Trinität der Sucher', }, 'replaceText': { '--explosion--': '--Explosion--', '--stunned--': '--betäubt--', '--unstunned--': '--nicht länger betäubt--', 'Above Board': 'Über dem Feld', 'Act Of Mercy': 'Schneller Stich des Dolches', 'Allegiant Arsenal': 'Waffenwechsel', 'Automatic Turret': 'Selbstschuss-Gyrocopter', 'Baleful Blade': 'Stoß der Edelklinge', 'Baleful Swathe': 'Schwarzer Wirbel der Edelklinge', 'Beck And Call To Arms': 'Feuerbefehl', 'Blade Of Entropy': 'Eisflammenklinge', 'Blood And Bone': 'Wellenschlag', 'Bombslinger': 'Bombenabwurf', 'Cleansing Slash': 'Säubernder Schnitt', 'Coat Of Arms': 'Trotz', 'Creeping Miasma': 'Miasmahauch', 'Dead Iron': 'Woge der Feuerfaust', 'Double Gambit': 'Illusionsmagie', 'Elemental Arrow': 'Element-Pfeil', 'Elemental Blast': 'Element-Explosion', 'Elemental Impact': 'Einschlag', 'Empyrean Iniquity': 'Empyreische Interdiktion', 'Excruciation': 'Fürchterlicher Schmerz', 'Feral Howl': 'Wildes Heulen', 'Firebreathe': 'Lava-Atem', 'First Mercy': '1. Streich: Viererdolch-Haltung', 'Flames Of Bozja': 'Bozianische Flamme', 'Flashvane': 'Schockpfeile', 'Fourth Mercy': '4. Streich: Viererdolch-Haltung', 'Freedom Of Bozja': 'Bozianische Freiheit', 'Fury Of Bozja': 'Bozianische Wut', 'Gleaming Arrow': 'Funkelnder Pfeil', 'Glory Of Bozja': 'Stolz von Bozja', 'Gods Save The Queen': 'Wächtergott der Königin', 'Head Down': 'Scharrende Hufe', 'Heat Breath': 'Hitzeatem', 'Heated Blast': 'Hitzekugel', 'Heaven\'s Wrath': 'Heilige Perforation', 'Hot And Cold': 'Heiß und kalt', 'Hot Charge': 'Heiße Rage', 'Hunter\'s Claw': 'Jägerklaue', 'Infernal Slash': 'Yama-Schnitt', 'Iron Impact': 'Kanon der Feuerfaust', 'Iron Splitter': 'Furor der Feuerfaust', 'Judgment Blade': 'Klinge des Urteils', 'Left-Sided Shockwave': 'Linke Schockwelle', 'Lots Cast': 'Magieexplosion', 'Malediction Of Agony': 'Pochender Fluch', 'Manipulate Miasma': 'Miasmakontrolle', 'Merciful Arc': 'Fächertanz des Dolches', 'Merciful Blooms': 'Kasha des Dolches', 'Merciful Breeze': 'Yukikaze des Dolches', 'Merciful Moon': 'Gekko des Dolches', 'Mercy Fourfold': 'Viererdolch', 'Northswain\'s Glow': 'Stella Polaris', 'Optimal Play': 'Bestes Manöver', 'Pawn Off': 'Kranzklinge', 'Phantom Edge': 'Phantomklingen', 'Queen\'s Edict': 'Hohes Edikt der Königin', 'Queen\'s Justice': 'Hoheitliche Strafe', 'Queen\'s Shot': 'Omnidirektionalschuss', 'Queen\'s Will': 'Edikt der Königin', 'Rapid Sever': 'Radikale Abtrennung', 'Relentless Play': 'Koordinierter Angriff', 'Reverberating Roar': 'Sturzimpuls', 'Reversal Of Forces': 'Materieinversion', 'Right-Sided Shockwave': 'Rechte Schockwelle', 'Seasons Of Mercy': 'Setsugekka des Dolches', 'Second Mercy': '2. Streich: Viererdolch-Haltung', 'Secrets Revealed': 'Enthüllte Geheimnisse', 'Shield Omen': 'Schildhaltung', 'Shimmering Shot': 'Glitzerpfeil', 'Shot In The Dark': 'Einhändiger Schuss', 'Strongpoint Defense': 'Widerstand', 'Summon': 'Beschwörung', 'Swirling Miasma': 'Miasmawirbel', 'Sword Omen': 'Schwerthaltung', 'Tail Swing': 'Schwanzfeger', 'The Ends': 'Kreuzschnitt', 'The Means': 'Kreuzschlag', 'Third Mercy': '3. Streich: Viererdolch-Haltung', 'Transference': 'Transfer', 'Turret\'s Tour': 'Querschlägerhagel', 'Undying Hatred': 'Über-Psychokinese', 'Unseen Eye': 'Geist des Blütensturms', 'Verdant Path': 'Lehren des Grünen Pfades', 'Verdant Tempest': 'Zauberwind des Grünen Pfades', 'Vile Wave': 'Welle der Boshaftigkeit', 'Weave Miasma': 'Miasmathese', 'Wrath Of Bozja': 'Bozianischer Zorn', }, }, { 'locale': 'fr', 'replaceSync': { 'Seeker Avatar': 'Clone De La Trinité Soudée', 'Aetherial Bolt': 'petite bombe', 'Aetherial Burst': 'énorme bombe', 'Aetherial Orb': 'amas d\'éther élémentaire', 'Aetherial Ward': 'Barrière magique', 'Automatic Turret': 'Auto-tourelle', 'Avowed Avatar': 'clone de la trinité féale', 'Blazing Orb': 'boule de feu', 'Bozjan Phantom': 'fantôme bozjien', 'Dahu': 'dahu', 'Frost Arrow': 'volée de flèches de glace', 'Marchosias': 'marchosias', 'Pride of the Lion': 'Hall du Lion', 'Queen\'s Gunner': 'fusilier de la reine', 'Queen\'s Knight': 'chevalier de la reine', 'Queen\'s Soldier': 'soldat de la reine', 'Queen\'s Warrior': 'guerrière de la reine', 'Queensheart': 'Chambre des prêtresses', 'Soldier Avatar': 'double de soldat', 'Stuffy Wraith': 'spectre boursouflé', 'Swirling Orb': 'boule de glace', 'Tempestuous Orb': 'grande boule de glace', 'The Hall of Hieromancy': 'Salle des oracles', 'The Hall of Supplication': 'Grande salle des prières', 'The Queen': 'Garde-la-Reine', 'The Theater of One': 'Amphithéâtre en ruines', 'The Vault of Singing Crystal': 'Chambre des cristaux chantants', 'Trinity Avowed': 'trinité féale', 'Trinity Seeker': 'trinité soudée', }, 'replaceText': { '\\?': ' ?', '--explosion--': '--explosion--', '--stunned--': '--étourdi(e)--', '--unstunned--': '--non étourdi(e)--', 'Above Board': 'Aire de flottement', 'Act Of Mercy': 'Fendreciel rédempteur', 'Allegiant Arsenal': 'Changement d\'arme', 'Automatic Turret': 'Auto-tourelle', 'Baleful Blade': 'Assaut singulier', 'Baleful Swathe': 'Flux de noirceur singulier', 'Beck And Call To Arms': 'Ordre d\'attaquer', 'Blade Of Entropy': 'Sabre du feu et de la glace', 'Blood And Bone': 'Onde tranchante', 'Bombslinger': 'Jet de bombe', 'Cleansing Slash': 'Taillade purifiante', 'Coat Of Arms': 'Bouclier directionnel', 'Creeping Miasma': 'Coulée miasmatique', 'Dead Iron': 'Vague des poings de feu', 'Double Gambit': 'Manipulation des ombres', 'Elemental Arrow': 'Flèche élémentaire', 'Elemental Blast': 'Explosion élémentaire', 'Elemental Impact': 'Impact', 'Empyrean Iniquity': 'Injustice empyréenne', 'Excruciation': 'Atroce douleur', 'Feral Howl': 'Rugissement sauvage', 'Firebreathe': 'Souffle de lave', 'First Mercy': 'Première lame rédemptrice', 'Flames Of Bozja': 'Flammes de Bozja', 'Flashvane': 'Flèches fulgurantes', 'Fourth Mercy': 'Quatrième lame rédemptrice', 'Freedom Of Bozja': 'Liberté de Bozja', 'Fury Of Bozja': 'Furie de Bozja', 'Gleaming Arrow': 'Flèche miroitante', 'Glory Of Bozja': 'Gloire de Bozja', 'Gods Save The Queen': 'Que les Dieux gardent la Reine', 'Head Down': 'Charge bestiale', 'Heat Breath': 'Souffle brûlant', 'Heated Blast': 'Déflagration de feu', 'Heaven\'s Wrath': 'Ire céleste', 'Hot And Cold': 'Chaud et froid', 'Hot Charge': 'Charge brûlante', 'Hunter\'s Claw': 'Griffes prédatrices', 'Infernal Slash': 'Taillade de Yama', 'Iron Impact': 'Canon d\'ardeur des poings de feu', 'Iron Splitter': 'Fracas des poings de feu', 'Judgment Blade': 'Lame du jugement', 'Left-Sided Shockwave/Right-Sided Shockwave': 'Onde de choc gauche/droite', 'Lots Cast': 'Bombe ensorcelée', 'Malediction Of Agony': 'Malédiction lancinante', 'Manipulate Miasma': 'Contrôle des miasmes', 'Merciful Arc': 'Éventail rédempteur', 'Merciful Blooms': 'Kasha rédempteur', 'Merciful Breeze': 'Yukikaze rédempteur', 'Merciful Moon': 'Gekkô rédempteur', 'Mercy Fourfold': 'Quatuor de lames rédemptrices', 'Northswain\'s Glow': 'Étoile du Nord', 'Optimal Play': 'Technique de maître d\'armes', 'Pawn Off': 'Sabre tournoyant', 'Phantom Edge': 'Épées spectrales', 'Queen\'s Edict': 'Injonction de Gunnhildr', 'Queen\'s Justice': 'Châtiment royal', 'Queen\'s Shot': 'Tir tous azimuts', 'Queen\'s Will': 'Édit de Gunnhildr', 'Rapid Sever': 'Tranchage rapide', 'Relentless Play': 'Ordre d\'attaque coordonnée', 'Reverberating Roar': 'Cri disloquant', 'Reversal Of Forces': 'Inversion des masses', 'Right-Sided Shockwave/Left-Sided Shockwave': 'Onde de choc droite/gauche', 'Seasons Of Mercy': 'Setsugekka rédempteur', 'Second Mercy': 'Deuxième lame rédemptrice', 'Secrets Revealed': 'Corporification', 'Shield Omen/Sword Omen': 'Posture du bouclier/épée', 'Shimmering Shot': 'Flèches scintillantes', 'Shot In The Dark': 'Tir à une main', 'Strongpoint Defense': 'Défense absolue', 'Summon': 'Invocation', 'Swirling Miasma': 'Anneau miasmatique', 'Sword Omen/Shield Omen': 'Posture de l\'épée/bouclier', 'Tail Swing': 'Queue balayante', 'The Ends': 'Croix lacérante', 'The Means': 'Croix perforante', 'Third Mercy': 'Troisième lame rédemptrice', 'Transference': 'Transfert', 'Turret\'s Tour': 'Ricochets frénétiques', 'Undying Hatred': 'Psychokinèse', 'Unseen Eye': 'Spectres de l\'ouragan de fleurs', 'Verdant Path': 'École de la Voie verdoyante', 'Verdant Tempest': 'Tempête de la Voie verdoyante', 'Vile Wave': 'Vague de malveillance', 'Weave Miasma': 'Miasmologie', 'Wrath Of Bozja': 'Courroux de Bozja', }, }, { 'locale': 'ja', 'replaceSync': { 'Seeker Avatar': 'シーカーの分体', 'Aetherial Bolt': '魔弾', 'Aetherial Burst': '大魔弾', 'Aetherial Orb': '魔力塊', 'Aetherial Ward': '魔法障壁', 'Automatic Turret': 'オートタレット', 'Avowed Avatar': 'アヴァウドの分体', 'Blazing Orb': '炎球', 'Bozjan Phantom': 'ボズヤ・ファントム', 'Dahu': 'ダウー', 'Frost Arrow': 'フロストアロー', 'Marchosias': 'マルコシアス', 'Pride of the Lion': '雄獅子の広間', 'Queen\'s Gunner': 'クイーンズ・ガンナー', 'Queen\'s Knight': 'クイーンズ・ナイト', 'Queen\'s Soldier': 'クイーンズ・ソルジャー', 'Queen\'s Warrior': 'クイーンズ・ウォリアー', 'Queensheart': '巫女たちの広間', 'Soldier Avatar': 'ソルジャーの分体', 'Stuffy Wraith': 'スタフィー・レイス', 'Swirling Orb': '氷球', 'Tempestuous Orb': '大氷球', 'The Hall of Hieromancy': '託宣所', 'The Hall of Supplication': '大祈祷所', 'The Queen': 'セイブ・ザ・クイーン', 'The Theater of One': '円形劇場跡', 'The Vault of Singing Crystal': '響き合う水晶の間', 'Trinity Avowed': 'トリニティ・アヴァウド', 'Trinity Seeker': 'トリニティ・シーカー', }, 'replaceText': { '--explosion--': '--爆発--', '--stunned--': '--スタンされる--', '--unstunned--': '--スタンされない--', 'Above Board': '浮遊波', 'Act Of Mercy': '破天鋭刃風', 'Allegiant Arsenal': 'ウェポンチェンジ', 'Automatic Turret': 'オートタレット', 'Baleful Blade': '豪剣強襲撃', 'Baleful Swathe': '豪剣黒流破', 'Beck And Call To Arms': '攻撃命令', 'Blade Of Entropy': '氷炎刃', 'Blood And Bone': '波動斬', 'Bombslinger': '爆弾投擲', 'Cleansing Slash': '乱命割殺斬', 'Coat Of Arms': '偏向防御', 'Creeping Miasma': '瘴気流', 'Dead Iron': '熱拳振動波', 'Double Gambit': '幻影術', 'Elemental Arrow': '熱/凍気矢', 'Elemental Blast': '熱/凍気弾', 'Elemental Impact': '着弾', 'Empyrean Iniquity': '天魔鬼神爆', 'Excruciation': '激痛', 'Feral Howl': 'フェラルハウル', 'Firebreathe': 'ラーヴァブレス', 'First Mercy': '初手:鋭刃四刀の構え', 'Flames Of Bozja': 'フレイム・オブ・ボズヤ', 'Flashvane': 'フラッシュアロー', 'Fourth Mercy': '四手:鋭刃四刀の構え', 'Freedom Of Bozja': 'リバティ・オブ・ボズヤ', 'Fury Of Bozja': 'フューリー・オブ・ボズヤ', 'Gleaming Arrow': 'グリッターアロー', 'Glory Of Bozja': 'グローリー・オブ・ボズヤ', 'Gods Save The Queen': 'ゴッド・セイブ・ザ・クイーン', 'Head Down': 'ビーストチャージ', 'Heat Breath': '火炎の息', 'Heated Blast': '熱気弾', 'Heaven\'s Wrath': '聖光爆裂斬', 'Hot And Cold': '氷炎乱流', 'Hot Charge': 'ホットチャージ', 'Hunter\'s Claw': 'ハンタークロウ', 'Infernal Slash': 'ヤーマスラッシュ', 'Iron Impact': '熱拳烈気砲', 'Iron Splitter': '熱拳地脈爆', 'Judgment Blade': '不動無明剣', 'Left-Sided Shockwave': 'レフトサイド・ショックウェーブ', 'Lots Cast': '魔爆発', 'Malediction Of Agony': '苦悶の呪詛', 'Manipulate Miasma': '瘴気操作', 'Merciful Arc': '鋭刃舞踏扇', 'Merciful Blooms': '鋭刃花車', 'Merciful Breeze': '鋭刃雪風', 'Merciful Moon': '鋭刃月光', 'Mercy Fourfold': '鋭刃四刀流', 'Northswain\'s Glow': '北斗骨砕斬', 'Optimal Play': '武装戦技', 'Pawn Off': '旋回刃', 'Phantom Edge': '霊幻剣', 'Queen\'s Edict': '女王の大勅令', 'Queen\'s Justice': '処罰令', 'Queen\'s Shot': '全方位射撃', 'Queen\'s Will': '女王の勅令', 'Rapid Sever': '滅多斬り', 'Relentless Play': '連携命令', 'Reverberating Roar': '崩落誘発', 'Reversal Of Forces': '質量転換', 'Right-Sided Shockwave': 'ライトサイド・ショックウェーブ', 'Seasons Of Mercy': '鋭刃雪月花', 'Second Mercy': '二手:鋭刃四刀の構え', 'Secrets Revealed': '実体結像', 'Shield Omen': '盾の型', 'Shimmering Shot': 'トゥインクルアロー', 'Shot In The Dark': '片手撃ち', 'Strongpoint Defense': '絶対防御', 'Summon': '召喚', 'Swirling Miasma': '瘴気輪', 'Sword Omen': '剣の型', 'Tail Swing': 'テールスイング', 'The Ends': '十字斬', 'The Means': '十字撃', 'Third Mercy': '三手:鋭刃四刀の構え', 'Transference': '転移', 'Turret\'s Tour': '跳弾乱舞', 'Undying Hatred': '超ねんりき', 'Unseen Eye': '花嵐の幻影', 'Verdant Path': '翠流派', 'Verdant Tempest': '翠流魔風塵', 'Vile Wave': '悪意の波動', 'Weave Miasma': '瘴気術', 'Wrath Of Bozja': 'ラース・オブ・ボズヤ', }, }, { 'locale': 'cn', 'replaceSync': { 'Seeker Avatar': '求道之分身', 'Aetherial Bolt': '魔弹', 'Aetherial Burst': '大魔弹', 'Aetherial Orb': '魔力块', 'Aetherial Ward': '魔法障壁', 'Automatic Turret': '自动炮塔', 'Avowed Avatar': '誓约之分身', 'Blazing Orb': '火球', 'Bozjan Phantom': '博兹雅幻灵', 'Dahu': '大兀', 'Frost Arrow': '寒霜箭', 'Marchosias': '马可西亚斯', 'Pride of the Lion': '雄狮大厅', 'Queen\'s Gunner': '女王枪手', 'Queen\'s Knight': '女王骑士', 'Queen\'s Soldier': '女王士兵', 'Queen\'s Warrior': '女王战士', 'Queensheart': '巫女大厅', 'Soldier Avatar': '士兵的分身', 'Stuffy Wraith': '沉闷幽灵', 'Swirling Orb': '冰球', 'Tempestuous Orb': '大冰球', 'The Hall of Hieromancy': '神谕所', 'The Hall of Supplication': '大祈祷所', 'The Queen': '天佑女王', 'The Theater of One': '圆形剧场遗迹', 'The Vault of Singing Crystal': '和鸣水晶之间', 'Trinity Avowed': '誓约之三位一体', 'Trinity Seeker': '求道之三位一体', }, 'replaceText': { '--explosion--': '--爆炸--', '--stunned--': '--眩晕--', '--unstunned--': '--眩晕结束--', 'Above Board': '浮游波', 'Act Of Mercy': '破天慈刃风', 'Allegiant Arsenal': '变换武器', 'Automatic Turret': '自动炮塔', 'Baleful Blade': '豪剑强袭击', 'Baleful Swathe': '豪剑黑流破', 'Beck And Call To Arms': '攻击命令', 'Blade Of Entropy': '冰炎刃', 'Blood And Bone': '波动斩', 'Bombslinger': '投掷炸弹', 'Cleansing Slash': '乱命割杀斩', 'Coat Of Arms': '偏向防御', 'Creeping Miasma': '瘴气流', 'Dead Iron': '热拳振动波', 'Double Gambit': '幻影术', 'Elemental Arrow': '元素箭', 'Elemental Blast': '元素爆破', 'Elemental Impact': '中弹', 'Empyrean Iniquity': '天魔鬼神爆', 'Excruciation': '剧痛', 'Feral Howl': '野性嚎叫', 'Firebreathe': '岩浆吐息', 'First Mercy': '慈悲四刀第一念', 'Flames Of Bozja': '博兹雅火焰', 'Flashvane': '闪光箭', 'Fourth Mercy': '慈悲四刀第四念', 'Freedom Of Bozja': '博兹雅之自由', 'Fury Of Bozja': '博兹雅之怒', 'Gleaming Arrow': '闪耀箭', 'Glory Of Bozja': '博兹雅之荣', 'Gods Save The Queen': '神佑女王', 'Head Down': '兽性冲击', 'Heat Breath': '灼热吐息', 'Heated Blast': '热浪弹', 'Heaven\'s Wrath': '圣光爆裂斩', 'Hot And Cold': '冰炎乱流', 'Hot Charge': '炽热冲锋', 'Hunter\'s Claw': '狩猎者之爪', 'Infernal Slash': '地狱斩', 'Iron Impact': '热拳烈气炮', 'Iron Splitter': '热拳地脉爆', 'Judgment Blade': '不动无明剑', 'Left-Sided Shockwave': '左侧震荡波', 'Lots Cast': '魔爆炸', 'Malediction Of Agony': '苦闷的诅咒', 'Manipulate Miasma': '操作瘴气', 'Merciful Arc': '慈悲舞动扇', 'Merciful Blooms': '慈悲花车', 'Merciful Breeze': '慈悲雪风', 'Merciful Moon': '慈悲月光', 'Mercy Fourfold': '慈悲四刀流', 'Northswain\'s Glow': '北斗骨碎斩', 'Optimal Play': '武装战技', 'Pawn Off': '旋回刃', 'Phantom Edge': '灵幻剑', 'Queen\'s Edict': '女王的大敕令', 'Queen\'s Justice': '处罚令', 'Queen\'s Shot': '全方位射击', 'Queen\'s Will': '女王的敕令', 'Rapid Sever': '急促斩击', 'Relentless Play': '协作指令', 'Reverberating Roar': '引发崩塌', 'Reversal Of Forces': '质量转换', 'Right-Sided Shockwave': '右侧震荡波', 'Seasons Of Mercy': '慈悲雪月花', 'Second Mercy': '慈悲四刀第二念', 'Secrets Revealed': '实体成像', 'Shield Omen': '盾型', 'Shimmering Shot': '闪烁箭', 'Shot In The Dark': '单手射击', 'Strongpoint Defense': '绝对防御', 'Summon': '召唤', 'Swirling Miasma': '瘴气圈', 'Sword Omen': '剑型', 'Tail Swing': '回旋尾', 'The Ends': '十字斩', 'The Means': '十字击', 'Third Mercy': '慈悲四刀第三念', 'Transference': '转移', 'Turret\'s Tour': '跳弹乱舞', 'Undying Hatred': '超念力', 'Unseen Eye': '风花舞的幻影', 'Verdant Path': '翠青流', 'Verdant Tempest': '翠青魔风尘', 'Vile Wave': '恶意的波动', 'Weave Miasma': '瘴气术', 'Wrath Of Bozja': '博兹雅之愤', }, }, { 'locale': 'ko', 'replaceSync': { 'Seeker Avatar': '탐구의 분열체', 'Aetherial Bolt': '마탄', 'Aetherial Burst': '대마탄', 'Aetherial Orb': '마력 덩어리', 'Aetherial Ward': '마법 장벽', 'Automatic Turret': '자동포탑', 'Avowed Avatar': '맹세의 분열체', 'Blazing Orb': '화염 구체', 'Bozjan Phantom': '보즈야 유령', 'Dahu': '다후', 'Frost Arrow': '서리 화살', 'Marchosias': '마르코시아스', 'Pride of the Lion': '수사자의 방', 'Queen\'s Gunner': '여왕의 총사', 'Queen\'s Knight': '여왕의 기사', 'Queen\'s Soldier': '여왕의 병사', 'Queen\'s Warrior': '여왕의 전사', 'Queensheart': '무녀들의 방', 'Soldier Avatar': '병사 분열체', 'Stuffy Wraith': '케케묵은 망령', 'Swirling Orb': '얼음 구체', 'Tempestuous Orb': '거대 얼음 구체', 'The Hall of Hieromancy': '신탁소', 'The Hall of Supplication': '대기도소', 'The Queen': '세이브 더 퀸', 'The Theater of One': '원형 극장 옛터', 'The Vault of Singing Crystal': '공명하는 수정의 방', 'Trinity Avowed': '맹세의 삼위일체', 'Trinity Seeker': '탐구의 삼위일체', }, 'replaceText': { '--explosion--': '--폭발--', '--stunned--': '--기절--', '--unstunned--': '--기절풀림--', 'Above Board': '부유파', 'Act Of Mercy': '예리한 파천풍', 'Allegiant Arsenal': '무기 변경', 'Automatic Turret': '자동포탑', 'Baleful Blade': '호검 강습 공격', 'Baleful Swathe': '호검 흑류파', 'Beck And Call To Arms': '공격 명령', 'Blade Of Entropy': '얼음불 칼날', 'Blood And Bone': '파동참', 'Bombslinger': '폭탄 투척', 'Cleansing Slash': '난명할살참', 'Coat Of Arms': '편향 방어', 'Creeping Miasma': '독기 흐름', 'Dead Iron': '불주먹 진동파', 'Double Gambit': '환영술', 'Elemental Arrow': '속성 화살', 'Elemental Blast': '속성 운석 폭발', 'Elemental Impact': '착탄', 'Empyrean Iniquity': '천마귀신폭', 'Excruciation': '격통', 'Feral Howl': '야성의 포효', 'Firebreathe': '용암숨', 'First Mercy': '예리한 첫 번째 검', 'Flames Of Bozja': '보즈야 플레임', 'Flashvane': '섬광 화살', 'Fourth Mercy': '예리한 네 번째 검', 'Freedom Of Bozja': '보즈야의 자유', 'Fury Of Bozja': '보즈야의 분노', 'Gleaming Arrow': '현란한 화살', 'Glory Of Bozja': '보즈야의 영광', 'Gods Save The Queen': '갓 세이브 더 퀸', 'Head Down': '야수 돌격', 'Heat Breath': '화염의 숨결', 'Heated Blast': '열기탄', 'Heaven\'s Wrath': '성광폭렬참', 'Hot And Cold': '빙염난류', 'Hot Charge': '맹렬한 돌진', 'Hunter\'s Claw': '사냥꾼의 발톱', 'Infernal Slash': '연옥 베기', 'Iron Impact': '불주먹 열기포', 'Iron Splitter': '불주먹 지맥 폭발', 'Judgment Blade': '부동무명검', 'Left-Sided Shockwave': '왼쪽 충격파', 'Lots Cast': '마폭발', 'Malediction Of Agony': '고통의 저주', 'Manipulate Miasma': '독기 조작', 'Merciful Arc': '예리한 부채검', 'Merciful Blooms': '예리한 화차', 'Merciful Breeze': '예리한 설풍', 'Merciful Moon': '예리한 월광', 'Mercy Fourfold': '예리한 사도류', 'Northswain\'s Glow': '북두골쇄참', 'Optimal Play': '무장 전술', 'Pawn Off': '선회인', 'Phantom Edge': '영환검', 'Queen\'s Edict': '여왕의 대칙령', 'Queen\'s Justice': '처벌령', 'Queen\'s Shot': '전방위 사격', 'Queen\'s Will': '여왕의 칙령', 'Rapid Sever': '마구 베기', 'Relentless Play': '연계 명령', 'Reverberating Roar': '낙석 유발', 'Reversal Of Forces': '질량 전환', 'Right-Sided Shockwave': '오른쪽 충격파', 'Seasons Of Mercy': '예리한 설월화', 'Second Mercy': '예리한 두 번째 검', 'Secrets Revealed': '실체 이루기', 'Shield Omen': '방패 태세', 'Shimmering Shot': '반짝반짝 화살', 'Shot In The Dark': '한손 쏘기', 'Strongpoint Defense': '절대 방어', 'Summon': '소환', 'Swirling Miasma': '독기 고리', 'Sword Omen': '검 태세', 'Tail Swing': '꼬리 휘두르기', 'The Ends': '십자참', 'The Means': '십자격', 'Third Mercy': '예리한 세 번째 검', 'Transference': '전이', 'Turret\'s Tour': '도탄난무', 'Undying Hatred': '초염력', 'Unseen Eye': '꽃폭풍의 환영', 'Verdant Path': '취일문 유파', 'Verdant Tempest': '취일문 마풍진', 'Vile Wave': '악의의 파동', 'Weave Miasma': '독기술', 'Wrath Of Bozja': '보즈야의 격노', }, }, ], }; export default triggerSet;
the_stack
import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager"; import { WebXRSessionManager } from "../webXRSessionManager"; import { Observable } from "../../Misc/observable"; import { Vector3, Matrix, Quaternion } from "../../Maths/math.vector"; import { WebXRAbstractFeature } from "./WebXRAbstractFeature"; import { IWebXRLegacyHitTestOptions, IWebXRLegacyHitResult, IWebXRHitTestFeature } from "./WebXRHitTestLegacy"; import { Tools } from "../../Misc/tools"; import { Nullable } from "../../types"; /** * Options used for hit testing (version 2) */ export interface IWebXRHitTestOptions extends IWebXRLegacyHitTestOptions { /** * Do not create a permanent hit test. Will usually be used when only * transient inputs are needed. */ disablePermanentHitTest?: boolean; /** * Enable transient (for example touch-based) hit test inspections */ enableTransientHitTest?: boolean; /** * Override the default transient hit test profile (generic-touchscreen). */ transientHitTestProfile?: string; /** * Offset ray for the permanent hit test */ offsetRay?: Vector3; /** * Offset ray for the transient hit test */ transientOffsetRay?: Vector3; /** * Instead of using viewer space for hit tests, use the reference space defined in the session manager */ useReferenceSpace?: boolean; /** * Override the default entity type(s) of the hit-test result */ entityTypes?: XRHitTestTrackableType[]; } /** * Interface defining the babylon result of hit-test */ export interface IWebXRHitResult extends IWebXRLegacyHitResult { /** * The input source that generated this hit test (if transient) */ inputSource?: XRInputSource; /** * Is this a transient hit test */ isTransient?: boolean; /** * Position of the hit test result */ position: Vector3; /** * Rotation of the hit test result */ rotationQuaternion: Quaternion; /** * The native hit test result */ xrHitResult: XRHitTestResult; } /** * The currently-working hit-test module. * Hit test (or Ray-casting) is used to interact with the real world. * For further information read here - https://github.com/immersive-web/hit-test * * Tested on chrome (mobile) 80. */ export class WebXRHitTest extends WebXRAbstractFeature implements IWebXRHitTestFeature<IWebXRHitResult> { private _tmpMat: Matrix = new Matrix(); private _tmpPos: Vector3 = new Vector3(); private _tmpQuat: Quaternion = new Quaternion(); private _transientXrHitTestSource: Nullable<XRTransientInputHitTestSource>; // in XR space z-forward is negative private _xrHitTestSource: Nullable<XRHitTestSource>; private initHitTestSource = (referenceSpace: XRReferenceSpace) => { if (!referenceSpace) { return; } const offsetRay = new XRRay(this.options.offsetRay || {}); const hitTestOptions: XRHitTestOptionsInit = { space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace, offsetRay: offsetRay, }; if (this.options.entityTypes) { hitTestOptions.entityTypes = this.options.entityTypes; } if (!hitTestOptions.space) { Tools.Warn("waiting for viewer reference space to initialize"); return; } this._xrSessionManager.session.requestHitTestSource!(hitTestOptions).then((hitTestSource) => { if (this._xrHitTestSource) { this._xrHitTestSource.cancel(); } this._xrHitTestSource = hitTestSource; }); }; /** * The module's name */ public static readonly Name = WebXRFeatureName.HIT_TEST; /** * The (Babylon) version of this module. * This is an integer representing the implementation version. * This number does not correspond to the WebXR specs version */ public static readonly Version = 2; /** * When set to true, each hit test will have its own position/rotation objects * When set to false, position and rotation objects will be reused for each hit test. It is expected that * the developers will clone them or copy them as they see fit. */ public autoCloneTransformation: boolean = false; /** * Triggered when new babylon (transformed) hit test results are available * Note - this will be called when results come back from the device. It can be an empty array!! */ public onHitTestResultObservable: Observable<IWebXRHitResult[]> = new Observable(); /** * Use this to temporarily pause hit test checks. */ public paused: boolean = false; /** * Creates a new instance of the hit test feature * @param _xrSessionManager an instance of WebXRSessionManager * @param options options to use when constructing this feature */ constructor( _xrSessionManager: WebXRSessionManager, /** * options to use when constructing this feature */ public readonly options: IWebXRHitTestOptions = {} ) { super(_xrSessionManager); this.xrNativeFeatureName = "hit-test"; Tools.Warn("Hit test is an experimental and unstable feature."); } /** * attach this feature * Will usually be called by the features manager * * @returns true if successful. */ public attach(): boolean { if (!super.attach()) { return false; } // Feature enabled, but not available if (!this._xrSessionManager.session.requestHitTestSource) { return false; } if (!this.options.disablePermanentHitTest) { if (this._xrSessionManager.referenceSpace) { this.initHitTestSource(this._xrSessionManager.referenceSpace); } this._xrSessionManager.onXRReferenceSpaceChanged.add(this.initHitTestSource); } if (this.options.enableTransientHitTest) { const offsetRay = new XRRay(this.options.transientOffsetRay || {}); this._xrSessionManager.session .requestHitTestSourceForTransientInput!({ profile: this.options.transientHitTestProfile || "generic-touchscreen", offsetRay, entityTypes: this.options.entityTypes, }) .then((hitSource) => { this._transientXrHitTestSource = hitSource; }); } return true; } /** * detach this feature. * Will usually be called by the features manager * * @returns true if successful. */ public detach(): boolean { if (!super.detach()) { return false; } if (this._xrHitTestSource) { this._xrHitTestSource.cancel(); this._xrHitTestSource = null; } this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this.initHitTestSource); if (this._transientXrHitTestSource) { this._transientXrHitTestSource.cancel(); this._transientXrHitTestSource = null; } return true; } /** * Dispose this feature and all of the resources attached */ public dispose(): void { super.dispose(); this.onHitTestResultObservable.clear(); } protected _onXRFrame(frame: XRFrame) { // make sure we do nothing if (async) not attached if (!this.attached || this.paused) { return; } if (this._xrHitTestSource) { const results = frame.getHitTestResults(this._xrHitTestSource); this._processWebXRHitTestResult(results); } if (this._transientXrHitTestSource) { let hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource); hitTestResultsPerInputSource.forEach((resultsPerInputSource) => { this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource); }); } } private _processWebXRHitTestResult(hitTestResults: XRHitTestResult[], inputSource?: XRInputSource) { const results: IWebXRHitResult[] = []; hitTestResults.forEach((hitTestResult) => { const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace); if (!pose) { return; } const pos = pose.transform.position; const quat = pose.transform.orientation; this._tmpPos.set(pos.x, pos.y, pos.z); this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w); Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat); if (!this._xrSessionManager.scene.useRightHandedSystem) { this._tmpPos.z *= -1; this._tmpQuat.z *= -1; this._tmpQuat.w *= -1; this._tmpMat.toggleModelMatrixHandInPlace(); } const result: IWebXRHitResult = { position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos, rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat, transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat, inputSource: inputSource, isTransient: !!inputSource, xrHitResult: hitTestResult, }; results.push(result); }); this.onHitTestResultObservable.notifyObservers(results); } } //register the plugin versions WebXRFeaturesManager.AddWebXRFeature( WebXRHitTest.Name, (xrSessionManager, options) => { return () => new WebXRHitTest(xrSessionManager, options); }, WebXRHitTest.Version, false );
the_stack
import realdeepmerge from 'deepmerge'; import { Meta } from '@/typings/module'; import { Module } from '@/typings/module/registry'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Deepmerge = (x: any, y: any) => any; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-axe', (): void => { it('should register module', async (): Promise<void> => { const deepmergeMock = jest.fn(); const register = jest.fn(); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: false, thresholds: { impact: 'serious', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: false, thresholds: { impact: 'serious', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should execute module', async (): Promise<void> => { const deepmergeMock = jest.fn(); const close = jest.fn().mockResolvedValue(true); const goto = jest.fn().mockResolvedValue(true); const setBypassCSP = jest.fn().mockResolvedValue(true); const newPage = jest.fn().mockResolvedValue({ close, goto, setBypassCSP, }); const chrome = { newPage }; const analyze = jest.fn().mockResolvedValue({ passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }); const disableRules = jest.fn(); const exclude = jest.fn(); const include = jest.fn(); const withRules = jest.fn(); const withTags = jest.fn(); const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const ret = await cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'https://example.com', }); expect(ret).toEqual({ data: [ { data: [ { label: 'foo', rawLabel: 'foo', rawThreshold: 'minor', rawValue: undefined, success: true, threshold: 'minor', thresholdLimit: 'upper', type: 'axe', value: '', }, { label: 'bar', rawLabel: 'bar', rawThreshold: 'minor', rawValue: 'moderate', success: false, threshold: 'minor', thresholdLimit: 'upper', type: 'axe', value: 'moderate', }, ], label: 'Axe Audits', rawLabel: 'Axe Audits', success: false, type: 'axe', }, ], raw: { passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }, success: false, }); expect(newPage).toHaveBeenCalledWith(); expect(close).toHaveBeenCalledWith(); expect(goto).toHaveBeenCalledWith('https://example.com'); expect(setBypassCSP).toHaveBeenCalledWith(true); expect(analyze).toHaveBeenCalledWith(); expect(disableRules).not.toHaveBeenCalled(); expect(exclude).not.toHaveBeenCalled(); expect(include).not.toHaveBeenCalled(); expect(withRules).not.toHaveBeenCalled(); expect(withTags).not.toHaveBeenCalled(); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ function AxePuppeteer(): any {} Object.assign(AxePuppeteer.prototype, { analyze, disableRules, exclude, include, withRules, withTags, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('axe-puppeteer', (): any => ({ AxePuppeteer, })); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should execute module with configs', async (): Promise<void> => { const deepmergeMock = jest.fn(); const close = jest.fn().mockResolvedValue(true); const goto = jest.fn().mockResolvedValue(true); const setBypassCSP = jest.fn().mockResolvedValue(true); const newPage = jest.fn().mockResolvedValue({ close, goto, setBypassCSP, }); const chrome = { newPage }; const analyze = jest.fn().mockResolvedValue({ passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }); const disableRules = jest.fn(); const exclude = jest.fn(); const include = jest.fn(); const withRules = jest.fn(); const withTags = jest.fn(); const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const ret = await cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'https://example.com', }); expect(ret).toEqual({ data: [ { data: [ { label: 'bar', rawLabel: 'bar', rawThreshold: 'serious', rawValue: 'moderate', success: true, threshold: 'serious', thresholdLimit: 'upper', type: 'axe', value: 'moderate', }, ], label: 'Axe Audits', rawLabel: 'Axe Audits', success: true, type: 'axe', }, ], raw: { passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }, success: true, }); expect(newPage).toHaveBeenCalledWith(); expect(close).toHaveBeenCalledWith(); expect(goto).toHaveBeenCalledWith('https://example.com'); expect(setBypassCSP).toHaveBeenCalledWith(true); expect(analyze).toHaveBeenCalledWith(); expect(disableRules).toHaveBeenCalledWith('rule-1'); expect(exclude).toHaveBeenCalledWith(['.a', '.b > c']); expect(include).toHaveBeenCalledWith('#z'); expect(withRules).toHaveBeenCalledWith(['rule-2']); expect(withTags).toHaveBeenCalledWith(['blah']); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ function AxePuppeteer(): any {} Object.assign(AxePuppeteer.prototype, { analyze, disableRules, exclude, include, withRules, withTags, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('axe-puppeteer', (): any => ({ AxePuppeteer, })); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { disabledRules: 'rule-1', exclude: ['.a', '.b > c'], include: '#z', rules: ['rule-2'], showSuccesses: false, tags: ['blah'], thresholds: { impact: 3, }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { disabledRules: 'rule-1', exclude: ['.a', '.b > c'], include: '#z', rules: ['rule-2'], showSuccesses: false, tags: ['blah'], thresholds: { impact: 3, }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should handle error on opening new page', async (): Promise<void> => { const deepmergeMock = jest.fn(); const newPage = jest.fn().mockResolvedValue(null); const chrome = { newPage }; const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const check = cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'http://example.com', }); await expect(check).rejects.toThrow(new Error('Could not open page to analyze with axe')); expect(newPage).toHaveBeenCalledWith(); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); });
the_stack
import { deepStrictEqual as eq, ok, fail } from 'assert'; import { JSDOM } from 'jsdom'; import sinon = require('sinon'); import { reset } from './mock'; import App from '../../renderer/app'; const { ipcRenderer } = require('electron') as any; // mocked describe('App', function () { let app: App; beforeEach(function () { reset(); (global as any).window = { addEventListener: sinon.spy(), }; app = new App(); app.start(); }); afterEach(function () { delete (global as any).window; delete (global as any).document; }); function emulateSend(chan: IpcChan.FromMain, ...args: any[]) { ok(ipcRenderer.on.called); const calls = ipcRenderer.on.getCalls(); for (const call of calls) { if (call.args[0] === chan) { call.args[1](null, ...args); return; } } fail(`No listener for ${chan}: ${JSON.stringify(calls, null, 2)}`); } it('sets action after tweet on IPC message', function () { emulateSend('tweetapp:action-after-tweet', 'reply previous'); eq((app as any).afterTweet, 'reply previous'); }); it('sets screen name on IPC message', function () { emulateSend('tweetapp:screen-name', 'foo'); eq((app as any).screenName, 'foo'); }); it('reopens given URL when no screen name is set on tweetapp:sent-tweet', function () { // Navigation is not implemented in jsdom (global as any).window.location = {}; const url = 'https://mobile.twitter.com/compose/tweet'; emulateSend('tweetapp:sent-tweet', url); eq(window.location.href, url); }); it('finds previous tweet ID and sets in_reply_to query param on tweetapp:sent-tweet', async function () { emulateSend('tweetapp:screen-name', 'foo'); emulateSend('tweetapp:action-after-tweet', 'reply previous'); let url: string | undefined; function setHrefSpy() { return new Promise<void>(resolve => { (global as any).window.location = { set href(u: string) { url = u; resolve(); }, }; }); } let hrefWasSet = setHrefSpy(); (global as any).document = new JSDOM(` <body> <a href="/foo/status/114514">tweet</a> </body> `).window.document; const twUrl = 'https://mobile.twitter.com/compose/tweet'; emulateSend('tweetapp:sent-tweet', twUrl); await hrefWasSet; eq(url, twUrl + '?in_reply_to=114514'); const call = ipcRenderer.send.getCalls().find((c: any) => c.args[0] === 'tweetapp:prev-tweet-id'); eq(call.args[1], '114514'); hrefWasSet = setHrefSpy(); const twTextUrl = 'https://mobile.twitter.com/compose/tweet?text=hello'; emulateSend('tweetapp:sent-tweet', twTextUrl); await hrefWasSet; eq(url, twTextUrl + '&in_reply_to=114514'); }); it('searches tweet button with 4s timeout', async function () { this.timeout(10000); // Timeout is 4 seconds const start = Date.now(); emulateSend('tweetapp:screen-name', 'foo'); emulateSend('tweetapp:action-after-tweet', 'reply previous'); let url: string | undefined; function setHrefSpy() { return new Promise<void>(resolve => { (global as any).window.location = { set href(u: string) { url = u; resolve(); }, }; }); } const hrefWasSet = setHrefSpy(); (global as any).document = new JSDOM('').window.document; const twUrl = 'https://mobile.twitter.com/compose/tweet'; emulateSend('tweetapp:sent-tweet', twUrl); await hrefWasSet; const elapsedMs = Date.now() - start; eq(url, twUrl); ok(elapsedMs > 4000, `${elapsedMs}`); }); it('opens given URL on tweetapp:open', function () { // Navigation is not implemented in jsdom (global as any).window.location = {}; const url = 'https://mobile.twitter.com/compose/tweet?text=hello'; emulateSend('tweetapp:open', url); eq(window.location.href, url); }); it('sets login name to user name <input> on tweetapp:login', function () { (global as any).document = new JSDOM(` <input name="username_or_email"/> <input name="password"/> `).window.document; emulateSend('tweetapp:screen-name', 'foo'); emulateSend('tweetapp:login'); const input = document.querySelector('input[name*="username_or_email"]') as HTMLInputElement | null; ok(input); eq(input!.value, 'foo'); }); it('does not set login name to user name <input> on tweetapp:login when screen name is unknown or <input> is not found', function () { (global as any).document = new JSDOM(` <input name="username_or_email"/> <input name="password"/> `).window.document; emulateSend('tweetapp:login'); const input = document.querySelector('input[name*="username_or_email"]') as HTMLInputElement | null; ok(input); eq(input!.value, ''); input!.name = 'foooo'; emulateSend('tweetapp:login'); // Should not raise an error }); it('does nothing when button is not found', function () { (global as any).document = new JSDOM('<div role="button" tabIndex="0">Foooo!!!!!</div>').window.document; const click = sinon.fake(); (document.getElementsByTagName('DIV')[0] as HTMLDivElement).click = click; emulateSend('tweetapp:click-tweet-button'); ok(!click.called); }); for (const html of [ '<div data-testid="tweetButton"></div>', '<div role="button" tabIndex="0">Tweet</div>', '<div role="button" tabIndex="0">Tweet All</div>', '<div role="button" tabIndex="0">Reply</div>', '<div role="button" tabIndex="0">ツイート</div>', '<div role="button" tabIndex="0">すべてツイート</div>', '<div role="button" tabIndex="0">返信</div>', ]) { it(`finds tweet button from "${html}" on tweetapp:click-tweet-button IPC message`, function () { (global as any).document = new JSDOM(html).window.document; const click = sinon.fake(); (document.getElementsByTagName('DIV')[0] as HTMLDivElement).click = click; emulateSend('tweetapp:click-tweet-button'); ok(click.calledOnce); }); } for (const [what, html] of [ [ 'data-testid', ` <div role="button" tabIndex="0"></div> <div id="back" role="button" tabIndex="0" aria-label="Back"></div> <div id="discard" data-testid="confirmationSheetCancel"></div> <div id="save" data-testid="confirmationSheetConfirm"></div> `, ], [ 'English texts', ` <div role="button" tabIndex="0"></div> <div id="back" role="button" tabIndex="0" aria-label="Back"></div> <div id="discard" role="button" tabIndex="0">Discard</div> <div id="save" role="button" tabIndex="0">Save</div> `, ], [ 'Japanese texts', ` <div role="button" tabIndex="0"></div> <div id="back" role="button" tabIndex="0" aria-label="戻る"></div> <div id="discard" role="button" tabIndex="0">破棄</div> <div id="save" role="button" tabIndex="0">保存</div> `, ], ]) { it(`finds "Discard" and "Save" buttons with ${what} on tweetapp:cancel-tweet IPC message`, function () { (global as any).document = new JSDOM(html).window.document; const backClick = sinon.fake(); (document.getElementById('back') as HTMLDivElement).click = backClick; const discardListener = sinon.fake(); (document.getElementById('discard') as HTMLDivElement).addEventListener = discardListener; const saveListener = sinon.fake(); (document.getElementById('save') as HTMLDivElement).addEventListener = saveListener; emulateSend('tweetapp:cancel-tweet'); ok(discardListener.calledOnce); eq(discardListener.lastCall.args[0], 'click'); ok(saveListener.calledOnce); eq(saveListener.lastCall.args[0], 'click'); }); } it('sends tweetapp:reset-window message when "Discard" and "Save" buttons are not found on tweetapp:cancel-tweet assuming no text in textarea', function () { const htmlOnlyBackExists = '<div id="back" role="button" tabIndex="0" aria-label="Back"></div>'; (global as any).document = new JSDOM(htmlOnlyBackExists).window.document; emulateSend('tweetapp:cancel-tweet'); ok(ipcRenderer.send.calledOnce); eq(ipcRenderer.send.lastCall.args, ['tweetapp:reset-window']); }); it('does nothing when no "Back" button is found on tweetapp:cancel-tweet IPC message', function () { (global as any).document = new JSDOM('').window.document; emulateSend('tweetapp:cancel-tweet'); ok(!ipcRenderer.send.called); }); it('sends IPC message to main process when online status changed', function () { (window as any).navigator = { onLine: true }; const calls = (window as any).addEventListener.getCalls(); const onOnline = calls.find((c: any) => c.args[0] === 'online').args[1]; const onOffline = calls.find((c: any) => c.args[0] === 'offline').args[1]; const onLoad = calls.find((c: any) => c.args[0] === 'load').args[1]; onLoad(); eq(ipcRenderer.send.lastCall.args, ['tweetapp:online-status', 'online']); onOffline(); eq(ipcRenderer.send.lastCall.args, ['tweetapp:online-status', 'offline']); onOnline(); eq(ipcRenderer.send.lastCall.args, ['tweetapp:online-status', 'online']); }); it('rejects ESC key since it navigates to home timeline at tweet form', function () { const calls = (window as any).addEventListener.getCalls(); const onKeydown = calls.find((c: any) => c.args[0] === 'keydown').args[1]; const stopPropagation = sinon.fake(); onKeydown({ key: 'A', stopPropagation, }); ok(!stopPropagation.called); onKeydown({ key: 'Escape', stopPropagation, }); ok(stopPropagation.called); }); });
the_stack
import { api, Process, config, utils, specHelper, chatRoom, } from "./../../src/index"; const actionhero = new Process(); describe("Core", () => { describe("chatRoom", () => { beforeAll(async () => { await actionhero.start(); for (var room in config.general.startingChatRooms) { try { await chatRoom.destroy(room); await chatRoom.add(room); } catch (error) { if ( !error.toString().match(config.errors.connectionRoomExists(room)) ) { throw error; } } } }); afterAll(async () => { await actionhero.stop(); }); describe("say and clients on separate servers", () => { let client1; let client2; let client3; beforeAll(async () => { client1 = await specHelper.buildConnection(); client2 = await specHelper.buildConnection(); client3 = await specHelper.buildConnection(); client1.verbs("roomAdd", "defaultRoom"); client2.verbs("roomAdd", "defaultRoom"); client3.verbs("roomAdd", "defaultRoom"); await utils.sleep(100); }); afterAll(async () => { client1.destroy(); client2.destroy(); client3.destroy(); await utils.sleep(100); }); test("all connections can join the default room and client #1 can see them", async () => { const { room, membersCount } = await client1.verbs( "roomView", "defaultRoom" ); expect(room).toEqual("defaultRoom"); expect(membersCount).toEqual(3); }); test("all connections can join the default room and client #2 can see them", async () => { const { room, membersCount } = await client2.verbs( "roomView", "defaultRoom" ); expect(room).toEqual("defaultRoom"); expect(membersCount).toEqual(3); }); test("all connections can join the default room and client #3 can see them", async () => { const { room, membersCount } = await client3.verbs( "roomView", "defaultRoom" ); expect(room).toEqual("defaultRoom"); expect(membersCount).toEqual(3); }); test("clients can communicate across the cluster", async () => { await client1.verbs("say", [ "defaultRoom", "Hi", "from", "client", "1", ]); await utils.sleep(100); const { message, room, from } = client2.messages[client2.messages.length - 1]; expect(message).toEqual("Hi from client 1"); expect(room).toEqual("defaultRoom"); expect(from).toEqual(client1.id); }); }); describe("chat", () => { beforeEach(async () => { try { await chatRoom.destroy("newRoom"); } catch (error) { // it's fine } }); test("can check if rooms exist", async () => { const found = await chatRoom.exists("defaultRoom"); expect(found).toEqual(true); }); test("can check if a room does not exist", async () => { const found = await chatRoom.exists("missingRoom"); expect(found).toEqual(false); }); test("server can create new room", async () => { const room = "newRoom"; let found; found = await chatRoom.exists(room); expect(found).toEqual(false); await chatRoom.add(room); found = await chatRoom.exists(room); expect(found).toEqual(true); }); test("server cannot create already existing room", async () => { try { await chatRoom.add("defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: room exists"); } }); test("can enumerate all the rooms in the system", async () => { await chatRoom.add("newRoom"); const rooms = await chatRoom.list(); expect(rooms).toHaveLength(3); ["defaultRoom", "newRoom", "otherRoom"].forEach((r) => { expect(rooms.indexOf(r)).toBeGreaterThan(-1); }); }); test("server can add connections to a LOCAL room", async () => { const client = await specHelper.buildConnection(); expect(client.rooms).toHaveLength(0); const didAdd = await chatRoom.addMember(client.id, "defaultRoom"); expect(didAdd).toEqual(true); expect(client.rooms[0]).toEqual("defaultRoom"); client.destroy(); }); test("will not re-add a member to a room", async () => { const client = await specHelper.buildConnection(); expect(client.rooms).toHaveLength(0); let didAdd = await chatRoom.addMember(client.id, "defaultRoom"); expect(didAdd).toEqual(true); try { didAdd = await chatRoom.addMember(client.id, "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual( "Error: connection already in this room (defaultRoom)" ); client.destroy(); } }); test("will not add a member to a non-existent room", async () => { const client = await specHelper.buildConnection(); expect(client.rooms).toHaveLength(0); try { await chatRoom.addMember(client.id, "crazyRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: room does not exist"); client.destroy(); } }); test("server will not remove a member not in a room", async () => { const client = await specHelper.buildConnection(); try { await chatRoom.removeMember(client.id, "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual( "Error: connection not in this room (defaultRoom)" ); client.destroy(); } }); test("server can remove connections to a room", async () => { const client = await specHelper.buildConnection(); const didAdd = await chatRoom.addMember(client.id, "defaultRoom"); expect(didAdd).toEqual(true); const didRemove = await chatRoom.removeMember(client.id, "defaultRoom"); expect(didRemove).toEqual(true); client.destroy(); }); test("server can destroy a room and connections will be removed", async () => { try { // to ensure it starts empty await chatRoom.destroy("newRoom"); } catch (error) {} const client = await specHelper.buildConnection(); await chatRoom.add("newRoom"); const didAdd = await chatRoom.addMember(client.id, "newRoom"); expect(didAdd).toEqual(true); expect(client.rooms[0]).toEqual("newRoom"); await chatRoom.destroy("newRoom"); expect(client.rooms).toHaveLength(0); // testing for the receipt of this message is a race condition with room.destroy and broadcast in test // client.messages[1].message.should.equal('this room has been deleted') // client.messages[1].room.should.equal('newRoom') client.destroy(); }); test("can get a list of room members", async () => { const client = await specHelper.buildConnection(); expect(client.rooms).toHaveLength(0); await chatRoom.add("newRoom"); await chatRoom.addMember(client.id, "newRoom"); const { room, membersCount } = await chatRoom.roomStatus("newRoom"); expect(room).toEqual("newRoom"); expect(membersCount).toEqual(1); client.destroy(); await chatRoom.destroy("newRoom"); }); test("can see the details of the other members in the room", async () => { const client = await specHelper.buildConnection(); const otherClient = await specHelper.buildConnection(); await chatRoom.add("newRoom"); await chatRoom.addMember(client.id, "newRoom"); await utils.sleep(100); await chatRoom.addMember(otherClient.id, "newRoom"); const { members, membersCount } = await chatRoom.roomStatus("newRoom"); expect(membersCount).toBe(2); expect(members).toEqual({ [client.id]: { id: client.id, joinedAt: expect.any(Number) }, [otherClient.id]: { id: otherClient.id, joinedAt: expect.any(Number), }, }); expect(members[otherClient.id].joinedAt).toBeGreaterThan( members[client.id].joinedAt ); client.destroy(); otherClient.destroy(); await chatRoom.destroy("newRoom"); }); describe("chat middleware", () => { let clientA; let clientB; let originalGenerateMessagePayload; beforeEach(async () => { originalGenerateMessagePayload = api.chatRoom.generateMessagePayload; clientA = await specHelper.buildConnection(); clientB = await specHelper.buildConnection(); }); afterEach(() => { api.chatRoom.middleware = {}; api.chatRoom.globalMiddleware = []; clientA.destroy(); clientB.destroy(); api.chatRoom.generateMessagePayload = originalGenerateMessagePayload; }); test("generateMessagePayload can be overloaded", async () => { api.chatRoom.generateMessagePayload = (message) => { return { thing: "stuff", room: message.connection.room, from: message.connection.id, }; }; await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientA.verbs("say", ["defaultRoom", "hi there"]); await utils.sleep(100); const message = clientB.messages[clientB.messages.length - 1]; expect(message.thing).toEqual("stuff"); expect(message.message).toBeUndefined(); }); test("(join + leave) can add middleware to announce members", async () => { chatRoom.addMiddleware({ name: "add chat middleware", join: async (connection, room) => { await chatRoom.broadcast( {}, room, `I have entered the room: ${connection.id}` ); }, }); chatRoom.addMiddleware({ name: "leave chat middleware", leave: async (connection, room) => { await chatRoom.broadcast( {}, room, `I have left the room: ${connection.id}` ); }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomLeave", "defaultRoom"); await utils.sleep(100); expect(clientA.messages.pop().message).toEqual( "I have left the room: " + clientB.id ); expect(clientA.messages.pop().message).toEqual( "I have entered the room: " + clientB.id ); }); test("(say) can modify message payloads", async () => { chatRoom.addMiddleware({ name: "chat middleware", say: (connection, room, messagePayload) => { if (messagePayload.from !== 0) { messagePayload.message = "something else"; } return messagePayload; }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); const lastMessage = clientA.messages[clientA.messages.length - 1]; expect(lastMessage.message).toEqual("something else"); }); test("can add middleware in a particular order and will be passed modified messagePayloads", async () => { chatRoom.addMiddleware({ name: "chat middleware 1", priority: 1000, say: (connection, room, messagePayload, callback) => { messagePayload.message = "MIDDLEWARE 1"; return messagePayload; }, }); chatRoom.addMiddleware({ name: "chat middleware 2", priority: 2000, say: (connection, room, messagePayload) => { messagePayload.message = messagePayload.message + " MIDDLEWARE 2"; return messagePayload; }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); const lastMessage = clientA.messages[clientA.messages.length - 1]; expect(lastMessage.message).toEqual("MIDDLEWARE 1 MIDDLEWARE 2"); }); test("say middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", say: (connection, room, messagePayload) => { throw new Error("messages blocked"); }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); // welcome message is passed, no join/leave/or say messages expect(clientA.messages).toHaveLength(1); expect(clientA.messages[0].welcome).toMatch(/Welcome/); }); test("join middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", join: (connection, room) => { throw new Error("joining rooms blocked"); }, }); try { await clientA.verbs("roomAdd", "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: joining rooms blocked"); expect(clientA.rooms).toHaveLength(0); } }); test("leave middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", leave: (connection, room) => { throw new Error("Hotel California"); }, }); const didJoin = await clientA.verbs("roomAdd", "defaultRoom"); expect(didJoin).toEqual(true); expect(clientA.rooms).toHaveLength(1); expect(clientA.rooms[0]).toEqual("defaultRoom"); try { await clientA.verbs("roomLeave", "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: Hotel California"); expect(clientA.rooms).toHaveLength(1); } }); test("(say verb with async keyword) can modify message payloads", async () => { chatRoom.addMiddleware({ name: "chat middleware", say: async (connection, room, messagePayload) => { if (messagePayload.from !== 0) { messagePayload.message = "something else"; } return messagePayload; }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); const lastMessage = clientA.messages[clientA.messages.length - 1]; expect(lastMessage.message).toEqual("something else"); }); test("can add middleware in a particular order and will be passed modified messagePayloads with both being async functions", async () => { chatRoom.addMiddleware({ name: "chat middleware 1", priority: 1000, say: async (connection, room, messagePayload, callback) => { messagePayload.message = "MIDDLEWARE 1"; return messagePayload; }, }); chatRoom.addMiddleware({ name: "chat middleware 2", priority: 2000, say: async (connection, room, messagePayload) => { messagePayload.message = messagePayload.message + " MIDDLEWARE 2"; return messagePayload; }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); const lastMessage = clientA.messages[clientA.messages.length - 1]; expect(lastMessage.message).toEqual("MIDDLEWARE 1 MIDDLEWARE 2"); }); test("say async function middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", say: async (connection, room, messagePayload) => { throw new Error("messages blocked"); }, }); await clientA.verbs("roomAdd", "defaultRoom"); await clientB.verbs("roomAdd", "defaultRoom"); await clientB.verbs("say", ["defaultRoom", "something", "awesome"]); await utils.sleep(100); // welcome message is passed, no join/leave/or say messages expect(clientA.messages).toHaveLength(1); expect(clientA.messages[0].welcome).toMatch(/Welcome/); }); test("join async function middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", join: async (connection, room) => { throw new Error("joining rooms blocked"); }, }); try { await clientA.verbs("roomAdd", "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: joining rooms blocked"); expect(clientA.rooms).toHaveLength(0); } }); test("leave async function middleware can block execution", async () => { chatRoom.addMiddleware({ name: "chat middleware", leave: async (connection, room) => { throw new Error("Hotel California"); }, }); const didJoin = await clientA.verbs("roomAdd", "defaultRoom"); expect(didJoin).toEqual(true); expect(clientA.rooms).toHaveLength(1); expect(clientA.rooms[0]).toEqual("defaultRoom"); try { await clientA.verbs("roomLeave", "defaultRoom"); throw new Error("should not get here"); } catch (error) { expect(error.toString()).toEqual("Error: Hotel California"); expect(clientA.rooms).toHaveLength(1); } }); }); }); }); });
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the IotDpsClient. */ export interface Operations { /** * Lists all of the available Microsoft.Devices REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available Microsoft.Devices REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available Microsoft.Devices REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available Microsoft.Devices REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * DpsCertificate * __NOTE__: An instance of this class is automatically created for an * instance of the IotDpsClient. */ export interface DpsCertificate { /** * Get the certificate from the provisioning service. * * @param {string} certificateName Name of the certificate to retrieve. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of the provisioning service the * certificate is associated with. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the certificate. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(certificateName: string, resourceGroupName: string, provisioningServiceName: string, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CertificateResponse>>; /** * Get the certificate from the provisioning service. * * @param {string} certificateName Name of the certificate to retrieve. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of the provisioning service the * certificate is associated with. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the certificate. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CertificateResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CertificateResponse} [result] - The deserialized result object if an error did not occur. * See {@link CertificateResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(certificateName: string, resourceGroupName: string, provisioningServiceName: string, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.CertificateResponse>; get(certificateName: string, resourceGroupName: string, provisioningServiceName: string, callback: ServiceCallback<models.CertificateResponse>): void; get(certificateName: string, resourceGroupName: string, provisioningServiceName: string, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CertificateResponse>): void; /** * @summary Upload the certificate to the provisioning service. * * Add new certificate or update an existing certificate. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName The name of the provisioning * service. * * @param {string} certificateName The name of the certificate create or * update. * * @param {object} certificateDescription The certificate body. * * @param {string} [certificateDescription.certificate] Base-64 representation * of the X509 leaf certificate .cer file or just .pem file content. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the certificate. This is required * to update an existing certificate, and ignored while creating a brand new * certificate. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, certificateName: string, certificateDescription: models.CertificateBodyDescription, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CertificateResponse>>; /** * @summary Upload the certificate to the provisioning service. * * Add new certificate or update an existing certificate. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName The name of the provisioning * service. * * @param {string} certificateName The name of the certificate create or * update. * * @param {object} certificateDescription The certificate body. * * @param {string} [certificateDescription.certificate] Base-64 representation * of the X509 leaf certificate .cer file or just .pem file content. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the certificate. This is required * to update an existing certificate, and ignored while creating a brand new * certificate. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CertificateResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CertificateResponse} [result] - The deserialized result object if an error did not occur. * See {@link CertificateResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, provisioningServiceName: string, certificateName: string, certificateDescription: models.CertificateBodyDescription, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.CertificateResponse>; createOrUpdate(resourceGroupName: string, provisioningServiceName: string, certificateName: string, certificateDescription: models.CertificateBodyDescription, callback: ServiceCallback<models.CertificateResponse>): void; createOrUpdate(resourceGroupName: string, provisioningServiceName: string, certificateName: string, certificateDescription: models.CertificateBodyDescription, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CertificateResponse>): void; /** * @summary Delete the Provisioning Service Certificate. * * Deletes the specified certificate assosciated with the Provisioning Service * * @param {string} resourceGroupName Resource group identifier. * * @param {string} ifMatch ETag of the certificate * * @param {string} provisioningServiceName The name of the provisioning * service. * * @param {string} certificateName This is a mandatory field, and is the * logical name of the certificate that the provisioning service will access * by. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] This is optional, and it is the * Common Name of the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data within the * certificate. * * @param {boolean} [options.certificateisVerified] Indicates if certificate * has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] A description that mentions the * purpose of the certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Time the certificate is created. * * @param {date} [options.certificatelastUpdated] Time the certificate is last * updated. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains a private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, ifMatch: string, provisioningServiceName: string, certificateName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete the Provisioning Service Certificate. * * Deletes the specified certificate assosciated with the Provisioning Service * * @param {string} resourceGroupName Resource group identifier. * * @param {string} ifMatch ETag of the certificate * * @param {string} provisioningServiceName The name of the provisioning * service. * * @param {string} certificateName This is a mandatory field, and is the * logical name of the certificate that the provisioning service will access * by. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] This is optional, and it is the * Common Name of the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data within the * certificate. * * @param {boolean} [options.certificateisVerified] Indicates if certificate * has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] A description that mentions the * purpose of the certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Time the certificate is created. * * @param {date} [options.certificatelastUpdated] Time the certificate is last * updated. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains a private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, ifMatch: string, provisioningServiceName: string, certificateName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, ifMatch: string, provisioningServiceName: string, certificateName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, ifMatch: string, provisioningServiceName: string, certificateName: string, options: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get all the certificates tied to the provisioning service. * * @param {string} resourceGroupName Name of resource group. * * @param {string} provisioningServiceName Name of provisioning service to * retrieve certificates for. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CertificateListDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CertificateListDescription>>; /** * Get all the certificates tied to the provisioning service. * * @param {string} resourceGroupName Name of resource group. * * @param {string} provisioningServiceName Name of provisioning service to * retrieve certificates for. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CertificateListDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CertificateListDescription} [result] - The deserialized result object if an error did not occur. * See {@link CertificateListDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, provisioningServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CertificateListDescription>; list(resourceGroupName: string, provisioningServiceName: string, callback: ServiceCallback<models.CertificateListDescription>): void; list(resourceGroupName: string, provisioningServiceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CertificateListDescription>): void; /** * Generate verification code for Proof of Possession. * * @param {string} certificateName The mandatory logical name of the * certificate, that the provisioning service uses to access. * * @param {string} ifMatch ETag of the certificate. This is required to update * an existing certificate, and ignored while creating a brand new certificate. * * @param {string} resourceGroupName name of resource group. * * @param {string} provisioningServiceName Name of provisioning service. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] Common Name for the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data of certificate. * * @param {boolean} [options.certificateisVerified] Indicates if the * certificate has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] Description mentioning the * purpose of the certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Certificate creation time. * * @param {date} [options.certificatelastUpdated] Certificate last updated * time. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VerificationCodeResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ generateVerificationCodeWithHttpOperationResponse(certificateName: string, ifMatch: string, resourceGroupName: string, provisioningServiceName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VerificationCodeResponse>>; /** * Generate verification code for Proof of Possession. * * @param {string} certificateName The mandatory logical name of the * certificate, that the provisioning service uses to access. * * @param {string} ifMatch ETag of the certificate. This is required to update * an existing certificate, and ignored while creating a brand new certificate. * * @param {string} resourceGroupName name of resource group. * * @param {string} provisioningServiceName Name of provisioning service. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] Common Name for the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data of certificate. * * @param {boolean} [options.certificateisVerified] Indicates if the * certificate has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] Description mentioning the * purpose of the certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Certificate creation time. * * @param {date} [options.certificatelastUpdated] Certificate last updated * time. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VerificationCodeResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VerificationCodeResponse} [result] - The deserialized result object if an error did not occur. * See {@link VerificationCodeResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ generateVerificationCode(certificateName: string, ifMatch: string, resourceGroupName: string, provisioningServiceName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.VerificationCodeResponse>; generateVerificationCode(certificateName: string, ifMatch: string, resourceGroupName: string, provisioningServiceName: string, callback: ServiceCallback<models.VerificationCodeResponse>): void; generateVerificationCode(certificateName: string, ifMatch: string, resourceGroupName: string, provisioningServiceName: string, options: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VerificationCodeResponse>): void; /** * @summary Verify certificate's private key possession. * * Verifies the certificate's private key possession by providing the leaf cert * issued by the verifying pre uploaded certificate. * * @param {string} certificateName The mandatory logical name of the * certificate, that the provisioning service uses to access. * * @param {string} ifMatch ETag of the certificate. * * @param {object} request The name of the certificate * * @param {string} [request.certificate] base-64 representation of X509 * certificate .cer file or just .pem file content. * * @param {string} resourceGroupName Resource group name. * * @param {string} provisioningServiceName Provisioning service name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] Common Name for the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data of certificate. * * @param {boolean} [options.certificateisVerified] Indicates if the * certificate has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] Describe the purpose of the * certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Certificate creation time. * * @param {date} [options.certificatelastUpdated] Certificate last updated * time. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ verifyCertificateWithHttpOperationResponse(certificateName: string, ifMatch: string, request: models.VerificationCodeRequest, resourceGroupName: string, provisioningServiceName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CertificateResponse>>; /** * @summary Verify certificate's private key possession. * * Verifies the certificate's private key possession by providing the leaf cert * issued by the verifying pre uploaded certificate. * * @param {string} certificateName The mandatory logical name of the * certificate, that the provisioning service uses to access. * * @param {string} ifMatch ETag of the certificate. * * @param {object} request The name of the certificate * * @param {string} [request.certificate] base-64 representation of X509 * certificate .cer file or just .pem file content. * * @param {string} resourceGroupName Resource group name. * * @param {string} provisioningServiceName Provisioning service name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.certificatename] Common Name for the certificate. * * @param {buffer} [options.certificaterawBytes] Raw data of certificate. * * @param {boolean} [options.certificateisVerified] Indicates if the * certificate has been verified by owner of the private key. * * @param {string} [options.certificatepurpose] Describe the purpose of the * certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' * * @param {date} [options.certificatecreated] Certificate creation time. * * @param {date} [options.certificatelastUpdated] Certificate last updated * time. * * @param {boolean} [options.certificatehasPrivateKey] Indicates if the * certificate contains private key. * * @param {string} [options.certificatenonce] Random number generated to * indicate Proof of Possession. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CertificateResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CertificateResponse} [result] - The deserialized result object if an error did not occur. * See {@link CertificateResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ verifyCertificate(certificateName: string, ifMatch: string, request: models.VerificationCodeRequest, resourceGroupName: string, provisioningServiceName: string, options?: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.CertificateResponse>; verifyCertificate(certificateName: string, ifMatch: string, request: models.VerificationCodeRequest, resourceGroupName: string, provisioningServiceName: string, callback: ServiceCallback<models.CertificateResponse>): void; verifyCertificate(certificateName: string, ifMatch: string, request: models.VerificationCodeRequest, resourceGroupName: string, provisioningServiceName: string, options: { certificatename? : string, certificaterawBytes? : Buffer, certificateisVerified? : boolean, certificatepurpose? : string, certificatecreated? : Date, certificatelastUpdated? : Date, certificatehasPrivateKey? : boolean, certificatenonce? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CertificateResponse>): void; } /** * @class * IotDpsResource * __NOTE__: An instance of this class is automatically created for an * instance of the IotDpsClient. */ export interface IotDpsResource { /** * @summary Get the non-security related metadata of the provisioning service. * * Get the metadata of the provisioning service without SAS keys. * * @param {string} provisioningServiceName Name of the provisioning service to * retrieve. * * @param {string} resourceGroupName Resource group name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescription>>; /** * @summary Get the non-security related metadata of the provisioning service. * * Get the metadata of the provisioning service without SAS keys. * * @param {string} provisioningServiceName Name of the provisioning service to * retrieve. * * @param {string} resourceGroupName Resource group name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescription>; get(provisioningServiceName: string, resourceGroupName: string, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; get(provisioningServiceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; /** * @summary Create or update the metadata of the provisioning service. * * Create or update the metadata of the provisioning service. The usual pattern * to modify a property is to retrieve the provisioning service metadata and * security metadata, and then combine them with the modified values in a new * body to update the provisioning service. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} iotDpsDescription Description of the provisioning service to * create or update. * * @param {string} [iotDpsDescription.etag] The Etag field is *not* required. * If it is provided in the response body, it must also be provided as a header * per the normal ETag convention. * * @param {object} iotDpsDescription.properties Service specific properties for * a provisioning service * * @param {string} [iotDpsDescription.properties.state] Current state of the * provisioning service. Possible values include: 'Activating', 'Active', * 'Deleting', 'Deleted', 'ActivationFailed', 'DeletionFailed', * 'Transitioning', 'Suspending', 'Suspended', 'Resuming', 'FailingOver', * 'FailoverFailed' * * @param {string} [iotDpsDescription.properties.provisioningState] The ARM * provisioning state of the provisioning service. * * @param {array} [iotDpsDescription.properties.iotHubs] List of IoT hubs * assosciated with this provisioning service. * * @param {string} [iotDpsDescription.properties.allocationPolicy] Allocation * policy to be used by this provisioning service. Possible values include: * 'Hashed', 'GeoLatency', 'Static' * * @param {array} [iotDpsDescription.properties.authorizationPolicies] List of * authorization keys for a provisioning service. * * @param {object} iotDpsDescription.sku Sku info for a provisioning Service. * * @param {string} [iotDpsDescription.sku.name] Sku name. Possible values * include: 'S1' * * @param {number} [iotDpsDescription.sku.capacity] The number of units to * provision * * @param {string} iotDpsDescription.location The resource location. * * @param {object} [iotDpsDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescription>>; /** * @summary Create or update the metadata of the provisioning service. * * Create or update the metadata of the provisioning service. The usual pattern * to modify a property is to retrieve the provisioning service metadata and * security metadata, and then combine them with the modified values in a new * body to update the provisioning service. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} iotDpsDescription Description of the provisioning service to * create or update. * * @param {string} [iotDpsDescription.etag] The Etag field is *not* required. * If it is provided in the response body, it must also be provided as a header * per the normal ETag convention. * * @param {object} iotDpsDescription.properties Service specific properties for * a provisioning service * * @param {string} [iotDpsDescription.properties.state] Current state of the * provisioning service. Possible values include: 'Activating', 'Active', * 'Deleting', 'Deleted', 'ActivationFailed', 'DeletionFailed', * 'Transitioning', 'Suspending', 'Suspended', 'Resuming', 'FailingOver', * 'FailoverFailed' * * @param {string} [iotDpsDescription.properties.provisioningState] The ARM * provisioning state of the provisioning service. * * @param {array} [iotDpsDescription.properties.iotHubs] List of IoT hubs * assosciated with this provisioning service. * * @param {string} [iotDpsDescription.properties.allocationPolicy] Allocation * policy to be used by this provisioning service. Possible values include: * 'Hashed', 'GeoLatency', 'Static' * * @param {array} [iotDpsDescription.properties.authorizationPolicies] List of * authorization keys for a provisioning service. * * @param {object} iotDpsDescription.sku Sku info for a provisioning Service. * * @param {string} [iotDpsDescription.sku.name] Sku name. Possible values * include: 'S1' * * @param {number} [iotDpsDescription.sku.capacity] The number of units to * provision * * @param {string} iotDpsDescription.location The resource location. * * @param {object} [iotDpsDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescription>; createOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; createOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; /** * @summary Update an existing provisioning service's tags. * * Update an existing provisioning service's tags. to update other fields use * the CreateOrUpdate method * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} provisioningServiceTags Updated tag information to set into * the provisioning service instance. * * @param {object} [provisioningServiceTags.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescription>>; /** * @summary Update an existing provisioning service's tags. * * Update an existing provisioning service's tags. to update other fields use * the CreateOrUpdate method * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} provisioningServiceTags Updated tag information to set into * the provisioning service instance. * * @param {object} [provisioningServiceTags.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescription>; update(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; update(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; /** * @summary Delete the Provisioning Service * * Deletes the Provisioning Service. * * @param {string} provisioningServiceName Name of provisioning service to * delete. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete the Provisioning Service * * Deletes the Provisioning Service. * * @param {string} provisioningServiceName Name of provisioning service to * delete. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(provisioningServiceName: string, resourceGroupName: string, callback: ServiceCallback<void>): void; deleteMethod(provisioningServiceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Get all the provisioning services in a subscription. * * List all the provisioning services for a given subscription id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescriptionListResult>>; /** * @summary Get all the provisioning services in a subscription. * * List all the provisioning services for a given subscription id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescriptionListResult} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescriptionListResult>; listBySubscription(callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; /** * Get a list of all provisioning services in the given resource group. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescriptionListResult>>; /** * Get a list of all provisioning services in the given resource group. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescriptionListResult} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescriptionListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; /** * Gets the status of a long running operation, such as create, update or * delete a provisioning service. * * @param {string} operationId Operation id corresponding to long running * operation. Use this to poll for the status. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service that * the operation is running on. * * @param {string} asyncinfo Async header used to poll on the status of the * operation, obtained while creating the long running operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AsyncOperationResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getOperationResultWithHttpOperationResponse(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AsyncOperationResult>>; /** * Gets the status of a long running operation, such as create, update or * delete a provisioning service. * * @param {string} operationId Operation id corresponding to long running * operation. Use this to poll for the status. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service that * the operation is running on. * * @param {string} asyncinfo Async header used to poll on the status of the * operation, obtained while creating the long running operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AsyncOperationResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AsyncOperationResult} [result] - The deserialized result object if an error did not occur. * See {@link AsyncOperationResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AsyncOperationResult>; getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, callback: ServiceCallback<models.AsyncOperationResult>): void; getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AsyncOperationResult>): void; /** * @summary Get the list of valid SKUs for a provisioning service. * * Gets the list of valid SKUs and tiers for a provisioning service. * * @param {string} provisioningServiceName Name of provisioning service. * * @param {string} resourceGroupName Name of resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IotDpsSkuDefinitionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listValidSkusWithHttpOperationResponse(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IotDpsSkuDefinitionListResult>>; /** * @summary Get the list of valid SKUs for a provisioning service. * * Gets the list of valid SKUs and tiers for a provisioning service. * * @param {string} provisioningServiceName Name of provisioning service. * * @param {string} resourceGroupName Name of resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IotDpsSkuDefinitionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IotDpsSkuDefinitionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IotDpsSkuDefinitionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listValidSkus(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IotDpsSkuDefinitionListResult>; listValidSkus(provisioningServiceName: string, resourceGroupName: string, callback: ServiceCallback<models.IotDpsSkuDefinitionListResult>): void; listValidSkus(provisioningServiceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IotDpsSkuDefinitionListResult>): void; /** * @summary Check if a provisioning service name is available. * * Check if a provisioning service name is available. This will validate if the * name is syntactically valid and if the name is usable * * @param {object} argumentsParameter Set the name parameter in the * OperationInputs structure to the name of the provisioning service to check. * * @param {string} argumentsParameter.name The name of the Provisioning Service * to check. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NameAvailabilityInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ checkProvisioningServiceNameAvailabilityWithHttpOperationResponse(argumentsParameter: models.OperationInputs, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NameAvailabilityInfo>>; /** * @summary Check if a provisioning service name is available. * * Check if a provisioning service name is available. This will validate if the * name is syntactically valid and if the name is usable * * @param {object} argumentsParameter Set the name parameter in the * OperationInputs structure to the name of the provisioning service to check. * * @param {string} argumentsParameter.name The name of the Provisioning Service * to check. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NameAvailabilityInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NameAvailabilityInfo} [result] - The deserialized result object if an error did not occur. * See {@link NameAvailabilityInfo} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ checkProvisioningServiceNameAvailability(argumentsParameter: models.OperationInputs, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NameAvailabilityInfo>; checkProvisioningServiceNameAvailability(argumentsParameter: models.OperationInputs, callback: ServiceCallback<models.NameAvailabilityInfo>): void; checkProvisioningServiceNameAvailability(argumentsParameter: models.OperationInputs, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NameAvailabilityInfo>): void; /** * @summary Get the security metadata for a provisioning service. * * List the primary and secondary keys for a provisioning service. * * @param {string} provisioningServiceName The provisioning service name to get * the shared access keys for. * * @param {string} resourceGroupName resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessSignatureAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessSignatureAuthorizationRuleListResult>>; /** * @summary Get the security metadata for a provisioning service. * * List the primary and secondary keys for a provisioning service. * * @param {string} provisioningServiceName The provisioning service name to get * the shared access keys for. * * @param {string} resourceGroupName resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessSignatureAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessSignatureAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link * SharedAccessSignatureAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessSignatureAuthorizationRuleListResult>; listKeys(provisioningServiceName: string, resourceGroupName: string, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeys(provisioningServiceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleListResult>): void; /** * @summary Get a shared access policy by name from a provisioning service. * * List primary and secondary keys for a specific key name * * @param {string} provisioningServiceName Name of the provisioning service. * * @param {string} keyName Logical key name to get key-values for. * * @param {string} resourceGroupName The name of the resource group that * contains the provisioning service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessSignatureAuthorizationRuleAccessRightsDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysForKeyNameWithHttpOperationResponse(provisioningServiceName: string, keyName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>>; /** * @summary Get a shared access policy by name from a provisioning service. * * List primary and secondary keys for a specific key name * * @param {string} provisioningServiceName Name of the provisioning service. * * @param {string} keyName Logical key name to get key-values for. * * @param {string} resourceGroupName The name of the resource group that * contains the provisioning service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessSignatureAuthorizationRuleAccessRightsDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessSignatureAuthorizationRuleAccessRightsDescription} [result] - The deserialized result object if an error did not occur. * See {@link * SharedAccessSignatureAuthorizationRuleAccessRightsDescription} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>; listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>): void; listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>): void; /** * @summary Create or update the metadata of the provisioning service. * * Create or update the metadata of the provisioning service. The usual pattern * to modify a property is to retrieve the provisioning service metadata and * security metadata, and then combine them with the modified values in a new * body to update the provisioning service. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} iotDpsDescription Description of the provisioning service to * create or update. * * @param {string} [iotDpsDescription.etag] The Etag field is *not* required. * If it is provided in the response body, it must also be provided as a header * per the normal ETag convention. * * @param {object} iotDpsDescription.properties Service specific properties for * a provisioning service * * @param {string} [iotDpsDescription.properties.state] Current state of the * provisioning service. Possible values include: 'Activating', 'Active', * 'Deleting', 'Deleted', 'ActivationFailed', 'DeletionFailed', * 'Transitioning', 'Suspending', 'Suspended', 'Resuming', 'FailingOver', * 'FailoverFailed' * * @param {string} [iotDpsDescription.properties.provisioningState] The ARM * provisioning state of the provisioning service. * * @param {array} [iotDpsDescription.properties.iotHubs] List of IoT hubs * assosciated with this provisioning service. * * @param {string} [iotDpsDescription.properties.allocationPolicy] Allocation * policy to be used by this provisioning service. Possible values include: * 'Hashed', 'GeoLatency', 'Static' * * @param {array} [iotDpsDescription.properties.authorizationPolicies] List of * authorization keys for a provisioning service. * * @param {object} iotDpsDescription.sku Sku info for a provisioning Service. * * @param {string} [iotDpsDescription.sku.name] Sku name. Possible values * include: 'S1' * * @param {number} [iotDpsDescription.sku.capacity] The number of units to * provision * * @param {string} iotDpsDescription.location The resource location. * * @param {object} [iotDpsDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescription>>; /** * @summary Create or update the metadata of the provisioning service. * * Create or update the metadata of the provisioning service. The usual pattern * to modify a property is to retrieve the provisioning service metadata and * security metadata, and then combine them with the modified values in a new * body to update the provisioning service. * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} iotDpsDescription Description of the provisioning service to * create or update. * * @param {string} [iotDpsDescription.etag] The Etag field is *not* required. * If it is provided in the response body, it must also be provided as a header * per the normal ETag convention. * * @param {object} iotDpsDescription.properties Service specific properties for * a provisioning service * * @param {string} [iotDpsDescription.properties.state] Current state of the * provisioning service. Possible values include: 'Activating', 'Active', * 'Deleting', 'Deleted', 'ActivationFailed', 'DeletionFailed', * 'Transitioning', 'Suspending', 'Suspended', 'Resuming', 'FailingOver', * 'FailoverFailed' * * @param {string} [iotDpsDescription.properties.provisioningState] The ARM * provisioning state of the provisioning service. * * @param {array} [iotDpsDescription.properties.iotHubs] List of IoT hubs * assosciated with this provisioning service. * * @param {string} [iotDpsDescription.properties.allocationPolicy] Allocation * policy to be used by this provisioning service. Possible values include: * 'Hashed', 'GeoLatency', 'Static' * * @param {array} [iotDpsDescription.properties.authorizationPolicies] List of * authorization keys for a provisioning service. * * @param {object} iotDpsDescription.sku Sku info for a provisioning Service. * * @param {string} [iotDpsDescription.sku.name] Sku name. Possible values * include: 'S1' * * @param {number} [iotDpsDescription.sku.capacity] The number of units to * provision * * @param {string} iotDpsDescription.location The resource location. * * @param {object} [iotDpsDescription.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescription>; beginCreateOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; beginCreateOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: models.ProvisioningServiceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; /** * @summary Update an existing provisioning service's tags. * * Update an existing provisioning service's tags. to update other fields use * the CreateOrUpdate method * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} provisioningServiceTags Updated tag information to set into * the provisioning service instance. * * @param {object} [provisioningServiceTags.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescription>>; /** * @summary Update an existing provisioning service's tags. * * Update an existing provisioning service's tags. to update other fields use * the CreateOrUpdate method * * @param {string} resourceGroupName Resource group identifier. * * @param {string} provisioningServiceName Name of provisioning service to * create or update. * * @param {object} provisioningServiceTags Updated tag information to set into * the provisioning service instance. * * @param {object} [provisioningServiceTags.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescription>; beginUpdate(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; beginUpdate(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: models.TagsResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescription>): void; /** * @summary Delete the Provisioning Service * * Deletes the Provisioning Service. * * @param {string} provisioningServiceName Name of provisioning service to * delete. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Delete the Provisioning Service * * Deletes the Provisioning Service. * * @param {string} provisioningServiceName Name of provisioning service to * delete. * * @param {string} resourceGroupName Resource group identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(provisioningServiceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(provisioningServiceName: string, resourceGroupName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(provisioningServiceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Get all the provisioning services in a subscription. * * List all the provisioning services for a given subscription id. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescriptionListResult>>; /** * @summary Get all the provisioning services in a subscription. * * List all the provisioning services for a given subscription id. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescriptionListResult} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescriptionListResult>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; /** * Get a list of all provisioning services in the given resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProvisioningServiceDescriptionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProvisioningServiceDescriptionListResult>>; /** * Get a list of all provisioning services in the given resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProvisioningServiceDescriptionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProvisioningServiceDescriptionListResult} [result] - The deserialized result object if an error did not occur. * See {@link ProvisioningServiceDescriptionListResult} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProvisioningServiceDescriptionListResult>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProvisioningServiceDescriptionListResult>): void; /** * @summary Get the list of valid SKUs for a provisioning service. * * Gets the list of valid SKUs and tiers for a provisioning service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IotDpsSkuDefinitionListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listValidSkusNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IotDpsSkuDefinitionListResult>>; /** * @summary Get the list of valid SKUs for a provisioning service. * * Gets the list of valid SKUs and tiers for a provisioning service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IotDpsSkuDefinitionListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IotDpsSkuDefinitionListResult} [result] - The deserialized result object if an error did not occur. * See {@link IotDpsSkuDefinitionListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listValidSkusNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IotDpsSkuDefinitionListResult>; listValidSkusNext(nextPageLink: string, callback: ServiceCallback<models.IotDpsSkuDefinitionListResult>): void; listValidSkusNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IotDpsSkuDefinitionListResult>): void; /** * @summary Get the security metadata for a provisioning service. * * List the primary and secondary keys for a provisioning service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SharedAccessSignatureAuthorizationRuleListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SharedAccessSignatureAuthorizationRuleListResult>>; /** * @summary Get the security metadata for a provisioning service. * * List the primary and secondary keys for a provisioning service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SharedAccessSignatureAuthorizationRuleListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SharedAccessSignatureAuthorizationRuleListResult} [result] - The deserialized result object if an error did not occur. * See {@link * SharedAccessSignatureAuthorizationRuleListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeysNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SharedAccessSignatureAuthorizationRuleListResult>; listKeysNext(nextPageLink: string, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeysNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SharedAccessSignatureAuthorizationRuleListResult>): void; }
the_stack
import compose from '@tinkoff/utils/function/compose'; import type { Dispatcher } from './dispatcher'; import type { Event } from '../createEvent/createEvent.h'; import type { StoreClass, StoreInstance } from '../typings'; import type { Middleware } from './dispatcher.h'; import { subscribe } from './storeSubscribe'; import { SimpleEmitter } from '../stores/SimpleEmitter'; import type { Reducer } from '../createReducer/createReducer.h'; type InitialState = { stores: Record<string, any> }; type Handlers = Dispatcher['handlers']; type StoreHandler = Handlers[string][number]; const eventExecutor = <P>(event: Event<P>, handlerFns: Record<string, Function>) => { const keys = Object.keys(handlerFns); for (let index = 0; index < keys.length; index++) { const storeName = keys[index]; const handlerFn = handlerFns[storeName]; if (!handlerFn) { throw new Error(`${storeName} does not have a handler for action ${event.type}`); } handlerFn(event.payload, event.type); } }; // Конвертация старого типа экшенов в новый export const convertAction = (actionOrNameEvent: string | Event<any>, payload?: any) => { if (typeof actionOrNameEvent === 'string') { return { payload, type: actionOrNameEvent, error: false, }; } return actionOrNameEvent; }; // Это форкнутый вариант dispatchr export class DispatcherContext<TContext> extends SimpleEmitter { dispatcher: Dispatcher; storeInstances: Record<StoreClass['storeName'], StoreInstance>; storeUnsubscribeCallbacks: Record<StoreClass['storeName'], Function>; dispatcherInterface: { // deprecated getContext: () => TContext; // deprecated getStore: DispatcherContext<TContext>['getStore']; }; rehydratedStoreState: Record<string, any>; // eslint-disable-next-line react/static-property-placement context: TContext; private fullState: Record<string, any>; applyDispatch = <Payload>(event: Event<Payload>) => { const eventHandlers = this.dispatcher.handlers[event.type] || []; if (!eventHandlers.length) { return event.payload; } this.applyHandlers(event, eventHandlers); return event.payload; }; /** * @param context The context to be used for store instances */ constructor( dispatcher: Dispatcher, context: TContext, initialState: InitialState, middlewares?: Middleware[] ) { super(); this.dispatcher = dispatcher; this.storeInstances = {}; this.storeUnsubscribeCallbacks = {}; this.context = context; this.dispatcherInterface = { getContext: () => this.context, getStore: this.getStore.bind(this), }; this.rehydratedStoreState = {}; this.fullState = {}; // Заполняем стейт данными if (initialState) { this.rehydrate(initialState); } if (middlewares) { this.applyDispatch = this.applyMiddlewares(middlewares); } // Инцииализируем уже имеющиеся сторы Object.keys(this.dispatcher.stores).forEach((store) => { this.getStore(store); }); } applyMiddlewares(middlewares: Middleware[]) { let dispatch = (...args: any[]) => { throw new Error( 'Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.' ); }; const api = { getState: this.getState.bind(this), subscribe: this.subscribe.bind(this), dispatch: (...args: any[]) => dispatch(...args), }; dispatch = compose(...middlewares.map((middleware) => middleware(api)))(this.applyDispatch); return dispatch; } /** * @deprecated * * Returns a single store instance and creates one if it doesn't already exist * @param storeClass The name of the instance * @returns The store instance * @throws {Error} if store is not registered */ getStore<T extends StoreClass>(storeClass: { store: T | string; optional: true; }): InstanceType<T> | null; getStore<T extends StoreClass>(storeClass: T | string): InstanceType<T>; getStore<T extends StoreClass>( storeClass: T | string | { store: T | string; optional: true } ): InstanceType<T> | null; // eslint-disable-next-line max-statements getStore<T extends StoreClass>( storeClass: T | string | { store: T | string; optional: true } ): InstanceType<T> | null { let storeClassPrepared; let optional = false; if (typeof storeClass === 'object') { storeClassPrepared = storeClass.store; optional = storeClass.optional; } else { storeClassPrepared = storeClass; } const storeName = this.dispatcher.getStoreName(storeClassPrepared); if (!this.storeInstances[storeName]) { let Store = this.dispatcher.stores[storeName]; if (!Store) { if (typeof storeClassPrepared === 'function') { this.dispatcher.registerStore(storeClassPrepared); Store = storeClassPrepared; } else { if (optional) { return null; } throw new Error(`Store ${storeName} was not registered.`); } } const storeInstance = new Store(this.dispatcherInterface); this.storeInstances[storeName] = storeInstance; if (this.rehydratedStoreState && this.rehydratedStoreState[storeName]) { const state = this.rehydratedStoreState[storeName]; if (storeInstance.rehydrate) { storeInstance.rehydrate(state); } this.rehydratedStoreState[storeName] = null; } const subscribeHandler = () => { const newState = storeInstance.getState(); if (newState !== this.fullState[storeName]) { this.fullState = { ...this.fullState, [storeName]: newState, }; this.emit('change'); } }; subscribe(storeInstance, subscribeHandler); const unsubscribe = () => { storeInstance.off('change', subscribeHandler); }; this.storeUnsubscribeCallbacks[storeName] = unsubscribe; // TODO: убрать после того отпадёт надобность связывать сторы router и application if (Store.dependencies) { Store.dependencies.forEach((dependencyStoreClass) => { const dependency = this.getStore(dependencyStoreClass); subscribe(dependency, () => { storeInstance.emit('change'); }); }); } } return this.storeInstances[storeName]; } /** * Dispatches a new action or throws if one is already in progress * @param eventOrType Name of the event to be dispatched * @param payload Parameters to describe the action * @throws {Error} if store has handler registered that does not exist */ dispatch<Payload>(eventOrType: string | Event<Payload>, payload?: Payload) { if (!eventOrType) { throw new Error(`eventOrType parameter ${eventOrType} is invalid.`); } // конвертим старый тип экшенов const event: Event<Payload> = convertAction(eventOrType, payload); return this.applyDispatch(event); } applyHandlers<P>(action: Event<P>, handlers: Handlers[string]) { const handlerFns: Record<string, Function> = {}; const storeInstanceGet = (store: StoreHandler) => { if (handlerFns[store.name]) { // Don't call the default if the store has an explicit action handler return; } const storeInstance = this.getStore(store.name); if (!storeInstance) { return; } if (typeof store.handler === 'function') { handlerFns[store.name] = store.handler.bind(storeInstance); } else { if (process.env.NODE_ENV !== 'production') { if (!storeInstance[store.handler]) { throw new Error(`${store.name} does not have a method called ${store.handler}`); } } handlerFns[store.name] = storeInstance[store.handler].bind(storeInstance); } }; const handlersLength = handlers.length; for (let index = 0; index < handlersLength; index++) { storeInstanceGet(handlers[index]); } return eventExecutor(action, handlerFns); } /** * Returns a raw data object representation of the current state of the * dispatcher and all store instances. If the store implements a shouldDehdyrate * function, then it will be called and only dehydrate if the method returns `true` * @method dehydrate * @returns dehydrated dispatcher data */ dehydrate() { const stores: Record<string, any> = {}; const keys = Object.keys(this.storeInstances); for (let i = 0; i < keys.length; i++) { const storeName = keys[i]; const store = this.storeInstances[storeName]; if (!store.dehydrate()) { continue; } stores[storeName] = store.dehydrate(); } return { stores, }; } /** * Takes a raw data object and rehydrates the dispatcher and store instances * @method rehydrate * @param dispatcherState raw state typically retrieved from `dehydrate` method */ rehydrate(dispatcherState: InitialState) { if (dispatcherState.stores) { const keys = Object.keys(dispatcherState.stores); for (let index = 0; index < keys.length; index++) { const storeName = keys[index]; this.rehydratedStoreState[storeName] = dispatcherState.stores[storeName]; } } } subscribe(callback: (state: Record<string, any>) => void): () => void; subscribe<S>(reducer: Reducer<S>, callback: (state: S) => void): () => void; subscribe( ...args: [(state: Record<string, any>) => void] | [Reducer<any>, (state: any) => void] ): () => void { if ('storeName' in args[0]) { const reducer = args[0]; const callback = args[1]; const reducerInstance = this.storeInstances[reducer.storeName]; const listener = () => { const state = this.getState(reducer); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion callback!(state); }; reducerInstance.on('change', listener); return () => { reducerInstance.off('change', listener); }; } const callback = args[0]; const listener = () => { const state = this.getState(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion callback!(state); }; this.on('change', listener); return () => { this.off('change', listener); }; } getState(): Record<string, any>; getState<S>(reducer: Reducer<S>): S; getState(reducer?: Reducer<any>): any { if (reducer) { return this.fullState[reducer.storeName]; } return this.fullState; } // Для отложенной инициализации контекста, в будующем нужно удалить setContext(context: TContext) { this.context = context; } hasStore(store: Reducer<any>) { return store.storeName in this.storeInstances && this.dispatcher.hasStore(store); } registerStore(store: Reducer<any>) { this.dispatcher.registerStore(store); this.getStore(store); } unregisterStore(store: Reducer<any>) { const { storeName } = store; this.dispatcher.unregisterStore(store); this.storeUnsubscribeCallbacks[storeName](); delete this.storeUnsubscribeCallbacks[storeName]; delete this.rehydratedStoreState[storeName]; delete this.storeInstances[storeName]; } }
the_stack
import { Maybe, Just, Nothing, MaybePatterns } from './Maybe' import { EitherAsync } from './EitherAsync' export interface MaybeAsyncTypeRef { /** Constructs a MaybeAsync object from a function that takes an object full of helpers that let you lift things into the MaybeAsync context and returns a Promise */ <T>(runPromise: (helpers: MaybeAsyncHelpers) => PromiseLike<T>): MaybeAsync<T> /** Constructs an MaybeAsync object from a function that returns a Maybe wrapped in a Promise */ fromPromise<T>(f: () => Promise<Maybe<T>>): MaybeAsync<T> /** Constructs an MaybeAsync object from a Maybe */ liftMaybe<T>(maybe: Maybe<T>): MaybeAsync<T> /** Takes a list of `MaybeAsync`s and returns a Promise that will resolve with all `Just` values. Internally it uses `Promise.all` to wait for all results */ catMaybes<T>(list: MaybeAsync<T>[]): Promise<T[]> } export interface MaybeAsync<T> extends PromiseLike<Maybe<T>> { /** * It's important to remember how `run` will behave because in an * async context there are other ways for a function to fail other * than to return a Nothing, for example: * If any of the computations inside MaybeAsync resolved to Nothing, * `run` will return a Promise resolved to Nothing. * If any of the promises were to be rejected then `run` will return * a Promise resolved to Nothing. * If an exception is thrown then `run` will return a Promise * resolved to Nothing. * If none of the above happen then a promise resolved to the * returned value wrapped in a Just will be returned. */ run(): Promise<Maybe<T>> /** Transforms the value inside `this` with a given function. If the MaybeAsync that is being mapped resolves to Nothing then the mapping function won't be called and `run` will resolve the whole thing to Nothing, just like the regular Maybe#map */ map<U>(f: (value: T) => U): MaybeAsync<U> /** Transforms `this` with a function that returns a `MaybeAsync`. Behaviour is the same as the regular Maybe#chain */ chain<U>(f: (value: T) => PromiseLike<Maybe<U>>): MaybeAsync<U> /** Converts `this` to a EitherAsync with a default error value */ toEitherAsync<L>(error: L): EitherAsync<L, T> /** Runs an effect if `this` is `Just`, returns `this` to make chaining other methods possible */ ifJust(effect: (value: T) => any): MaybeAsync<T> /** Runs an effect if `this` is `Nothing`, returns `this` to make chaining other methods possible */ ifNothing(effect: () => any): MaybeAsync<T> /** Returns the default value if `this` is `Nothing`, otherwise it returns a Promise that will resolve to the value inside `this` */ orDefault(defaultValue: T): Promise<T> /** Maps the future value of `this` with another future `Maybe` function */ ap<U>(maybeF: PromiseLike<Maybe<(value: T) => U>>): MaybeAsync<U> /** Returns the first `Just` between the future value of `this` and another future `Maybe` or future `Nothing` if both `this` and the argument are `Nothing` */ alt(other: MaybeAsync<T>): MaybeAsync<T> /** Returns `this` if it resolves to `Nothing`, otherwise it returns the result of applying the function argument to the value of `this` and wrapping it in a `Just` */ extend<U>(f: (value: MaybeAsync<T>) => U): MaybeAsync<U> /** Takes a predicate function and returns `this` if the predicate, applied to the resolved value, is true or Nothing if it's false */ filter<U extends T>(pred: (value: T) => value is U): MaybeAsync<U> /** Takes a predicate function and returns `this` if the predicate, applied to the resolved value, is true or Nothing if it's false */ filter(pred: (value: T) => boolean): MaybeAsync<T> /** Flattens nested `MaybeAsync`s. `m.join()` is equivalent to `m.chain(x => x)` */ join<U>(this: MaybeAsync<MaybeAsync<U>>): MaybeAsync<U> /** Useful if you are not interested in the result of an operation */ void(): MaybeAsync<void> /** Structural pattern matching for `MaybeAsync` in the form of a function */ caseOf<U>(patterns: MaybePatterns<T, U>): Promise<U> /* Similar to the Promise method of the same name, the provided function is called when the `MaybeAsync` is executed regardless of whether the `Maybe` result is `Nothing` or `Just` */ finally(effect: () => any): MaybeAsync<T> 'fantasy-land/map'<U>(f: (value: T) => U): MaybeAsync<U> 'fantasy-land/chain'<U>(f: (value: T) => PromiseLike<Maybe<U>>): MaybeAsync<U> 'fantasy-land/ap'<U>(maybeF: MaybeAsync<(value: T) => U>): MaybeAsync<U> 'fantasy-land/alt'(other: MaybeAsync<T>): MaybeAsync<T> 'fantasy-land/extend'<U>(f: (value: MaybeAsync<T>) => U): MaybeAsync<U> 'fantasy-land/filter'<U extends T>( pred: (value: T) => value is U ): MaybeAsync<U> 'fantasy-land/filter'(pred: (value: T) => boolean): MaybeAsync<T> /** WARNING: This is implemented only for Promise compatibility. Please use `chain` instead. */ then: PromiseLike<Maybe<T>>['then'] } export interface MaybeAsyncValue<T> extends PromiseLike<T> {} export interface MaybeAsyncHelpers { /** Allows you to take a regular Maybe value and lift it to the MaybeAsync context. Awaiting a lifted Maybe will give you the value inside. If the Maybe is Nothing then the function will exit immediately and MaybeAsync will resolve to Nothing after running it */ liftMaybe<T>(maybe: Maybe<T>): MaybeAsyncValue<T> /** Allows you to take a Maybe inside a Promise and lift it to the MaybeAsync context. Awaiting a lifted Promise<Maybe> will give you the value inside the Maybe. If the Maybe is Nothing or the Promise is rejected then the function will exit immediately and MaybeAsync will resolve to Nothing after running it */ fromPromise<T>(promise: PromiseLike<Maybe<T>>): MaybeAsyncValue<T> } const helpers: MaybeAsyncHelpers = { liftMaybe<T>(maybe: Maybe<T>): MaybeAsyncValue<T> { if (maybe.isJust()) { return Promise.resolve(maybe.extract()) } throw Nothing }, fromPromise<T>(promise: PromiseLike<Maybe<T>>): MaybeAsyncValue<T> { return promise.then(helpers.liftMaybe) as MaybeAsyncValue<T> } } class MaybeAsyncImpl<T> implements MaybeAsync<T> { [Symbol.toStringTag]: 'MaybeAsync' = 'MaybeAsync' constructor( private runPromise: (helpers: MaybeAsyncHelpers) => PromiseLike<T> ) {} orDefault(defaultValue: T): Promise<T> { return this.run().then((x) => x.orDefault(defaultValue)) } join<U>(this: MaybeAsync<MaybeAsync<U>>): MaybeAsync<U> { return MaybeAsync(async (helpers) => { const maybe = await this.run() if (maybe.isJust()) { const nestedMaybe = await maybe.extract() return helpers.liftMaybe(nestedMaybe) } return helpers.liftMaybe(Nothing as Maybe<U>) }) } ap<U>(maybeF: MaybeAsync<(value: T) => U>): MaybeAsync<U> { return MaybeAsync(async (helpers) => { const otherValue = await maybeF if (otherValue.isJust()) { const thisValue = await this if (thisValue.isJust()) { return otherValue.extract()(thisValue.extract()) } else { return helpers.liftMaybe(Nothing as Maybe<U>) } } return helpers.liftMaybe(Nothing as Maybe<U>) }) } alt(other: MaybeAsync<T>): MaybeAsync<T> { return MaybeAsync(async (helpers) => { const thisValue = await this if (thisValue.isJust()) { return thisValue.extract() } else { const otherValue = await other return helpers.liftMaybe(otherValue) } }) } extend<U>(f: (value: MaybeAsync<T>) => U): MaybeAsync<U> { return MaybeAsync(async (helpers) => { const maybe = await this.run() if (maybe.isJust()) { const v = MaybeAsync.liftMaybe(maybe as any as Maybe<T>) return helpers.liftMaybe(Just(f(v))) } return helpers.liftMaybe(Nothing as any as Maybe<U>) }) } filter<U extends T>(pred: (value: T) => value is U): MaybeAsync<U> filter(pred: (value: T) => boolean): MaybeAsync<T> filter(pred: (value: T) => boolean) { return MaybeAsync(async (helpers) => { const value = await this.run() return helpers.liftMaybe(value.filter(pred)) }) } async run(): Promise<Maybe<T>> { try { return Just(await this.runPromise(helpers)) } catch { return Nothing } } map<U>(f: (value: T) => U): MaybeAsync<U> { return MaybeAsync((helpers) => this.runPromise(helpers).then(f)) } chain<U>(f: (value: T) => PromiseLike<Maybe<U>>): MaybeAsync<U> { return MaybeAsync(async (helpers) => { const value = await this.runPromise(helpers) return helpers.fromPromise(f(value)) }) } toEitherAsync<L>(error: L): EitherAsync<L, T> { return EitherAsync(async ({ liftEither }) => { const maybe = await this.run() return liftEither(maybe.toEither(error)) }) } ifJust(effect: (value: T) => any): MaybeAsync<T> { return MaybeAsync(async (helpers) => { const maybe = await this.run() maybe.ifJust(effect) return helpers.liftMaybe(maybe) }) } ifNothing(effect: () => any): MaybeAsync<T> { return MaybeAsync(async (helpers) => { const maybe = await this.run() maybe.ifNothing(effect) return helpers.liftMaybe(maybe) }) } void(): MaybeAsync<void> { return this.map((_) => {}) } caseOf<U>(patterns: MaybePatterns<T, U>): Promise<U> { return this.run().then((x) => x.caseOf(patterns)) } finally(effect: () => any): MaybeAsync<T> { return MaybeAsync(({ fromPromise }) => fromPromise(this.run().finally(effect)) ) } 'fantasy-land/map' = this.map 'fantasy-land/chain' = this.chain 'fantasy-land/ap' = this.ap 'fantasy-land/filter' = this.filter 'fantasy-land/extend' = this.extend 'fantasy-land/alt' = this.alt then<TResult1 = Maybe<T>, TResult2 = never>( onfulfilled?: | ((value: Maybe<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: | ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null ): PromiseLike<TResult1 | TResult2> { return this.run().then(onfulfilled, onrejected) } } export const MaybeAsync: MaybeAsyncTypeRef = Object.assign( <T>( runPromise: (helpers: MaybeAsyncHelpers) => PromiseLike<T> ): MaybeAsync<T> => new MaybeAsyncImpl(runPromise), { catMaybes: <T>(list: MaybeAsync<T>[]): Promise<T[]> => Promise.all(list).then(Maybe.catMaybes), fromPromise: <T>(f: () => Promise<Maybe<T>>): MaybeAsync<T> => MaybeAsync(({ fromPromise: fP }) => fP(f())), liftMaybe: <T>(maybe: Maybe<T>): MaybeAsync<T> => MaybeAsync(({ liftMaybe }) => liftMaybe(maybe)) } ) MaybeAsyncImpl.prototype.constructor = MaybeAsync
the_stack
import { Stark as IStark, Assertion, StarkProof, StarkOptions, SecurityOptions, Logger } from '@guildofweavers/genstark'; import { MerkleTree, Hash, HashAlgorithm, createHash } from '@guildofweavers/merkle'; import { AirModule, Vector, Matrix, AirSchema, instantiate, WasmOptions } from '@guildofweavers/air-assembly'; import { CompositionPolynomial, LowDegreeProver, LinearCombination, QueryIndexGenerator } from './components'; import { sizeOf, powLog2, readBigInt, rehashMerkleProofValues, noop } from './utils'; import { Serializer } from './Serializer'; import { StarkError } from './StarkError'; // MODULE VARIABLES // ================================================================================================ const DEFAULT_EXE_QUERY_COUNT = 80; const DEFAULT_FRI_QUERY_COUNT = 40; const MAX_EXE_QUERY_COUNT = 128; const MAX_FRI_QUERY_COUNT = 64; const HASH_ALGORITHMS: HashAlgorithm[] = ['sha256', 'blake2s256']; const DEFAULT_HASH_ALGORITHM: HashAlgorithm = 'sha256'; // CLASS DEFINITION // ================================================================================================ export class Stark implements IStark { readonly air : AirModule; readonly hash : Hash; readonly indexGenerator : QueryIndexGenerator; readonly serializer : Serializer; readonly logger : Logger; // CONSTRUCTOR // -------------------------------------------------------------------------------------------- constructor(schema: AirSchema, component: string, options: Partial<StarkOptions> = {}, logger: Logger) { const wasmOptions = buildWasmOptions(options.wasm); // instantiate AIR module this.air = instantiate(schema, component, { extensionFactor: options.extensionFactor, wasmOptions }); if (wasmOptions && !this.air.field.isOptimized) { console.warn(`WARNING: WebAssembly optimization is not available for the specified field`); } // build security options const sOptions = buildSecurityOptions(options, this.air.extensionFactor); // instantiate Hash object const useWasm = (wasmOptions !== undefined) || this.air.field.isOptimized; this.hash = createHash(sOptions.hashAlgorithm, useWasm); if (!this.hash.isOptimized) { console.warn(`WARNING: WebAssembly optimization is not available for ${sOptions.hashAlgorithm} hash algorithm`); }; this.indexGenerator = new QueryIndexGenerator(sOptions); this.serializer = new Serializer(this.air, this.hash.digestSize); this.logger = logger; } // ACCESSORS // -------------------------------------------------------------------------------------------- get securityLevel(): number { const extensionFactor = this.air.extensionFactor; // execution trace security const exeQueryCount = this.indexGenerator.exeQueryCount; const es = powLog2(extensionFactor / this.air.maxConstraintDegree, exeQueryCount); // FRI proof security const friQueryCount = this.indexGenerator.friQueryCount; const fs = Math.log2(extensionFactor) * friQueryCount; // collision resistance of hash function const hs = this.hash.digestSize * 4; return Math.floor(Math.min(es, fs, hs)); } // PROVER // -------------------------------------------------------------------------------------------- prove(assertions: Assertion[], inputs?: any[], seed?: bigint[]): StarkProof { const log = this.logger.start('Starting STARK computation'); // 0 ----- validate parameters if (!Array.isArray(assertions)) throw new TypeError('Assertions parameter must be an array'); if (assertions.length === 0) throw new TypeError('At least one assertion must be provided'); // 1 ----- set up evaluation context const context = this.air.initProvingContext(inputs, seed); const evaluationDomainSize = context.evaluationDomain.length; log('Set up evaluation context'); // 2 ----- generate execution trace and make sure it is correct let executionTrace: Matrix; try { executionTrace = context.generateExecutionTrace(); validateAssertions(executionTrace, assertions); } catch (error) { throw new StarkError(`Failed to generate the execution trace`, error); } log('Generated execution trace'); // 3 ----- compute P(x) polynomials and low-degree extend them const pPolys = context.field.interpolateRoots(context.executionDomain, executionTrace); log('Computed execution trace polynomials P(x)'); const pEvaluations = context.field.evalPolysAtRoots(pPolys, context.evaluationDomain); log('Low-degree extended P(x) polynomials over evaluation domain'); // 4 ----- build merkle tree for evaluations of P(x) and S(x) const sEvaluations = context.secretRegisterTraces; const eVectors = [...context.field.matrixRowsToVectors(pEvaluations), ...sEvaluations]; const hashedEvaluations = this.hash.mergeVectorRows(eVectors); log('Serialized evaluations of P(x) and S(x) polynomials'); const eTree = MerkleTree.create(hashedEvaluations, this.hash); log('Built evaluation merkle tree'); // 5 ----- compute composition polynomial C(x) const cLogger = this.logger.sub('Computing composition polynomial'); const cPoly = new CompositionPolynomial(assertions, eTree.root, context, cLogger); const cEvaluations = cPoly.evaluateAll(pPolys, pEvaluations, context); this.logger.done(cLogger); log('Computed composition polynomial C(x)'); // 6 ---- compute random linear combination of evaluations const lCombination = new LinearCombination(eTree.root, cPoly.compositionDegree, cPoly.coefficientCount, context); const lEvaluations = lCombination.computeMany(cEvaluations, pEvaluations, sEvaluations); log('Combined P(x) and S(x) evaluations with C(x) evaluations'); // 7 ----- Compute low-degree proof let ldProof; try { const ldLogger = this.logger.sub('Computing low degree proof'); const ldProver = new LowDegreeProver(this.indexGenerator, this.hash, context, ldLogger); ldProof = ldProver.prove(lEvaluations, context.evaluationDomain, cPoly.compositionDegree); this.logger.done(ldLogger); log('Computed low-degree proof'); } catch (error) { throw new StarkError('Low degree proof failed', error); } // 8 ----- query evaluation tree at pseudo-random positions const positions = this.indexGenerator.getExeIndexes(ldProof.lcRoot, evaluationDomainSize); const augmentedPositions = this.getAugmentedPositions(positions, evaluationDomainSize); const eValues = this.mergeValues(eVectors, augmentedPositions); const eProof = eTree.proveBatch(augmentedPositions); eProof.values = eValues; log(`Computed ${positions.length} evaluation spot checks`); this.logger.done(log, 'STARK computed'); // build and return the proof object return { evRoot : eTree.root, evProof : eProof, ldProof : ldProof, iShapes : context.inputShapes }; } // VERIFIER // -------------------------------------------------------------------------------------------- verify(assertions: Assertion[], proof: StarkProof, publicInputs?: any[]) { const log = this.logger.start('Starting STARK verification'); // 0 ----- validate parameters if (assertions.length < 1) throw new TypeError('At least one assertion must be provided'); // 1 ----- set up evaluation context const eRoot = proof.evRoot; const extensionFactor = this.air.extensionFactor; const context = this.air.initVerificationContext(proof.iShapes, publicInputs); const evaluationDomainSize = context.traceLength * extensionFactor; const cPoly = new CompositionPolynomial(assertions, eRoot, context, noop); const lCombination = new LinearCombination(eRoot, cPoly.compositionDegree, cPoly.coefficientCount, context); log('Set up evaluation context'); // 2 ----- compute positions for evaluation spot-checks const positions = this.indexGenerator.getExeIndexes(proof.ldProof.lcRoot, evaluationDomainSize); const augmentedPositions = this.getAugmentedPositions(positions, evaluationDomainSize); log(`Computed positions for evaluation spot checks`); // 3 ----- decode evaluation spot-checks const pEvaluations = new Map<number, bigint[]>(); const sEvaluations = new Map<number, bigint[]>(); for (let i = 0; i < proof.evProof.values.length; i++) { let mergedEvaluations = proof.evProof.values[i]; let position = augmentedPositions[i]; let [p, s] = this.parseValues(mergedEvaluations); pEvaluations.set(position, p); sEvaluations.set(position, s); } log(`Decoded evaluation spot checks`); // 4 ----- verify merkle proof for evaluation tree try { const evProof = rehashMerkleProofValues(proof.evProof, this.hash); if (!MerkleTree.verifyBatch(eRoot, augmentedPositions, evProof, this.hash)) { throw new StarkError(`Verification of evaluation Merkle proof failed`); } } catch (error) { if (error instanceof StarkError === false) { error = new StarkError(`Verification of evaluation Merkle proof failed`, error); } throw error; } log(`Verified evaluation merkle proof`); // 5 ----- compute linear combinations of C, P, and S values for all spot checks const lcValues = new Array<bigint>(positions.length); for (let i = 0; i < positions.length; i++) { let step = positions[i]; let x = context.field.exp(context.rootOfUnity, BigInt(step)); let pValues = pEvaluations.get(step)!; let nValues = pEvaluations.get((step + extensionFactor) % evaluationDomainSize)!; let sValues = sEvaluations.get(step)!; // evaluate composition polynomial at x let cValue = cPoly.evaluateAt(x, pValues, nValues, sValues, context); // combine composition polynomial evaluation with values of P(x) and S(x) lcValues[i] = lCombination.computeOne(x, cValue, pValues, sValues); } log(`Verified transition and boundary constraints`); // 6 ----- verify low-degree proof try { const ldProver = new LowDegreeProver(this.indexGenerator, this.hash, context, noop); ldProver.verify(proof.ldProof, lcValues, positions, cPoly.compositionDegree); } catch (error) { throw new StarkError('Verification of low degree failed', error); } log(`Verified low-degree proof`); this.logger.done(log, 'STARK verified'); return true; } // UTILITIES // -------------------------------------------------------------------------------------------- generateExecutionTrace(inputs?: any[], seed?: bigint[]): { dTrace: Matrix, sTrace: Matrix } { const context = this.air.initProvingContext(inputs, seed); const dTrace = context.generateExecutionTrace(); const sTrace = context.generateStaticTrace(); return { dTrace, sTrace }; } sizeOf(proof: StarkProof): number { const size = sizeOf(proof, this.air.field.elementSize, this.hash.digestSize); return size.total; } serialize(proof: StarkProof) { return this.serializer.serializeProof(proof); } parse(buffer: Buffer): StarkProof { return this.serializer.parseProof(buffer); } // HELPER METHODS // -------------------------------------------------------------------------------------------- private getAugmentedPositions(positions: number[], evaluationDomainSize: number): number[] { const skip = this.air.extensionFactor; const augmentedPositionSet = new Set<number>(); for (let i = 0; i < positions.length; i++) { augmentedPositionSet.add(positions[i]); augmentedPositionSet.add((positions[i] + skip) % evaluationDomainSize); } return Array.from(augmentedPositionSet); } private mergeValues(values: Vector[], positions: number[]): Buffer[] { const bufferSize = values.length * this.air.field.elementSize; const result: Buffer[] = []; for (let position of positions) { let buffer = Buffer.allocUnsafe(bufferSize), offset = 0; for (let vector of values) { offset += vector.copyValue(position, buffer, offset); } result.push(buffer); } return result; } private parseValues(buffer: Buffer): [bigint[], bigint[]] { const elementSize = this.air.field.elementSize; let offset = 0; const pValues = new Array<bigint>(this.air.traceRegisterCount); for (let i = 0; i < pValues.length; i++, offset += elementSize) { pValues[i] = readBigInt(buffer, offset, elementSize); } const sValues = new Array<bigint>(this.air.secretInputCount); for (let i = 0; i < sValues.length; i++, offset += elementSize) { sValues[i] = readBigInt(buffer, offset, elementSize); } return [pValues, sValues]; } } // HELPER FUNCTIONS // ================================================================================================ function buildSecurityOptions(options: Partial<StarkOptions> | undefined, extensionFactor: number): SecurityOptions { // execution trace spot checks const exeQueryCount = (options ? options.exeQueryCount : undefined) || DEFAULT_EXE_QUERY_COUNT; if (exeQueryCount < 1 || exeQueryCount > MAX_EXE_QUERY_COUNT || !Number.isInteger(exeQueryCount)) { throw new TypeError(`Execution sample size must be an integer between 1 and ${MAX_EXE_QUERY_COUNT}`); } // low degree evaluation spot checks const friQueryCount = (options ? options.friQueryCount : undefined) || DEFAULT_FRI_QUERY_COUNT; if (friQueryCount < 1 || friQueryCount > MAX_FRI_QUERY_COUNT || !Number.isInteger(friQueryCount)) { throw new TypeError(`FRI sample size must be an integer between 1 and ${MAX_FRI_QUERY_COUNT}`); } // hash function const hashAlgorithm = (options ? options.hashAlgorithm : undefined) || DEFAULT_HASH_ALGORITHM; if (!HASH_ALGORITHMS.includes(hashAlgorithm)) { throw new TypeError(`Hash algorithm ${hashAlgorithm} is not supported`); } // extension factor if (!extensionFactor) { throw new TypeError(`Extension factor is undefined`); } return { extensionFactor, exeQueryCount, friQueryCount, hashAlgorithm }; } function buildWasmOptions(useWasm?: boolean): WasmOptions | undefined { if (useWasm === false) return undefined; return { memory : new WebAssembly.Memory({ initial: 512, // 32 MB maximum: 32768 // 2 GB }) }; } function validateAssertions(trace: Matrix, assertions: Assertion[]) { const registers = trace.rowCount; const steps = trace.colCount; for (let a of assertions) { // make sure register references are correct if (a.register < 0 || a.register >= registers) { throw new Error(`Invalid assertion: register ${a.register} is outside of register bank`); } // make sure steps are correct if (a.step < 0 || a.step >= steps) { throw new Error(`Invalid assertion: step ${a.step} is outside of execution trace`); } // make sure assertions don't contradict execution trace if (trace.getValue(a.register, a.step) !== a.value) { throw new StarkError(`Assertion at step ${a.step}, register ${a.register} conflicts with execution trace`); } } }
the_stack
import { Mongo } from 'meteor/mongo'; import { Helper, OptionalHelper, Data, Full, Helpers, AllowPartial, } from 'meteor/dburles:collection-helpers'; interface Author { _id?: string | undefined; firstName: string; lastName: string; // function properties are automatically detected as helpers; no need to specify fullName: () => string; books: () => Mongo.Cursor<Book>; } interface Book { _id?: string | undefined; authorId: string; name: string; author: () => Author | undefined; // use Helper<T> to declare non-function helpers foo: Helper<string>; } const Books = new Mongo.Collection<Book>('books'); const Authors = new Mongo.Collection<Author>('authors'); // $ExpectType Collection<Book, Book> Books; // when inserting items, only data properties are required const author1 = Authors.insert({ firstName: 'Charles', lastName: 'Darwin', }); const author2 = Authors.insert({ firstName: 'Carl', lastName: 'Sagan', }); const book1 = Books.insert({ authorId: author1, name: 'On the Origin of Species', }); const book2 = Books.insert({ authorId: author2, name: 'Contact', }); // when providing helpers, no data properties but all helpers are required // all helpers must be provided at once; this is the only way to typecheck that none are forgotten // $ExpectType void Books.helpers({ author() { return Authors.findOne(this.authorId); }, foo: 'bar', }); // $ExpectError Books.helpers({ author() { return Authors.findOne(this.authorId); }, }); // you can override this behavior if you explicitly request to // (don't do this unless you intend to provide all the helpers sooner or later!) // $ExpectType void Authors.helpers<AllowPartial>({ fullName() { return `${this.firstName} ${this.lastName}`; }, }); // $ExpectType void Authors.helpers<AllowPartial>({ books() { return Books.find({ authorId: this._id }); }, }); const book = Books.findOne(book1)!; const author: Author | undefined = book.author(); // can modify resulting Book and update Books with it, even though it has helpers attached book.name = 'Renamed Book'; // $ExpectType number Books.update(book._id!, book); // with mandatory helpers, new objects can be declared directly as Data<T> const bookData: Data<Book> = { authorId: 'Author', name: 'Name', }; // this interface has its helpers declared as optional; this makes instantiating the interface easier, // but means you need to specify Full<T> to say an object has had its helpers attached interface OptionalHelpers { _id: string; value: number; increment?: (() => void) | undefined; zero?: Helper<number> | undefined; } const optionalHelpers = new Mongo.Collection<OptionalHelpers>('optionalHelpers'); // optional helpers still have to be provided when calling helpers // $ExpectError optionalHelpers.helpers({}); // $ExpectError optionalHelpers.helpers({ increment() { this.value++; }, }); // $ExpectType void optionalHelpers.helpers({ increment() { this.value++; }, zero: 0, }); const optionalHelper1 = optionalHelpers.insert({ value: 2 }); // Helpers are still guaranteed on the results of findOne, even though helpers were declared optional // $ExpectType void optionalHelpers.findOne(optionalHelper1)!.increment(); // same goes for find // $ExpectType void optionalHelpers.find(optionalHelper1).fetch()[0].increment(); const foundOptionalHelpers1: OptionalHelpers = optionalHelpers.findOne(optionalHelper1)!; // however, variables of the interface type will be missing their helpers unless declared as Full<T> // $ExpectError foundOptionalHelpers1.increment(); // you can do this, but it's kinda ugly imo const foundOptionalHelpers1Full: Full<OptionalHelpers> = optionalHelpers.findOne(optionalHelper1)!; // $ExpectType void foundOptionalHelpers1Full.increment(); // the benefit of this declaration style is that you can pass around instances without ever putting them in a collection: const takesOptionalHelpers = (arg: OptionalHelpers) => { return arg.value; }; const literalOptHelp: OptionalHelpers = { _id: "id", value: 4, }; // $ExpectType number takesOptionalHelpers(literalOptHelp); // $ExpectType number takesOptionalHelpers({ _id: "another id", value: 13 }); // this might be a better choice if your interface is a general data type that you just happen to put in collections sometimes, // rather than a collection schema you work with retrieved instances of often // helpers can call themselves recursively interface RecursiveHelpers { _id: string; value: number; factorial: (arg: number) => number; } const recursiveHelpers = new Mongo.Collection<RecursiveHelpers>('recursiveHelpers'); recursiveHelpers.helpers({ factorial(x) { if (x <= 1) return 1; return this.factorial(x - 1); }, }); const rh1 = recursiveHelpers.insert({ value: 3 }); // $ExpectType number recursiveHelpers.findOne(rh1)!.factorial(4); // even when optional! interface RecursiveOptionalHelpers { _id: string; value: number; factorial?: ((arg: number) => number) | undefined; } const recursiveOptionalHelpers = new Mongo.Collection<RecursiveHelpers>('recursiveHelpers'); recursiveHelpers.helpers({ factorial(x) { if (x <= 1) return 1; return this.factorial(x - 1); }, }); const roh1 = recursiveOptionalHelpers.insert({ value: 3 }); // $ExpectType number recursiveHelpers.findOne(rh1)!.factorial(4); // regression test: // { ...OptionalId<Data<T>>, _id: T['id'] } should be assignable to Data<T> // (tested here with upsert) interface MandatoryId { _id: string; value: number; } const mandatoryIds = new Mongo.Collection<MandatoryId>('mandatoryIds'); mandatoryIds.helpers({}); const withoutId: Mongo.OptionalId<MandatoryId> = { value: 3, }; // $ExpectType number | undefined mandatoryIds.upsert('new ID', { ...withoutId, _id: 'new ID' }).numberAffected; // regression test: // union properties on interfaces: // - are helpers if all their members are helpers // - aren't helpers if none of their members are helpers // - may or may not be helpers if only some of their members are helpers // (consider this undefined behavior; I don't think there's *any* correct behavior // for this situation, so I'm just letting it work out however it does without intervention) // unions of Helper<T> and unmarked methods don't work; if you legitimately need this functionality, // tell me and I'll fix it; use Helper<T | YourMethodType> as a workaround until then // // null does not count as a helper type // however, Helper<null> and Helper<T | null> should work more or less correctly interface ComplicatedMembers { _id?: string | undefined; nullable: number | null; alwaysNull: null; helperNull: Helper<null>; helperNumber: Helper<number>; helperNullableFalse: Helper<false | null>; optionalHelperString?: Helper<string> | undefined; // tslint:disable-next-line void-return helperVoidableNumber: Helper<number | void>; methodUnion: (() => boolean) | ((arg: number) => boolean); helperUnion: Helper<string> | Helper<number>; nonHelperUnion: number | string; helperMethodOrString: Helper<(() => string) | string>; } const complicatedMembers = new Mongo.Collection<ComplicatedMembers>('complicatedMembers'); // every member recognized as a helper is required when providing helpers // $ExpectType void complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperNull: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperNull: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperNumber: 5, helperNullableFalse: null, helperNull: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNullableFalse: null, helperNull: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNull: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperNull: null, helperVoidableNumber: undefined, helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperVoidableNumber: undefined, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperNull: null, optionalHelperString: 'foo', helperMethodOrString: () => "method", }); // $ExpectError complicatedMembers.helpers({ methodUnion: () => true, helperUnion: 3, helperNumber: 5, helperNullableFalse: null, helperVoidableNumber: undefined, helperNull: null, optionalHelperString: 'foo', }); const complicatedMembersId = complicatedMembers.insert({ nullable: 2, alwaysNull: null, nonHelperUnion: 'test', }); const complicatedMembersInstance = complicatedMembers.findOne(complicatedMembersId)!; // $ExpectType number complicatedMembersInstance.helperNumber + 1; // $ExpectType string complicatedMembersInstance.optionalHelperString.slice(); // $ExpectType boolean complicatedMembersInstance.methodUnion(3); const strOrNum: string | number = complicatedMembersInstance.helperUnion; const falseOrNull: false | null = complicatedMembersInstance.helperNullableFalse; const helperNullAccess: null = complicatedMembersInstance.helperNull; // Limitation: null/undefined helpers, and helpers whose types are unions with null or undefined, can't be properly // read off a raw ComplicatedMembers const asComplicatedMembers: ComplicatedMembers = complicatedMembersInstance; // const falseOrNull2 : false | null = asComplicatedMembers.helperNullableFalse; // you can work with these by: // - accepting Helper<null> rather than null const falseOrNull2: false | Helper<null> = asComplicatedMembers.helperNullableFalse; // - using a "voidable" rather than a nullable // tslint:disable-next-line void-return const numberOrVoid: number | void = asComplicatedMembers.helperVoidableNumber; // - or, the recommended solution: using OptionalHelper<T> // OptionalHelper<T> defines a helper which can be left undefined when providing a collection's helpers // that property can be required or optional on the interface; either way, it'll be optional on Helpers<T> and // on Full<T> // and it even works on methods interface ActuallyOptionalHelpers { _id?: string | undefined; value: number; getValue: OptionalHelper<() => number>; incrementValue?: OptionalHelper<() => void> | undefined; optionalHelperValue: OptionalHelper<number>; optionalHelperName?: OptionalHelper<string> | undefined; } const actuallyOptionalHelpers = new Mongo.Collection<ActuallyOptionalHelpers>('actuallyOptionalHelpers'); // every one of those helpers is totally optional - we can even provide an empty object! // $ExpectType void actuallyOptionalHelpers.helpers({}); // $ExpectType void actuallyOptionalHelpers.helpers({ getValue() { return this.value; }, }); // $ExpectType void actuallyOptionalHelpers.helpers({ incrementValue() { this.value++; }, }); // $ExpectType void actuallyOptionalHelpers.helpers({ optionalHelperValue: 3, }); // $ExpectType void actuallyOptionalHelpers.helpers({ optionalHelperName: 'foo', }); // $ExpectType void actuallyOptionalHelpers.helpers({ getValue() { return this.value; }, incrementValue() { this.value++; }, optionalHelperValue: 3, optionalHelperName: 'foo', }); // as usual, only non-helper properties are required when inserting an item const aohId = actuallyOptionalHelpers.insert({ value: 7, }); const aohInstance = actuallyOptionalHelpers.findOne(aohId)!; // since they don't have to be provided, users of an item with optional helpers aren't promised those helpers will be present let aohName: string | undefined = aohInstance.optionalHelperName; const aohValue: number | undefined = aohInstance.optionalHelperValue; // $ExpectError aohInstance.getValue(); // asserting their existence works // $ExpectType number aohInstance.getValue!(); // as does control-flow analysis if (aohInstance.getValue) { // $ExpectType number aohInstance.getValue(); } // can still put retrieved items back into the container actuallyOptionalHelpers.insert(aohInstance); // unlike with Helper<T | null>, these work directly from the original interface type const asAoh: ActuallyOptionalHelpers = aohInstance; aohName = asAoh.optionalHelperName; // $ExpectType number asAoh.getValue!();
the_stack
import React, { FC } from 'react'; import styled from 'styled-components'; import { ColorScheme } from '../../../plugins'; import { PluginTheme } from '../../../plugins/misc'; import { useThemes } from '../../hooks/theme'; import { HelpTooltip } from '../help-tooltip'; const THEMES_PER_ROW = 5; const isDark = (mode: 'dark' | 'light') => mode === 'dark'; const isLight = (mode: 'dark' | 'light') => mode === 'light'; const RootWrapper = styled.div({}); const CheckboxWrapper = styled.div({ marginLeft: 'var(--padding-md)', }); const Themes = styled.div({ display: 'flex', flexWrap: 'wrap', }); const ThemeButton = styled.div<{ $isActive: boolean; $isInOsThemeMode: boolean }>(({ $isActive, $isInOsThemeMode }) => ({ position: 'relative', margin: 'var(--padding-md) var(--padding-md)', fontSize: 0, borderRadius: 'var(--radius-md)', transition: 'all 150ms ease-out', // This is a workaround for some anti-aliasing artifacts that impact the color scheme badges. // The box shadow is placed on a pseudo-element. When it is active, it is configured to overlap // 1px with the underlying geometry to prevent gaps caused by anti-aliasing. '&:before': { display: 'block', position: 'absolute', boxShadow: '0 0 0 1px var(--hl-sm)', transition: 'all 150ms ease-out', borderRadius: 'var(--radius-md)', width: '100%', height: '100%', content: "''", ...($isActive ? { boxShadow: '0 0 0 var(--padding-xs) var(--color-surprise)', width: 'calc(100% - 2px)', height: 'calc(100% - 2px)', margin: '1px', } : {}), }, '&:hover:before': { ...($isInOsThemeMode ? { boxShadow: '0 0 0 0 var(--color-surprise)' } : {}), }, ...($isActive ? { transform: 'scale(1.05)', } : {}), '&:hover': { transform: 'scale(1.05)', }, ...($isInOsThemeMode ? { '&:hover .overlay-wrapper': { display: 'flex', }, '&:hover .theme-preview': { visibility: 'hidden', // this prevents alpha-blending problems with the underlying svg bleeding through }, } : {}), })); const ThemeTitle = styled.h2({ marginTop: 0, marginBottom: 'var(--padding-xs)', fontSize: 'var(--font-size-md)', }); const ThemeWrapper = styled.div({ maxWidth: `${100 / THEMES_PER_ROW}%`, minWidth: 110, marginBottom: 'var(--padding-md)', marginTop: 'var(--padding-md)', textAlign: 'center', }); const ColorSchemeBadge = styled.div<{ $theme: 'dark' | 'light'}>(({ $theme }) => ({ position: 'absolute', top: 0, width: 12, height: 12, fill: 'white', padding: 4, transition: 'background-color 150ms ease-out', backgroundColor: 'var(--color-surprise)', ...(isDark($theme) ? { right: 0, borderTopRightRadius: 'var(--radius-md)', borderBottomLeftRadius: 'var(--radius-md)', } : {}), ...(isLight($theme) ? { left: 0, borderTopLeftRadius: 'var(--radius-md)', borderBottomRightRadius: 'var(--radius-md)', } : {}), })); const OverlayWrapper = styled.div({ position: 'absolute', height: '100%', width: '100%', alignItems: 'center', flexWrap: 'nowrap', justifyContent: 'space-evenly', boxSizing: 'content-box', display: 'none', // controlled by hover on the ThemeWrapper }); const OverlaySide = styled.div<{ $theme: 'dark' | 'light' }>(({ $theme }) => ({ display: 'flex', cursor: 'pointer', flexGrow: 1, alignItems: 'center', justifyContent: 'center', height: '100%', background: 'var(--color-bg)', '& svg': { opacity: 0.4, fill: 'var(--color-fg)', height: 20, }, '&:hover svg': { opacity: 1, fill: 'var(--color-surprise)', }, boxSizing: 'border-box', border: '1px solid var(--hl-sm)', ...(isDark($theme) ? { borderTopRightRadius: 'var(--radius-md)', borderBottomRightRadius: 'var(--radius-md)', borderLeftStyle: 'none', } : {}), ...(isLight($theme) ? { borderTopLeftRadius: 'var(--radius-md)', borderBottomLeftRadius: 'var(--radius-md)', borderRightStyle: 'none', } : {}), '&:hover': { border: '1px solid var(--color-surprise)', }, })); const SunSvg = () => ( <svg viewBox="0 0 14 14"> <circle cx="7" cy="7" r="4" /> <rect x="6.5" y="12" width="1" height="2" rx="0.5" /> <rect x="6.5" width="1" height="2" rx="0.5" /> <rect x="2" y="6.5" width="1" height="2" rx="0.5" transform="rotate(90 2 6.5)" /> <rect x="14" y="6.5" width="1" height="2" rx="0.5" transform="rotate(90 14 6.5)" /> <rect x="3.81799" y="3.11084" width="1" height="2" rx="0.5" transform="rotate(135 3.81799 3.11084)" /> <rect x="12.3033" y="11.5962" width="1" height="2" rx="0.5" transform="rotate(135 12.3033 11.5962)" /> <rect x="10.889" y="3.81799" width="1" height="2" rx="0.5" transform="rotate(-135 10.889 3.81799)" /> <rect x="2.40381" y="12.3033" width="1" height="2" rx="0.5" transform="rotate(-135 2.40381 12.3033)" /> </svg> ); const MoonSvg = () => ( <svg viewBox="0 0 14 14"> <path d="M4.00005 11C7.86604 11 11 7.86604 11 4.00005C11 2.83978 10.7178 1.74545 10.2181 0.781982C12.4649 1.94714 14 4.29432 14 7.00005C14 10.866 10.866 14 7.00005 14C4.29432 14 1.94714 12.4649 0.781982 10.2181C1.74545 10.7178 2.83978 11 4.00005 11Z" /> </svg> ); const ThemePreview: FC<{ theme: PluginTheme }> = ({ theme: { name: themeName } }) => ( <svg /* @ts-expect-error -- TSCONVERSION */ theme={themeName} className="theme-preview" width="100%" height="100%" viewBox="0 0 500 300" style={{ borderRadius: 'var(--radius-md)' }} > {/* A WORD TO THE WISE: If you, dear traveler from the future, are here for the purpose of theming things due to changes in the app structure, please remember to add `--sub` to your classes or else the selected class' theme variables will apply to all theme previews. Search your codebase for `--sub` to see more. */} {/* @ts-expect-error -- TSCONVERSION */} <g subtheme={themeName}> {/* App Header */} <g className="theme--app-header--sub"> <rect x="0" y="0" width="100%" height="10%" style={{ fill: 'var(--color-bg)' }} /> </g> {/* Panes */} <g className="theme--pane--sub"> {/* Response Area */} <rect x="0" y="10%" width="100%" height="100%" style={{ fill: 'var(--color-bg)' }} /> {/* URL Bars */} <rect x="25%" y="10%" width="100%" height="10%" className="theme--pane__header--sub" style={{ fill: 'var(--color-bg)' }} /> {/* Send Button */} <g> <rect x="53%" y="10%" width="9%" height="10%" style={{ fill: 'var(--color-surprise)' }} /> </g> </g> {/* Sidebar */} <g className="theme--sidebar--sub"> <rect x="0" y="10%" width="25%" height="100%" style={{ fill: 'var(--color-bg)' }} /> </g> {/* Lines */} <line x1="0%" x2="100%" y1="10%" y2="10%" strokeWidth="1" style={{ stroke: 'var(--hl-md)' }} /> <line x1="25%" x2="100%" y1="20%" y2="20%" strokeWidth="1" style={{ stroke: 'var(--hl-md)' }} /> <line x1="62%" x2="62%" y1="10%" y2="100%" strokeWidth="1" style={{ stroke: 'var(--hl-md)' }} /> <line x1="25%" x2="25%" y1="10%" y2="100%" strokeWidth="1" style={{ stroke: 'var(--hl-md)' }} /> {/* Color Squares */} <rect x="40%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-success)' }} /> <rect x="50%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-info)' }} /> <rect x="60%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-warning)' }} /> <rect x="70%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-danger)' }} /> <rect x="80%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-surprise)' }} /> <rect x="90%" y="85%" width="5%" height="8%" style={{ fill: 'var(--color-info)' }} /> </g> </svg> ); const IndividualTheme: FC<{ isActive: boolean; isDark: boolean; isLight: boolean; isInOsThemeMode: boolean; onChangeTheme: (name: string, mode: ColorScheme) => Promise<void>; theme: PluginTheme; }> = ({ isActive, isDark, isLight, isInOsThemeMode, onChangeTheme, theme, }) => { const { displayName, name } = theme; const onClickThemeButton = () => { if (isInOsThemeMode) { // The overlays handle this behavior in OS theme mode. // React's event bubbling means that this will be fired when you click on an overlay, so we need to turn it off when in this mode. // Even still, we don't want to risk some potnetial subpixel or z-index nonsense accidentally setting the default when know we shouldn't. return; } return onChangeTheme(name, 'default'); }; return ( <ThemeWrapper> <ThemeTitle>{displayName}</ThemeTitle> <ThemeButton onClick={onClickThemeButton} $isActive={isActive} $isInOsThemeMode={isInOsThemeMode} > {isInOsThemeMode ? ( <> <OverlayWrapper className="overlay-wrapper"> <OverlaySide $theme="light" onClick={() => { onChangeTheme(name, 'light'); }}><SunSvg /></OverlaySide> <OverlaySide $theme="dark" onClick={() => { onChangeTheme(name, 'dark'); }}><MoonSvg /></OverlaySide> </OverlayWrapper> {isActive && isDark ? ( <ColorSchemeBadge $theme="dark"><MoonSvg /></ColorSchemeBadge> ) : null} {isActive && isLight ? ( <ColorSchemeBadge $theme="light"><SunSvg /></ColorSchemeBadge> ) : null} </> ) : null} <ThemePreview theme={theme} /> </ThemeButton> </ThemeWrapper> ); }; export const ThemePanel: FC = () => { const { themes, activate, changeAutoDetect, isActive, isActiveDark, isActiveLight, autoDetectColorScheme, } = useThemes(); return ( <RootWrapper> <CheckboxWrapper className="form-control form-control--thin"> <label className="inline-block"> Use OS color scheme <HelpTooltip className="space-left"> Pick your prefered themes for light and dark </HelpTooltip> <input type="checkbox" name="autoDetectColorScheme" checked={autoDetectColorScheme} onChange={changeAutoDetect} /> </label> </CheckboxWrapper> <Themes> {themes.map(theme => ( <IndividualTheme key={theme.name} theme={theme} isActive={isActive(theme)} onChangeTheme={activate} isDark={isActiveDark(theme)} isLight={isActiveLight(theme)} isInOsThemeMode={autoDetectColorScheme} /> ))} </Themes> </RootWrapper> ); };
the_stack
import { AdapterBase } from "./AdapterBase"; import { ISpace, addEventToSpaceInternal, IBoard, getDeadSpaceIndex } from "../boards"; import { Space, SpaceSubtype, GameVersion } from "../types"; import { createEventInstance } from "../events/events"; import { parse as parseInst } from "mips-inst"; import { strings } from "../fs/strings"; import { arrayToArrayBuffer, arrayBufferToDataURL } from "../utils/arrays"; import { fromTiles, toTiles } from "../utils/img/tiler"; import { FORM } from "../models/FORM"; import { mainfs } from "../fs/mainfs"; import { BMPfromRGBA } from "../utils/img/BMP"; import { toArrayBuffer } from "../utils/image"; import { toPack } from "../utils/img/ImgPack"; import { assemble } from "mips-assembler"; import { scenes } from "../fs/scenes"; import { createBoardOverlay } from "./MP1.U.boardoverlay"; import { IBoardInfo } from "./boardinfobase"; import { ChanceTime } from "../events/builtin/MP1/U/ChanceTimeEvent1"; import { StarChanceEvent } from "../events/builtin/MP1/U/StarChanceEvent1"; import { getImageData } from "../utils/img/getImageData"; import { getSoundEffectMapMP1 } from "./MP1.U.soundeffects"; import { getEventsInLibrary } from "../events/EventLibrary"; import { EventMap } from "../app/boardState"; import { getAudioMapMP1 } from "./MP1.U.audio"; export const MP1 = new class MP1Adapter extends AdapterBase { public gameVersion: GameVersion = 1; public nintendoLogoFSEntry: number[] = [9, 110]; public hudsonLogoFSEntry: number[] = [9, 111]; public boardDefDirectory: number = 10; public MAINFS_READ_ADDR: number = 0x000145B0; public HEAP_FREE_ADDR: number = 0x00014730; public TABLE_HYDRATE_ADDR: number = 0x0004C900; // Gives a new space the default things it would need. hydrateSpace(space: ISpace, board: IBoard, eventLibrary: EventMap) { if (space.type === Space.STAR) { space.star = true; } else if (space.type === Space.CHANCE) { addEventToSpaceInternal(board, space, createEventInstance(ChanceTime), false, eventLibrary); } } onLoad(board: IBoard, boardInfo: IBoardInfo, boardWasStashed: boolean) { if (!boardWasStashed) { this._extractKoopa(board, boardInfo); this._extractBowser(board, boardInfo); this._extractGoomba(board, boardInfo); } } onCreateBoardOverlay(board: IBoard, boardInfo: IBoardInfo, boardIndex: number, audioIndices: number[]) { return createBoardOverlay(board, boardInfo, boardIndex, audioIndices); } onAfterOverwrite(romView: DataView, board: IBoard, boardInfo: IBoardInfo, boardIndex: number): void { // this._writeKoopa(board, boardInfo); // this._writeBowser(board, boardInfo); // Patch game to use all 8MB. romView.setUint16(0x3BF62, 0x8040); // Main heap now starts at 0x80400000 romView.setUint16(0x3BF6A, (0x00400000 - this.EVENT_MEM_SIZE) >>> 16); // ... and can fill up through the reserved event location romView.setUint16(0x3BF76, 0x0020); // Temp heap fills as much as 0x200000 romView.setUint16(0x5F3F6, 0x0020); // Patch HVQ decode RAM 0x4a3a4 to redirect to raw decode hook. const romStartOffset = 0xCBFD0; let asmStartOffset = 0xCB3D0; romView.setUint32(0x4AFD4, parseInst(`J ${asmStartOffset}`)); // Patch over some debug strings with logic to handle raw images. const hvqAsm = ` .orga ${romStartOffset} LW S5, 0x0(A0) LUI S6, 0x4856 // "HV" ADDIU S6, S6, 0x5120 // "Q " BEQ S5, S6, call_hvq_decode NOP ADDU S5, R0, A1 ADDIU S6, S5, 0x1800 // (64 x 48 tile) ADDU S7, R0, A0 LW GP, 0(S7) SW GP, 0(S5) ADDIU S5, S5, 4 ADDIU S7, S7, 4 BEQ S5, S6, ret_to_hook NOP J ${asmStartOffset + 0x20} // J back to LW NOP call_hvq_decode: ADDU S5, R0, R0 ADDU S6, R0, R0 ADDU S7, R0, R0 ADDU GP, R0, R0 JAL 0x7F54C // JAL HVQDecode NOP ret_to_hook: ADDU S5, R0, R0 ADDU S6, R0, R0 ADDU S7, R0, R0 ADDU GP, R0, R0 J 0x4A3DC // J back into original function, skipping HVQDecode NOP `; assemble(hvqAsm, { buffer: romView.buffer }); } onOverwritePromises(board: IBoard, boardInfo: IBoardInfo, boardIndex: number) { const bgIndex = boardInfo.bgDir; let bgPromises = [ this.onWriteBoardSelectImg(board, boardInfo), // The board select image/icon this.onWriteBoardLogoImg(board, boardInfo), // Various board logos this._brandBootSplashscreen(), this._writeBackground(bgIndex, board.bg.src, board.bg.width, board.bg.height), this._writeBackground(boardInfo.pauseBgDir!, board.bg.src, 320, 240), // Overview map this._writeAdditionalBackgrounds(board), ]; switch (boardIndex) { case 0: // DK board bgPromises = bgPromises.concat([ this._writeBackground(bgIndex + 1, board.otherbg.largescene!, 320, 240), // Game start, end this._writeBackground(bgIndex + 2, board.otherbg.conversation!, 320, 240), // Conversation this._writeBackground(bgIndex + 3, board.otherbg.conversation!, 320, 240), // Treasure thing... // Pause bg this._writeBackground(bgIndex + 5, board.bg.src, 320, 240), // End game overview map this._writeBackground(bgIndex + 6, board.otherbg.splashscreen!, 320, 240), // Splashscreen bg ]); break; case 1: // Peach board bgPromises = bgPromises.concat([ this._writeBackground(bgIndex + 1, board.otherbg.largescene!, 320, 240), // Game start, end this._writeBackground(bgIndex + 2, board.otherbg.conversation!, 320, 240), // Mini-Game results, Boo? this._writeBackground(bgIndex + 3, board.otherbg.conversation!, 320, 240), // Conversation this._writeBackground(bgIndex + 4, board.otherbg.conversation!, 320, 240), // Visit Toad this._writeBackground(bgIndex + 5, board.otherbg.conversation!, 320, 240), this._writeBackground(bgIndex + 6, board.otherbg.largescene!, 320, 240), // Third end game cutscene bg // Pause bg this._writeBackground(bgIndex + 8, board.bg.src, 320, 240), // First end game cutscene bg this._writeBackground(bgIndex + 9, board.bg.src, 320, 240), // Second end game cutscene bg this._writeBackground(bgIndex + 10, board.otherbg.splashscreen!, 320, 240), // Splashscreen ]); break; case 2: // Yoshi board bgPromises = bgPromises.concat([ // 18: bgDir this._writeBackground(bgIndex + 1 /* 19 */, board.otherbg.largescene!, 320, 240), // Game start, end this._writeBackground(bgIndex + 2 /* 20 */, board.otherbg.conversation!, 320, 240), // Conversation, Boo, Koopa this._writeBackground(bgIndex + 3 /* 21 */, board.otherbg.conversation!, 320, 240), // Conversation this._writeBackground(bgIndex + 4 /* 22 */, board.otherbg.conversation!, 320, 240), // Conversation, Toad this._writeBackground(bgIndex + 5 /* 23 */, board.otherbg.conversation!, 320, 240), // Conversation, Bowser this._writeBackground(bgIndex + 6 /* 24 */, board.bg.src, 320, 240), // // 25: Pause bg this._writeBackground(bgIndex + 8 /* 26 */, board.otherbg.splashscreen!, 320, 240), // Splashscreen ]); break; case 3: // Wario board bgPromises = bgPromises.concat([ // 27: bgDir this._writeBackground(bgIndex + 1 /* 28 */, board.otherbg.largescene!, 320, 240), // Game start, end this._writeBackground(bgIndex + 2 /* 29 */, board.otherbg.conversation!, 320, 240), // Conversation, Koopa this._writeBackground(bgIndex + 3 /* 30 */, board.otherbg.conversation!, 320, 240), // Conversation, Bowser, Boo this._writeBackground(bgIndex + 4 /* 31 */, board.otherbg.conversation!, 320, 240), // this._writeBackground(bgIndex + 5 /* 32 */, board.otherbg.conversation!, 320, 240), // Conversation, Bowser, Toad this._writeBackground(bgIndex + 6 /* 33 */, board.bg.src, 320, 240), // this._writeBackground(bgIndex + 7 /* 34 */, board.otherbg.conversation!, 320, 240), // this._writeBackground(bgIndex + 8 /* 35 */, board.otherbg.conversation!, 320, 240), // // 36: Pause bg this._writeBackground(bgIndex + 10 /* 37 */, board.otherbg.conversation!, 320, 240), // this._writeBackground(bgIndex + 11 /* 38 */, board.otherbg.splashscreen!, 320, 240), // Splashscreen ]); break; } return Promise.all(bgPromises) } onWriteEvents(board: IBoard) { // Right now the boards always put Chance time spaces where Stars were, // so we will just automate adding the post-star chance event. const spaces = board.spaces; for (let i = 0; i < spaces.length; i++) { let space = board.spaces[i]; if (!space || !space.star) continue; let events = space.events || []; let hasStarChance = events.some(e => e.id === "STARCHANCE"); // Pretty unlikely if (!hasStarChance) addEventToSpaceInternal(board, space, createEventInstance(StarChanceEvent), false, getEventsInLibrary()); } } onWriteEventAsmHook(romView: DataView, boardInfo: IBoardInfo, boardIndex: number) { } onParseStrings(board: IBoard, boardInfo: IBoardInfo) { let strs = boardInfo.str || {}; if (strs.boardSelect) { let idx = strs.boardSelect; if (Array.isArray(idx)) idx = idx[0] as number; let str = strings.read(idx) as string; let lines = str.split("\n"); // Read the board name and description. let nameStart = lines[0].indexOf(">") + 1; let nameEnd = lines[0].indexOf("<", nameStart); board.name = lines[0].substring(nameStart, nameEnd); board.description = [lines[1], lines[2]].join("\n"); // Parse difficulty star level let difficulty = 0; let lastIndex = str.indexOf(this.getCharacterMap()[0x2A], 0); while (lastIndex !== -1) { difficulty++; lastIndex = str.indexOf(this.getCharacterMap()[0x2A], lastIndex + 1); } board.difficulty = difficulty; } } onWriteStrings(board: IBoard, boardInfo: IBoardInfo) { let strs = boardInfo.str || {}; if (strs.boardSelect) { let bytes = []; bytes.push(0x0B); // Clear? bytes.push(0x05); // Start GREEN bytes = bytes.concat(strings._strToBytes(board.name || "")); bytes.push(0x02); // Start DEFAULT bytes.push(0x0A); // \n bytes = bytes.concat(strings._strToBytes(board.description || "")); // Assumes \n's are correct within. bytes.push(0x0A); // \n bytes = bytes.concat([0x10, 0x10, 0x10, 0x10, 0x10, 0x10]); // Spaces bytes.push(0x06); // Start BLUE bytes = bytes.concat(strings._strToBytes("Map Difficulty ")); let star = 0x2A; if (board.difficulty > 5 || board.difficulty < 1) { // Hackers! bytes.push(star); bytes = bytes.concat(strings._strToBytes(" ")); bytes.push(0x3E); // Little x bytes = bytes.concat(strings._strToBytes(" " + board.difficulty.toString())); } else { for (let i = 0; i < board.difficulty; i++) bytes.push(star); } bytes.push(0x02); // Start DEFAULT bytes.push(0x00); // Null byte let strBuffer = arrayToArrayBuffer(bytes); let idx = strs.boardSelect; if (Array.isArray(idx)) { for (let i = 0; i < idx.length; i++) { strings.write(idx[i] as number, strBuffer); } } else { strings.write(idx, strBuffer); } } // For now, just make Koopa's intro neutral. if (strs.koopaIntro) { let bytes: number[] = []; bytes = bytes.concat(strings._strToBytes("Welcome, everybody!\nI am your guide,\nKoopa Troopa.")); bytes.push(0xFF); // PAUSE bytes.push(0x0B); // Clear? bytes = bytes.concat(strings._strToBytes("Now then,\nlet's decide turn order.")); bytes.push(0xFF); // PAUSE bytes.push(0x00); // Null byte let strBuffer = arrayToArrayBuffer(bytes); strings.write(strs.koopaIntro, strBuffer); } // For now, just make a generic comment. if (strs.starComments) { let bytes: number[] = []; bytes = bytes.concat(strings._strToBytes("Good luck!\nWith enough stars, you\ncould be the superstar!")); bytes.push(0xFF); // PAUSE bytes.push(0x00); // Null byte let strBuffer = arrayToArrayBuffer(bytes); for (let i = 0; i < strs.starComments.length; i++) strings.write(strs.starComments[i], strBuffer); } } onChangeBoardSpaceTypesFromGameSpaceTypes(board: IBoard, chains: number[][]) { // Space types match MP1 exactly. } onChangeGameSpaceTypesFromBoardSpaceTypes(board: IBoard) { } _extractKoopa(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.koopaSpaceInst || !boardInfo.sceneIndex) return; const sceneView = scenes.getDataView(boardInfo.sceneIndex); let koopaSpace = sceneView.getUint16(boardInfo.koopaSpaceInst + 2); if (board.spaces[koopaSpace]) board.spaces[koopaSpace].subtype = SpaceSubtype.KOOPA; } _writeKoopa(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.koopaSpaceInst || !boardInfo.sceneIndex) return; let koopaSpace; for (let i = 0; i < board.spaces.length; i++) { if (board.spaces[i].subtype === SpaceSubtype.KOOPA) { koopaSpace = i; break; } } koopaSpace = (koopaSpace === undefined ? getDeadSpaceIndex(board) : koopaSpace); const sceneView = scenes.getDataView(boardInfo.sceneIndex); sceneView.setUint16(boardInfo.koopaSpaceInst + 2, koopaSpace); } _extractBowser(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.bowserSpaceInst || !boardInfo.sceneIndex) return; const sceneView = scenes.getDataView(boardInfo.sceneIndex); let bowserSpace = sceneView.getUint16(boardInfo.bowserSpaceInst + 2); if (board.spaces[bowserSpace]) board.spaces[bowserSpace].subtype = SpaceSubtype.BOWSER; } _writeBowser(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.bowserSpaceInst || !boardInfo.sceneIndex) return; let bowserSpace; for (let i = 0; i < board.spaces.length; i++) { if (board.spaces[i].subtype === SpaceSubtype.BOWSER) { bowserSpace = i; break; } } bowserSpace = (bowserSpace === undefined ? getDeadSpaceIndex(board) : bowserSpace); const sceneView = scenes.getDataView(boardInfo.sceneIndex); sceneView.setUint16(boardInfo.bowserSpaceInst + 2, bowserSpace); } _extractGoomba(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.goombaSpaceInst || !boardInfo.sceneIndex) return; const sceneView = scenes.getDataView(boardInfo.sceneIndex); let goombaSpace = sceneView.getUint16(boardInfo.goombaSpaceInst + 2); if (board.spaces[goombaSpace]) board.spaces[goombaSpace].subtype = SpaceSubtype.GOOMBA; } onParseBoardSelectImg(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.img.boardSelectImg) return; let boardSelectFORM = mainfs.get(9, boardInfo.img.boardSelectImg); let boardSelectUnpacked = FORM.unpack(boardSelectFORM)!; let boardSelectImgTiles = [ new DataView(boardSelectUnpacked.BMP1[0].parsed.src), new DataView(boardSelectUnpacked.BMP1[1].parsed.src), new DataView(boardSelectUnpacked.BMP1[2].parsed.src), new DataView(boardSelectUnpacked.BMP1[3].parsed.src) ]; let boardSelectImg = fromTiles(boardSelectImgTiles, 2, 2, 64 * 4, 32); board.otherbg.boardselect = arrayBufferToDataURL(boardSelectImg, 128, 64); // $$log(board.otherbg.boardselect); } async onWriteBoardSelectImg(board: IBoard, boardInfo: IBoardInfo): Promise<void> { let boardSelectIndex = boardInfo.img.boardSelectImg; if (!boardSelectIndex) { return; } // We need to write the image onto a canvas to get the RGBA32 values. let [width, height] = [128, 64]; const imgData = await getImageData(board.otherbg.boardselect!, width, height); // First, turn the image back into 4 BMP tiles let boardSelectImgTiles = toTiles(imgData.data, 2, 2, (width / 2) * 4, height / 2); let boardSelectBmps = boardSelectImgTiles.map(tile => { return BMPfromRGBA(tile, 32, 8); }); // Now write the BMPs back into the FORM. let boardSelectFORM = mainfs.get(9, boardSelectIndex!); let boardSelectUnpacked = FORM.unpack(boardSelectFORM)!; for (let i = 0; i < 4; i++) { let palette = boardSelectBmps[i][1]; // FIXME: This is padding the palette count a bit. // For some reason, the images get corrupt with very low palette count. while (palette.colors.length < 17) { palette.colors.push(0x00000000); } FORM.replaceBMP(boardSelectUnpacked, i, boardSelectBmps[i][0], palette); } // Now write the FORM. let boardSelectPacked = FORM.pack(boardSelectUnpacked); //saveAs(new Blob([boardSelectPacked]), "formPacked"); mainfs.write(9, boardSelectIndex!, boardSelectPacked); } onParseBoardLogoImg(board: IBoard, boardInfo: IBoardInfo) { if (!boardInfo.img.pauseLogoImg) return; board.otherbg.boardlogo = this._readImgFromMainFS(10, boardInfo.img.pauseLogoImg, 0); } onWriteBoardLogoImg(board: IBoard, boardInfo: IBoardInfo): Promise<void> { return new Promise((resolve, reject) => { let introLogoImgs = boardInfo.img.introLogoImg; let pauseLogoImg = boardInfo.img.pauseLogoImg; if (!introLogoImgs && !pauseLogoImg) { resolve(); return; } // We need to write the image onto a canvas to get the RGBA32 values. let [introWidth, introHeight] = boardInfo.img.introLogoImgDimens!; let srcImage = new Image(); let failTimer = setTimeout(() => reject(`Failed to write logos for ${boardInfo.name}`), 45000); srcImage.onload = () => { // Write the intro logo images. if (introLogoImgs) { let imgBuffer = toArrayBuffer(srcImage, introWidth, introHeight); if (!Array.isArray(introLogoImgs)) introLogoImgs = [introLogoImgs]; for (let i = 0; i < introLogoImgs.length; i++) { let logoImgIdx = introLogoImgs[i]; // First, read the old image pack. let oldPack = mainfs.get(10, logoImgIdx); // Then, pack the image and write it. let imgInfoArr = [ { src: imgBuffer, width: introWidth, height: introHeight, bpp: 32, } ]; let newPack = toPack(imgInfoArr, 16, 0, oldPack); // saveAs(new Blob([newPack]), "imgpack"); mainfs.write(10, logoImgIdx, newPack); } } if (pauseLogoImg) { // Always 200x82 let imgBuffer = toArrayBuffer(srcImage, 200, 82); // First, read the old image pack. let oldPack = mainfs.get(10, pauseLogoImg); //saveAs(new Blob([oldPack]), "oldpauseimgpack"); // Then, pack the image and write it. let imgInfoArr = [ { src: imgBuffer, width: 200, height: 82, bpp: 32, } ]; let newPack = toPack(imgInfoArr, 16, 0, oldPack); //saveAs(new Blob([newPack]), "newPack"); mainfs.write(10, pauseLogoImg, newPack); } clearTimeout(failTimer); resolve(); }; srcImage.src = board.otherbg.boardlogo!; }); } _clearOtherBoardNames(boardIndex: number) { // There is an ugly comic-sansy board name graphic in the after-game results. // We will just make it totally transparent because it is not important. let resultsBoardNameImgPack = mainfs.get(10, 406 + boardIndex); let imgPackU8Array = new Uint8Array(resultsBoardNameImgPack); imgPackU8Array.fill(0, 0x2C); // To the end mainfs.write(10, 406 + boardIndex, resultsBoardNameImgPack); } getAudioMap(tableIndex: number): string[] { return getAudioMapMP1(tableIndex); } getSoundEffectMap(table: number): string[] { return getSoundEffectMapMP1(table); } getCharacterMap(): { [num: number]: string } { return { 0x00: "", // NULL terminator 0x01: "<BLACK>", // Start black font 0x02: "<DEFAULT>", // Start default font 0x03: "<RED>", // Start red font 0x04: "<PURPLE>", // Start purple font 0x05: "<GREEN>", // Start green font 0x06: "<BLUE>", // Start blue font 0x07: "<YELLOW>", // Start yellow font 0x08: "<WHITE>", // Start white font 0x09: "<SEIZURE>", // Start flashing font 0x0A: "\n", 0x0B: "\u3014", // FEED Carriage return / start of bubble? 0x0C: "○", // 2ND BYTE OF PLAYER CHOICE 0x0D: "\t", // UNCONFIRMED / WRONG 0x0E: "\t", // 1ST BYTE OF PLAYER CHOICE // 0x0F - nothing 0x10: " ", 0x11: "{0}", // These are format params that get replaced with various things 0x12: "{1}", 0x13: "{2}", 0x14: "{3}", 0x15: "{4}", 0x16: "{5}", // Theoretically there may be more up through 0x20? // 0x18 - nothing // 0x20 - nothing 0x21: "\u3000", // ! A button 0x22: "\u3001", // " B button 0x23: "\u3002", // C-up button 0x24: "\u3003", // C-right button 0x25: "\u3004", // C-left button 0x26: "\u3005", // & C-down button 0x27: "\u3006", // ' Z button 0x28: "\u3007", // ( Analog stick 0x29: "\u3008", // ) (coin) 0x2A: "\u3009", // * Star 0x2B: "\u3010", // , S button 0x2C: "\u3011", // , R button // 0x2D - nothing // 0x2E - nothing // 0x2F - nothing // 0x30 - 0x39: 0-9 ascii 0x3A: "\u3012", // Hollow coin 0x3B: "\u3013", // Hollow star 0x3C: "+", // < 0x3D: "-", // = 0x3E: "x", // > Little x 0x3F: "->", // Little right ARROW // 0x40 - nothing // 0x41 - 0x5A: A-Z ascii 0x5B: "\"", // [ End quotes 0x5C: "'", // \ Single quote 0x5D: "(", // ] Open parenthesis 0x5E: ")", 0x5F: "/", // _ // 0x60 - nothing // 0x61 - 0x7A: a-z ascii 0x7B: ":", // : 0x80: "\"", // Double quote no angle 0x81: "°", // . Degree 0x82: ",", // , 0x83: "°", // Low circle FIXME 0x85: ".", // … Period 0xC0: "“", // A` 0xC1: "”", // A' 0xC2: "!", // A^ 0xC3: "?", // A~ 0xFF: "\u3015", // PAUSE }; } }();
the_stack
import { ensureDir, writeFile, remove } from 'fs-extra' import * as Path from 'path' import * as Fs from 'fs-extra' import { exec } from 'child_process' import { find, IKactusFile as _IKactusFile, IKactusConfig, parseFile, importFolder, } from 'kactus-cli' import { getUserDataPath, getTempPath } from '../ui/lib/app-proxy' import { Repository } from '../models/repository' import { Account } from '../models/account' import { Image } from '../models/diff' import { IGitAccount } from '../models/git-account' import { getDotComAPIEndpoint } from './api' import { sketchtoolPath, runPluginCommand, getSketchVersion } from './sketch' import * as Perf from '../ui/lib/git-perf' export type IFullKactusConfig = IKactusConfig & { sketchVersion?: string } export type IKactusFile = _IKactusFile & { isParsing: boolean isImporting: boolean preview?: Image previewError?: boolean } interface IKactusStatusResult { readonly config: IFullKactusConfig readonly files: Array<IKactusFile> readonly lastChecked: number } /** * Retrieve the status for a given repository */ export async function getKactusStatus( sketchPath: string, repository: Repository ): Promise<IKactusStatusResult> { const commandName = `[Kactus] get kactus status` return Perf.measure(commandName, async () => { const kactus = await find(repository.path) const sketchVersion = (await getSketchVersion(sketchPath)) || undefined return { config: { // need to copy the config otheerwise there is a memory leak ...kactus.config, sketchVersion, root: kactus.config.root ? Path.join(repository.path, kactus.config.root) : repository.path, }, files: kactus.files .map(f => { return { ...f, id: f.path.replace(repository.path, '').replace(/^\//, ''), isParsing: false, isImporting: false, } }) .sort((a, b) => (a.id > b.id ? 1 : -1)), lastChecked: Date.now(), } }) } export async function generateDocumentPreview( sketchPath: string, file: string, output: string ): Promise<string> { const commandName = `[Kactus] generate document preview` return Perf.measure(commandName, async () => { await ensureDir(output) return new Promise<string>((resolve, reject) => { exec( sketchtoolPath(sketchPath) + ' export preview "' + file + '" --output="' + output + '" --filename=document.png --overwriting=YES --max-size=1000 --compression=0.7 --save-for-web=YES', (err, stdout, stderr) => { if (err) { return reject(err) } resolve(output + '/document.png') } ) }) }) } const DUPLICATE_PAGE_REGEX = /(.*)___([0-9]+)$/ export async function generatePagePreview( sketchPath: string, file: string, name: string, output: string ): Promise<string> { const commandName = `[Kactus] generate page preview` return Perf.measure( commandName, () => new Promise<string>((resolve, reject) => { let pageName = name let index = 0 const match = DUPLICATE_PAGE_REGEX.exec(name) if (match) { pageName = match[1] index = parseInt(match[2]) - 1 } exec( sketchtoolPath(sketchPath) + ' export pages "' + file + '" --item="' + pageName + '" --output="' + output + '" --save-for-web=YES --use-id-for-name=YES --overwriting=YES --formats=png --compression=0.7', (err, stdout, stderr) => { if (err) { return reject(err) } const id = stdout.split('\n')[index].replace('Exported', '').trim() if (!id) { return reject(new Error('Failed to generate the preview')) } resolve(output + '/' + id) } ) }) ) } export async function generateArtboardPreview( sketchPath: string, file: string, id: string, output: string ): Promise<string> { const commandName = `[Kactus] generate artboard preview` return Perf.measure( commandName, () => new Promise<string>((resolve, reject) => { exec( sketchtoolPath(sketchPath) + ' export artboards "' + file + '" --item="' + id + '" --output="' + output + '" --save-for-web=YES --use-id-for-name=YES --overwriting=YES --include-symbols=YES --formats=png --compression=0.7', (err, stdout, stderr) => { if (err) { return reject(err) } resolve(output + '/' + id + '.png') } ) }) ) } export async function generateLayerPreview( sketchPath: string, file: string, id: string, output: string ): Promise<string> { const commandName = `[Kactus] generate layer preview` return Perf.measure( commandName, () => new Promise<string>((resolve, reject) => { exec( sketchtoolPath(sketchPath) + ' export layers "' + file + '" --item="' + id + '" --output="' + output + '" --save-for-web=YES --use-id-for-name=YES --overwriting=YES --formats=png --compression=0.7', (err, stdout, stderr) => { if (err) { return reject(err) } resolve(output + '/' + id + '.png') } ) }) ) } export async function saveKactusConfig( repository: Repository, config: IFullKactusConfig ): Promise<void> { const commandName = `[Kactus] save kactus config` return Perf.measure(commandName, async () => { const configPath = Path.join(repository.path, 'kactus.json') const configToSave = { ...config } delete configToSave.sketchVersion if (configToSave.root === repository.path) { delete configToSave.root } else if (configToSave.root) { configToSave.root = configToSave.root.replace(repository.path, '.') } return await writeFile(configPath, JSON.stringify(configToSave, null, 2)) }) } export function shouldShowPremiumUpsell( repository: Repository, account: IGitAccount | null, accounts: ReadonlyArray<Account> ) { if (!account) { return false } let potentialPremiumAccount = accounts.find(a => a.unlockedEnterpriseKactus) || accounts.find(a => a.unlockedKactus) if (!potentialPremiumAccount && account instanceof Account) { potentialPremiumAccount = account } if (!potentialPremiumAccount) { potentialPremiumAccount = accounts[0] } if (repository.gitHubRepository) { if (!potentialPremiumAccount) { // that shouldn't happen, when a repo is from github, // there is a account associated with it. // so bail out return false } if ( potentialPremiumAccount.endpoint !== getDotComAPIEndpoint() && !potentialPremiumAccount.unlockedEnterpriseKactus ) { return { enterprise: true, user: potentialPremiumAccount } } if ( repository.gitHubRepository.isPrivate && !potentialPremiumAccount.unlockedKactus && !potentialPremiumAccount.unlockedEnterpriseKactus ) { return { enterprise: false, user: potentialPremiumAccount } } } else if ( !potentialPremiumAccount || !potentialPremiumAccount.unlockedEnterpriseKactus ) { return { enterprise: true, user: potentialPremiumAccount } } return false } export async function parseSketchFile( repository: Repository, f: IKactusFile, config: IFullKactusConfig ) { const commandName = `[Kactus] parse file ${f.id}` return Perf.measure(commandName, async () => { const storagePath = Path.join( getTempPath(), 'kactus', String(repository.id), f.id ) await remove(storagePath) return parseFile(f.path + '.sketch', config) }) } export async function importSketchFile( repository: Repository, sketchPath: string, f: IKactusFile, config: IFullKactusConfig ) { const commandName = `[Kactus] import file ${f.id}` return Perf.measure(commandName, async () => { const storagePath = Path.join( getTempPath(), 'kactus', String(repository.id), f.id ) await remove(storagePath) await importFolder(f.path, { ...config, sketchPath }) return runPluginCommand( sketchPath, Path.resolve(__dirname, './plugin.sketchplugin'), 'refresh-files' ) }) } const storageRootPath = Path.join(getUserDataPath(), 'previews') export function getKactusStoragePaths( repository: Repository, commitish: string, sketchFile: IKactusFile ) { const storagePath = Path.join( storageRootPath, String(repository.id), commitish ) const sketchStoragePath = Path.join(storagePath, sketchFile.id) return { storagePath, sketchStoragePath, } } export const getKactusCacheSize = async () => { if (!(await Fs.pathExists(storageRootPath))) { return 0 } const getSize = async (path: string) => { const stats = await Fs.stat(path) let total = stats.size if (!stats.isDirectory()) { return total } const names = await Fs.readdir(path) for (const name of names) { total += await getSize(Path.join(path, name)) } return total } return await getSize(storageRootPath) } export const clearKactusCache = async (olderThan?: Date, repoName?: string) => { if (!(await Fs.pathExists(storageRootPath))) { return } if (!olderThan) { if (!repoName) { await Fs.remove(storageRootPath) } else { await Fs.remove(Path.join(storageRootPath, repoName)) } return } const repos = await Fs.readdir(storageRootPath) for (const repo of repos) { if (!repoName || repo === repoName) { const repoCachePath = Path.join(storageRootPath, repo) if ((await Fs.stat(repoCachePath)).isDirectory()) { const commitishes = await Fs.readdir(repoCachePath) for (const commitish of commitishes) { const commitishCachePath = Path.join(repoCachePath, commitish) const { ctime } = await Fs.stat(commitishCachePath) // if the commitish hasn't been access for a long time, remove it if (ctime < olderThan) { console.log(`removed ${commitishCachePath}`) await Fs.remove(commitishCachePath) } } } } } }
the_stack
import { strict as assert } from "assert"; import { IsoBuffer, stringToBuffer, Uint8ArrayToString, } from "@fluidframework/common-utils"; import { SummaryObject, ISummaryTree, ISummaryBlob, ISummaryHandle, SummaryType, ISnapshotTree, ITree, } from "@fluidframework/protocol-definitions"; import { BlobTreeEntry, TreeTreeEntry } from "@fluidframework/protocol-base"; import { convertSnapshotTreeToSummaryTree, convertSummaryTreeToITree, convertToSummaryTree, utf8ByteLength, } from "../summaryUtils"; describe("Summary Utils", () => { function assertSummaryTree(obj: SummaryObject): ISummaryTree { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (obj && obj.type === SummaryType.Tree) { return obj; } else { assert.fail("Object should be summary tree"); } } function assertSummaryBlob(obj: SummaryObject): ISummaryBlob { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (obj && obj.type === SummaryType.Blob) { return obj; } else { assert.fail("Object should be summary blob"); } } function assertSummaryHandle(obj: SummaryObject): ISummaryHandle { // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (obj && obj.type === SummaryType.Handle) { return obj; } else { assert.fail("Object should be summary handle"); } } describe("ITree <-> ISummaryTree", () => { let tree: ITree; beforeEach(() => { const base64Content = IsoBuffer.from("test-b64").toString("base64"); tree = { entries: [ new TreeTreeEntry("t", { entries: [ new BlobTreeEntry("bu8", "test-u8"), new BlobTreeEntry("b64", base64Content, "base64"), new TreeTreeEntry("tu", { entries: [], unreferenced: true}), ], unreferenced: undefined, }), new BlobTreeEntry("b", "test-blob"), new TreeTreeEntry("h", { id: "test-handle", entries: [ new BlobTreeEntry("ignore", "this-should-be-ignored"), ], }), new TreeTreeEntry("unref", { entries: [], unreferenced: true, }), ], unreferenced: undefined, }; }); it("Should convert ITree to ISummaryTree correctly", () => { const summaryResults = convertToSummaryTree(tree); const summaryTree = assertSummaryTree(summaryResults.summary); // blobs should parse const blob = assertSummaryBlob(summaryTree.tree.b); assert.strictEqual(blob.content, "test-blob"); // trees with ids should become handles const handle = assertSummaryHandle(summaryTree.tree.h); assert.strictEqual(handle.handleType, SummaryType.Tree); assert.strictEqual(handle.handle, "test-handle"); // subtrees should recurse const subTree = assertSummaryTree(summaryTree.tree.t); const subBlobUtf8 = assertSummaryBlob(subTree.tree.bu8); assert.strictEqual(subBlobUtf8.content, "test-u8"); const subBlobBase64 = assertSummaryBlob(subTree.tree.b64); assert.strictEqual(Uint8ArrayToString(subBlobBase64.content as Uint8Array), "test-b64"); const subTreeUnref = assertSummaryTree(subTree.tree.tu); assert.strictEqual(Object.keys(subTreeUnref.tree).length, 0, "There should be no entries in tu subtree"); }); it("Should convert ITree to ISummaryTree correctly with fullTree enabled", () => { const summaryResults = convertToSummaryTree(tree, true); const summaryTree = assertSummaryTree(summaryResults.summary); // blobs should parse const blob = assertSummaryBlob(summaryTree.tree.b); assert.strictEqual(blob.content, "test-blob"); // trees with ids should not become handles const usuallyIgnoredSubtree = assertSummaryTree(summaryTree.tree.h); const usuallyIgnoredBlob = assertSummaryBlob(usuallyIgnoredSubtree.tree.ignore); assert.strictEqual(usuallyIgnoredBlob.content, "this-should-be-ignored"); // subtrees should recurse const subTree = assertSummaryTree(summaryTree.tree.t); const subBlobUtf8 = assertSummaryBlob(subTree.tree.bu8); assert.strictEqual(subBlobUtf8.content, "test-u8"); const subBlobBase64 = assertSummaryBlob(subTree.tree.b64); assert.strictEqual(Uint8ArrayToString(subBlobBase64.content as Uint8Array), "test-b64"); const subUnrefTree = assertSummaryTree(subTree.tree.tu); assert.strictEqual(Object.keys(subUnrefTree.tree).length, 0, "There should be no entries in tu subtree"); }); it("Should calculate summary data correctly", () => { const summaryResults = convertToSummaryTree(tree); // nodes should count assert.strictEqual(summaryResults.stats.blobNodeCount, 3); assert.strictEqual(summaryResults.stats.handleNodeCount, 1); assert.strictEqual(summaryResults.stats.treeNodeCount, 4); const bufferLength = IsoBuffer.from("test-b64").byteLength + IsoBuffer.from("test-blob").byteLength + IsoBuffer.from("test-u8").byteLength; assert.strictEqual(summaryResults.stats.totalBlobSize, bufferLength); }); it("should convert unreferenced state correctly", () => { const summaryResults = convertToSummaryTree(tree); const summaryTree = assertSummaryTree(summaryResults.summary); assert.strictEqual(summaryTree.unreferenced, undefined, "The root summary tree should be referenced"); const subTreeT = assertSummaryTree(summaryTree.tree.t); assert.strictEqual(subTreeT.unreferenced, undefined, "The t subtree should be referenced"); const subTreeTUnrefTree = assertSummaryTree(subTreeT.tree.tu); assert.strictEqual(subTreeTUnrefTree.unreferenced, true, "The tu subtree of t should be referenced"); const subTreeUnref = assertSummaryTree(summaryTree.tree.unref); assert.strictEqual(subTreeUnref.unreferenced, true, "The unref subtree should be unreferenced"); }); it("should convert ISummaryTree to ITree correctly", () => { // convertSummaryTreeToITree API does not accept a tree with handles. So, remove handles from the ITree. const treeWithoutHandles: ITree = { entries: tree.entries.filter((treeEntry) => { return treeEntry.path !== "h"; }), unreferenced: undefined, }; const summaryResults = convertToSummaryTree(treeWithoutHandles); const summaryTree = assertSummaryTree(summaryResults.summary); // Covert the ISummaryTree back to ITree and validate that it matches with the original tree. const iTree = convertSummaryTreeToITree(summaryTree); assert.deepStrictEqual(treeWithoutHandles, iTree, "Could not covert back to ITree correctly"); }); }); describe("ISnapshotTree -> ISummaryTree", () => { let snapshotTree: ISnapshotTree; beforeEach(() => { snapshotTree = { blobs: { "b": "blob-b", "blob-b": IsoBuffer.from("test-blob").toString("base64"), }, trees: { t: { blobs: { "bu8": "blob-bu8", "blob-bu8": IsoBuffer.from("test-u8").toString("base64"), "b64": "blob-b64", "blob-b64": IsoBuffer.from("test-b64").toString("base64"), }, trees: { tu: { blobs: { }, trees: { }, commits: { }, unreferenced: true, }, }, commits: { }, }, unref: { blobs: { }, trees: { }, commits: { }, unreferenced: true, }, }, commits: { }, }; }); it("Should convert correctly", () => { const summaryResults = convertSnapshotTreeToSummaryTree(snapshotTree); const summaryTree = assertSummaryTree(summaryResults.summary); // blobs should parse const blob = assertSummaryBlob(summaryTree.tree.b); assert.strictEqual(blob.content, "test-blob"); // subtrees should recurse const subTree = assertSummaryTree(summaryTree.tree.t); const subBlobUtf8 = assertSummaryBlob(subTree.tree.bu8); assert.strictEqual(subBlobUtf8.content, "test-u8"); const subBlobBase64 = assertSummaryBlob(subTree.tree.b64); assert.strictEqual(Uint8ArrayToString(subBlobBase64.content as Uint8Array), "test-b64"); const subTreeUnref = assertSummaryTree(subTree.tree.tu); assert.strictEqual(Object.keys(subTreeUnref.tree).length, 0, "There should be no entries in tu subtree"); }); it("Should calculate summary data correctly", () => { const summaryResults = convertSnapshotTreeToSummaryTree(snapshotTree); // nodes should count assert.strictEqual(summaryResults.stats.blobNodeCount, 3); assert.strictEqual(summaryResults.stats.handleNodeCount, 0); assert.strictEqual(summaryResults.stats.treeNodeCount, 4); const bufferLength = IsoBuffer.from("test-b64").byteLength + IsoBuffer.from("test-blob").byteLength + IsoBuffer.from("test-u8").byteLength; assert.strictEqual(summaryResults.stats.totalBlobSize, bufferLength); }); it("should convert unreferenced state correctly", () => { const summaryResults = convertSnapshotTreeToSummaryTree(snapshotTree); const summaryTree = assertSummaryTree(summaryResults.summary); assert.strictEqual(summaryTree.unreferenced, undefined, "The root summary tree should be referenced"); const subTreeT = assertSummaryTree(summaryTree.tree.t); assert.strictEqual(subTreeT.unreferenced, undefined, "The t subtree should be referenced"); const subTreeTUnrefTree = assertSummaryTree(subTreeT.tree.tu); assert.strictEqual(subTreeTUnrefTree.unreferenced, true, "The tu subtree of t should be referenced"); const subTreeUnref = assertSummaryTree(summaryTree.tree.unref); assert.strictEqual(subTreeUnref.unreferenced, true, "The unref subtree should be unreferenced"); }); }); describe("utf8ByteLength()", () => { it("gives correct utf8 byte length", () => { const a = [ "prague is a city in europe", "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ", "Τὴ γλῶσσα μοῦ ἔδωσαν ἑλληνικὴ", "На берегу пустынных волн", "⠊⠀⠉⠁⠝⠀⠑⠁⠞⠀⠛⠇⠁⠎⠎⠀⠁⠝⠙⠀⠊⠞⠀⠙⠕⠑⠎⠝⠞⠀⠓⠥⠗⠞⠀⠍⠑", "أنا قادر على أكل الزجاج و هذا لا يؤلمني.", " 我能吞下玻璃而不傷身體。", "ᐊᓕᒍᖅ ᓂᕆᔭᕌᖓᒃᑯ ᓱᕋᙱᑦᑐᓐᓇᖅᑐᖓ", "🤦🏼‍♂️", "🏴󠁧󠁢󠁷󠁬󠁳󠁿", // the flag of wales "���", "������", ]; a.map((s) => assert.strictEqual(utf8ByteLength(s), stringToBuffer(s, "utf8").byteLength, s)); }); }); });
the_stack
import type {TextureLevel} from '@loaders.gl/schema'; import {GL_EXTENSIONS_CONSTANTS} from '../gl-extensions'; import {extractMipmapImages} from '../utils/extract-mipmap-images'; const PVR_CONSTANTS: Record<string, number> = { MAGIC_NUMBER: 0x03525650, MAGIC_NUMBER_EXTRA: 0x50565203, HEADER_LENGTH: 13, HEADER_SIZE: 52, MAGIC_NUMBER_INDEX: 0, PIXEL_FORMAT_INDEX: 2, COLOUR_SPACE_INDEX: 4, HEIGHT_INDEX: 6, WIDTH_INDEX: 7, MIPMAPCOUNT_INDEX: 11, METADATA_SIZE_INDEX: 12 }; const PVR_PIXEL_FORMATS: Record<number, number[]> = { 0: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG], 1: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG], 2: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG], 3: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG], 6: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL], 7: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT], 9: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT3_EXT], 11: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT], 22: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB8_ETC2], 23: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA8_ETC2_EAC], 24: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2], 25: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_R11_EAC], 26: [GL_EXTENSIONS_CONSTANTS.COMPRESSED_RG11_EAC], 27: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR ], 28: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_5X4_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR ], 29: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_5X5_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR ], 30: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_6X5_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR ], 31: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_6X6_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR ], 32: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_8X5_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR ], 33: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_8X6_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR ], 34: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_8X8_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR ], 35: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_10X5_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR ], 36: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_10X6_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR ], 37: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_10X8_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR ], 38: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_10X10_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR ], 39: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_12X10_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR ], 40: [ GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_12X12_KHR, GL_EXTENSIONS_CONSTANTS.COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR ] }; const PVR_SIZE_FUNCTIONS: Record<number, (width: number, height: number) => number> = { 0: pvrtc2bppSize, 1: pvrtc2bppSize, 2: pvrtc4bppSize, 3: pvrtc4bppSize, 6: dxtEtcSmallSize, 7: dxtEtcSmallSize, 9: dxtEtcAstcBigSize, 11: dxtEtcAstcBigSize, 22: dxtEtcSmallSize, 23: dxtEtcAstcBigSize, 24: dxtEtcSmallSize, 25: dxtEtcSmallSize, 26: dxtEtcAstcBigSize, 27: dxtEtcAstcBigSize, 28: atc5x4Size, 29: atc5x5Size, 30: atc6x5Size, 31: atc6x6Size, 32: atc8x5Size, 33: atc8x6Size, 34: atc8x8Size, 35: atc10x5Size, 36: atc10x6Size, 37: atc10x8Size, 38: atc10x10Size, 39: atc12x10Size, 40: atc12x12Size }; /** * Check if data is in "PVR" format by its magic number * @param data - binary data of compressed texture * @returns true - data in "PVR" format, else - false */ export function isPVR(data: ArrayBuffer): boolean { const header = new Uint32Array(data, 0, PVR_CONSTANTS.HEADER_LENGTH); const version = header[PVR_CONSTANTS.MAGIC_NUMBER_INDEX]; return version === PVR_CONSTANTS.MAGIC_NUMBER || version === PVR_CONSTANTS.MAGIC_NUMBER_EXTRA; } /** * Parse texture data as "PVR" format * @param data - binary data of compressed texture * @returns Array of the texture levels * @see http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf */ export function parsePVR(data: ArrayBuffer): TextureLevel[] { const header = new Uint32Array(data, 0, PVR_CONSTANTS.HEADER_LENGTH); const pvrFormat = header[PVR_CONSTANTS.PIXEL_FORMAT_INDEX]; const colourSpace = header[PVR_CONSTANTS.COLOUR_SPACE_INDEX]; const pixelFormats = PVR_PIXEL_FORMATS[pvrFormat] || []; const internalFormat = pixelFormats.length > 1 && colourSpace ? pixelFormats[1] : pixelFormats[0]; const sizeFunction = PVR_SIZE_FUNCTIONS[pvrFormat]; const mipMapLevels = header[PVR_CONSTANTS.MIPMAPCOUNT_INDEX]; const width = header[PVR_CONSTANTS.WIDTH_INDEX]; const height = header[PVR_CONSTANTS.HEIGHT_INDEX]; const dataOffset = PVR_CONSTANTS.HEADER_SIZE + header[PVR_CONSTANTS.METADATA_SIZE_INDEX]; const image = new Uint8Array(data, dataOffset); return extractMipmapImages(image, { mipMapLevels, width, height, sizeFunction, internalFormat }); } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/ function pvrtc2bppSize(width: number, height: number): number { width = Math.max(width, 16); height = Math.max(height, 8); return (width * height) / 4; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/ function pvrtc4bppSize(width: number, height: number): number { width = Math.max(width, 8); height = Math.max(height, 8); return (width * height) / 2; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc/ // Size for: // COMPRESSED_RGB_S3TC_DXT1_EXT // COMPRESSED_R11_EAC // COMPRESSED_SIGNED_R11_EAC // COMPRESSED_RGB8_ETC2 // COMPRESSED_SRGB8_ETC2 // COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 // COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 function dxtEtcSmallSize(width: number, height: number): number { return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc/ // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ // Size for: // COMPRESSED_RGBA_S3TC_DXT3_EXT // COMPRESSED_RGBA_S3TC_DXT5_EXT // COMPRESSED_RG11_EAC // COMPRESSED_SIGNED_RG11_EAC // COMPRESSED_RGBA8_ETC2_EAC // COMPRESSED_SRGB8_ALPHA8_ETC2_EAC // COMPRESSED_RGBA_ASTC_4x4_KHR function dxtEtcAstcBigSize(width: number, height: number): number { return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc5x4Size(width: number, height: number): number { return Math.floor((width + 4) / 5) * Math.floor((height + 3) / 4) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc5x5Size(width: number, height: number): number { return Math.floor((width + 4) / 5) * Math.floor((height + 4) / 5) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc6x5Size(width: number, height: number): number { return Math.floor((width + 5) / 6) * Math.floor((height + 4) / 5) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc6x6Size(width: number, height: number): number { return Math.floor((width + 5) / 6) * Math.floor((height + 5) / 6) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc8x5Size(width: number, height: number): number { return Math.floor((width + 7) / 8) * Math.floor((height + 4) / 5) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc8x6Size(width: number, height: number): number { return Math.floor((width + 7) / 8) * Math.floor((height + 5) / 6) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc8x8Size(width: number, height: number): number { return Math.floor((width + 7) / 8) * Math.floor((height + 7) / 8) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc10x5Size(width: number, height: number): number { return Math.floor((width + 9) / 10) * Math.floor((height + 4) / 5) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc10x6Size(width: number, height: number): number { return Math.floor((width + 9) / 10) * Math.floor((height + 5) / 6) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc10x8Size(width: number, height: number): number { return Math.floor((width + 9) / 10) * Math.floor((height + 7) / 8) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc10x10Size(width: number, height: number): number { return Math.floor((width + 9) / 10) * Math.floor((height + 9) / 10) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc12x10Size(width: number, height: number): number { return Math.floor((width + 11) / 12) * Math.floor((height + 9) / 10) * 16; } // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_astc/ function atc12x12Size(width: number, height: number): number { return Math.floor((width + 11) / 12) * Math.floor((height + 11) / 12) * 16; }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class AmplifyUIBuilder extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AmplifyUIBuilder.Types.ClientConfiguration) config: Config & AmplifyUIBuilder.Types.ClientConfiguration; /** * Creates a new component for an Amplify app. */ createComponent(params: AmplifyUIBuilder.Types.CreateComponentRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.CreateComponentResponse) => void): Request<AmplifyUIBuilder.Types.CreateComponentResponse, AWSError>; /** * Creates a new component for an Amplify app. */ createComponent(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.CreateComponentResponse) => void): Request<AmplifyUIBuilder.Types.CreateComponentResponse, AWSError>; /** * Creates a theme to apply to the components in an Amplify app. */ createTheme(params: AmplifyUIBuilder.Types.CreateThemeRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.CreateThemeResponse) => void): Request<AmplifyUIBuilder.Types.CreateThemeResponse, AWSError>; /** * Creates a theme to apply to the components in an Amplify app. */ createTheme(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.CreateThemeResponse) => void): Request<AmplifyUIBuilder.Types.CreateThemeResponse, AWSError>; /** * Deletes a component from an Amplify app. */ deleteComponent(params: AmplifyUIBuilder.Types.DeleteComponentRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a component from an Amplify app. */ deleteComponent(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a theme from an Amplify app. */ deleteTheme(params: AmplifyUIBuilder.Types.DeleteThemeRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a theme from an Amplify app. */ deleteTheme(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Exchanges an access code for a token. */ exchangeCodeForToken(params: AmplifyUIBuilder.Types.ExchangeCodeForTokenRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExchangeCodeForTokenResponse) => void): Request<AmplifyUIBuilder.Types.ExchangeCodeForTokenResponse, AWSError>; /** * Exchanges an access code for a token. */ exchangeCodeForToken(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExchangeCodeForTokenResponse) => void): Request<AmplifyUIBuilder.Types.ExchangeCodeForTokenResponse, AWSError>; /** * Exports component configurations to code that is ready to integrate into an Amplify app. */ exportComponents(params: AmplifyUIBuilder.Types.ExportComponentsRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExportComponentsResponse) => void): Request<AmplifyUIBuilder.Types.ExportComponentsResponse, AWSError>; /** * Exports component configurations to code that is ready to integrate into an Amplify app. */ exportComponents(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExportComponentsResponse) => void): Request<AmplifyUIBuilder.Types.ExportComponentsResponse, AWSError>; /** * Exports theme configurations to code that is ready to integrate into an Amplify app. */ exportThemes(params: AmplifyUIBuilder.Types.ExportThemesRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExportThemesResponse) => void): Request<AmplifyUIBuilder.Types.ExportThemesResponse, AWSError>; /** * Exports theme configurations to code that is ready to integrate into an Amplify app. */ exportThemes(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ExportThemesResponse) => void): Request<AmplifyUIBuilder.Types.ExportThemesResponse, AWSError>; /** * Returns an existing component for an Amplify app. */ getComponent(params: AmplifyUIBuilder.Types.GetComponentRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.GetComponentResponse) => void): Request<AmplifyUIBuilder.Types.GetComponentResponse, AWSError>; /** * Returns an existing component for an Amplify app. */ getComponent(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.GetComponentResponse) => void): Request<AmplifyUIBuilder.Types.GetComponentResponse, AWSError>; /** * Returns an existing theme for an Amplify app. */ getTheme(params: AmplifyUIBuilder.Types.GetThemeRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.GetThemeResponse) => void): Request<AmplifyUIBuilder.Types.GetThemeResponse, AWSError>; /** * Returns an existing theme for an Amplify app. */ getTheme(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.GetThemeResponse) => void): Request<AmplifyUIBuilder.Types.GetThemeResponse, AWSError>; /** * Retrieves a list of components for a specified Amplify app and backend environment. */ listComponents(params: AmplifyUIBuilder.Types.ListComponentsRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ListComponentsResponse) => void): Request<AmplifyUIBuilder.Types.ListComponentsResponse, AWSError>; /** * Retrieves a list of components for a specified Amplify app and backend environment. */ listComponents(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ListComponentsResponse) => void): Request<AmplifyUIBuilder.Types.ListComponentsResponse, AWSError>; /** * Retrieves a list of themes for a specified Amplify app and backend environment. */ listThemes(params: AmplifyUIBuilder.Types.ListThemesRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ListThemesResponse) => void): Request<AmplifyUIBuilder.Types.ListThemesResponse, AWSError>; /** * Retrieves a list of themes for a specified Amplify app and backend environment. */ listThemes(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.ListThemesResponse) => void): Request<AmplifyUIBuilder.Types.ListThemesResponse, AWSError>; /** * Refreshes a previously issued access token that might have expired. */ refreshToken(params: AmplifyUIBuilder.Types.RefreshTokenRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.RefreshTokenResponse) => void): Request<AmplifyUIBuilder.Types.RefreshTokenResponse, AWSError>; /** * Refreshes a previously issued access token that might have expired. */ refreshToken(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.RefreshTokenResponse) => void): Request<AmplifyUIBuilder.Types.RefreshTokenResponse, AWSError>; /** * Updates an existing component. */ updateComponent(params: AmplifyUIBuilder.Types.UpdateComponentRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.UpdateComponentResponse) => void): Request<AmplifyUIBuilder.Types.UpdateComponentResponse, AWSError>; /** * Updates an existing component. */ updateComponent(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.UpdateComponentResponse) => void): Request<AmplifyUIBuilder.Types.UpdateComponentResponse, AWSError>; /** * Updates an existing theme. */ updateTheme(params: AmplifyUIBuilder.Types.UpdateThemeRequest, callback?: (err: AWSError, data: AmplifyUIBuilder.Types.UpdateThemeResponse) => void): Request<AmplifyUIBuilder.Types.UpdateThemeResponse, AWSError>; /** * Updates an existing theme. */ updateTheme(callback?: (err: AWSError, data: AmplifyUIBuilder.Types.UpdateThemeResponse) => void): Request<AmplifyUIBuilder.Types.UpdateThemeResponse, AWSError>; } declare namespace AmplifyUIBuilder { export type Boolean = boolean; export interface Component { /** * The unique ID of the Amplify app associated with the component. */ appId: String; /** * The information to connect a component's properties to data at runtime. */ bindingProperties: ComponentBindingProperties; /** * A list of the component's ComponentChild instances. */ children?: ComponentChildList; /** * The data binding configuration for the component's properties. Use this for a collection component. */ collectionProperties?: ComponentCollectionProperties; /** * The type of the component. This can be an Amplify custom UI component or another custom component. */ componentType: ComponentType; /** * The time that the component was created. */ createdAt: SyntheticTimestamp_date_time; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The unique ID of the component. */ id: Uuid; /** * The time that the component was modified. */ modifiedAt?: SyntheticTimestamp_date_time; /** * The name of the component. */ name: ComponentName; /** * Describes the component's properties that can be overriden in a customized instance of the component. */ overrides: ComponentOverrides; /** * Describes the component's properties. */ properties: ComponentProperties; /** * The unique ID of the component in its original source system, such as Figma. */ sourceId?: String; /** * One or more key-value pairs to use when tagging the component. */ tags?: Tags; /** * A list of the component's variants. A variant is a unique style configuration of a main component. */ variants: ComponentVariants; } export type ComponentBindingProperties = {[key: string]: ComponentBindingPropertiesValue}; export interface ComponentBindingPropertiesValue { /** * Describes the properties to customize with data at runtime. */ bindingProperties?: ComponentBindingPropertiesValueProperties; /** * The default value of the property. */ defaultValue?: String; /** * The property type. */ type?: String; } export interface ComponentBindingPropertiesValueProperties { /** * An Amazon S3 bucket. */ bucket?: String; /** * The default value to assign to the property. */ defaultValue?: String; /** * The field to bind the data to. */ field?: String; /** * The storage key for an Amazon S3 bucket. */ key?: String; /** * An Amplify DataStore model. */ model?: String; /** * A list of predicates for binding a component's properties to data. */ predicates?: PredicateList; /** * An authenticated user attribute. */ userAttribute?: String; } export interface ComponentChild { /** * The list of ComponentChild instances for this component. */ children?: ComponentChildList; /** * The type of the child component. */ componentType: String; /** * The name of the child component. */ name: String; /** * Describes the properties of the child component. */ properties: ComponentProperties; } export type ComponentChildList = ComponentChild[]; export type ComponentCollectionProperties = {[key: string]: ComponentDataConfiguration}; export interface ComponentConditionProperty { /** * The value to assign to the property if the condition is not met. */ else?: ComponentProperty; /** * The name of a field. Specify this when the property is a data model. */ field?: String; /** * The value of the property to evaluate. */ operand?: String; /** * The operator to use to perform the evaluation, such as eq to represent equals. */ operator?: String; /** * The name of the conditional property. */ property?: String; /** * The value to assign to the property if the condition is met. */ then?: ComponentProperty; } export interface ComponentDataConfiguration { /** * A list of IDs to use to bind data to a component. Use this property to bind specifically chosen data, rather than data retrieved from a query. */ identifiers?: IdentifierList; /** * The name of the data model to use to bind data to a component. */ model: String; /** * Represents the conditional logic to use when binding data to a component. Use this property to retrieve only a subset of the data in a collection. */ predicate?: Predicate; /** * Describes how to sort the component's properties. */ sort?: SortPropertyList; } export type ComponentList = Component[]; export type ComponentName = string; export type ComponentOverrides = {[key: string]: ComponentOverridesValue}; export type ComponentOverridesValue = {[key: string]: String}; export type ComponentProperties = {[key: string]: ComponentProperty}; export interface ComponentProperty { /** * The information to bind the component property to data at runtime. */ bindingProperties?: ComponentPropertyBindingProperties; /** * The information to bind the component property to form data. */ bindings?: FormBindings; /** * The information to bind the component property to data at runtime. Use this for collection components. */ collectionBindingProperties?: ComponentPropertyBindingProperties; /** * A list of component properties to concatenate to create the value to assign to this component property. */ concat?: ComponentPropertyList; /** * The conditional expression to use to assign a value to the component property.. */ condition?: ComponentConditionProperty; /** * Specifies whether the user configured the property in Amplify Studio after importing it. */ configured?: Boolean; /** * The default value to assign to the component property. */ defaultValue?: String; /** * An event that occurs in your app. Use this for workflow data binding. */ event?: String; /** * The default value assigned to property when the component is imported into an app. */ importedValue?: String; /** * The data model to use to assign a value to the component property. */ model?: String; /** * The component type. */ type?: String; /** * An authenticated user attribute to use to assign a value to the component property. */ userAttribute?: String; /** * The value to assign to the component property. */ value?: String; } export interface ComponentPropertyBindingProperties { /** * The data field to bind the property to. */ field?: String; /** * The component property to bind to the data field. */ property: String; } export type ComponentPropertyList = ComponentProperty[]; export interface ComponentSummary { /** * The unique ID of the Amplify app associated with the component. */ appId: String; /** * The component type. */ componentType: ComponentType; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The unique ID of the component. */ id: Uuid; /** * The name of the component. */ name: ComponentName; } export type ComponentSummaryList = ComponentSummary[]; export type ComponentType = string; export interface ComponentVariant { /** * The properties of the component variant that can be overriden when customizing an instance of the component. */ overrides?: ComponentOverrides; /** * The combination of variants that comprise this variant. */ variantValues?: ComponentVariantValues; } export type ComponentVariantValues = {[key: string]: String}; export type ComponentVariants = ComponentVariant[]; export interface CreateComponentData { /** * The data binding information for the component's properties. */ bindingProperties: ComponentBindingProperties; /** * A list of child components that are instances of the main component. */ children?: ComponentChildList; /** * The data binding configuration for customizing a component's properties. Use this for a collection component. */ collectionProperties?: ComponentCollectionProperties; /** * The component type. This can be an Amplify custom UI component or another custom component. */ componentType: ComponentType; /** * The name of the component */ name: ComponentName; /** * Describes the component properties that can be overriden to customize an instance of the component. */ overrides: ComponentOverrides; /** * Describes the component's properties. */ properties: ComponentProperties; /** * The unique ID of the component in its original source system, such as Figma. */ sourceId?: String; /** * One or more key-value pairs to use when tagging the component data. */ tags?: Tags; /** * A list of the unique variants of this component. */ variants: ComponentVariants; } export interface CreateComponentRequest { /** * The unique ID of the Amplify app to associate with the component. */ appId: String; /** * The unique client token. */ clientToken?: String; /** * Represents the configuration of the component to create. */ componentToCreate: CreateComponentData; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; } export interface CreateComponentResponse { /** * Describes the configuration of the new component. */ entity?: Component; } export interface CreateThemeData { /** * The name of the theme. */ name: ThemeName; /** * Describes the properties that can be overriden to customize an instance of the theme. */ overrides?: ThemeValuesList; /** * One or more key-value pairs to use when tagging the theme data. */ tags?: Tags; /** * A list of key-value pairs that defines the properties of the theme. */ values: ThemeValuesList; } export interface CreateThemeRequest { /** * The unique ID of the Amplify app associated with the theme. */ appId: String; /** * The unique client token. */ clientToken?: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * Represents the configuration of the theme to create. */ themeToCreate: CreateThemeData; } export interface CreateThemeResponse { /** * Describes the configuration of the new theme. */ entity?: Theme; } export interface DeleteComponentRequest { /** * The unique ID of the Amplify app associated with the component to delete. */ appId: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The unique ID of the component to delete. */ id: Uuid; } export interface DeleteThemeRequest { /** * The unique ID of the Amplify app associated with the theme to delete. */ appId: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The unique ID of the theme to delete. */ id: Uuid; } export interface ExchangeCodeForTokenRequest { /** * The third-party provider for the token. The only valid value is figma. */ provider: TokenProviders; /** * Describes the configuration of the request. */ request: ExchangeCodeForTokenRequestBody; } export interface ExchangeCodeForTokenRequestBody { /** * The access code to send in the request. */ code: SyntheticExchangeCodeForTokenRequestBodyString; /** * The location of the application that will receive the access code. */ redirectUri: String; } export interface ExchangeCodeForTokenResponse { /** * The access token. */ accessToken: SyntheticExchangeCodeForTokenResponseString; /** * The date and time when the new access token expires. */ expiresIn: Integer; /** * The token to use to refresh a previously issued access token that might have expired. */ refreshToken: SyntheticExchangeCodeForTokenResponseString; } export interface ExportComponentsRequest { /** * The unique ID of the Amplify app to export components to. */ appId: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; } export interface ExportComponentsResponse { /** * Represents the configuration of the exported components. */ entities: ComponentList; } export interface ExportThemesRequest { /** * The unique ID of the Amplify app to export the themes to. */ appId: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; } export interface ExportThemesResponse { /** * Represents the configuration of the exported themes. */ entities: ThemeList; } export interface FormBindingElement { /** * The name of the component to retrieve a value from. */ element: String; /** * The property to retrieve a value from. */ property: String; } export type FormBindings = {[key: string]: FormBindingElement}; export interface GetComponentRequest { /** * The unique ID of the Amplify app. */ appId: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; /** * The unique ID of the component. */ id: Uuid; } export interface GetComponentResponse { /** * Represents the configuration settings for the component. */ component?: Component; } export interface GetThemeRequest { /** * The unique ID of the Amplify app. */ appId: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; /** * The unique ID for the theme. */ id: Uuid; } export interface GetThemeResponse { /** * Represents the configuration settings for the theme. */ theme?: Theme; } export type IdentifierList = String[]; export type Integer = number; export type ListComponentsLimit = number; export interface ListComponentsRequest { /** * The unique ID for the Amplify app. */ appId: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The maximum number of components to retrieve. */ maxResults?: ListComponentsLimit; /** * The token to request the next page of results. */ nextToken?: String; } export interface ListComponentsResponse { /** * The list of components for the Amplify app. */ entities: ComponentSummaryList; /** * The pagination token that's included if more results are available. */ nextToken?: String; } export type ListThemesLimit = number; export interface ListThemesRequest { /** * The unique ID for the Amplify app. */ appId: String; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The maximum number of theme results to return in the response. */ maxResults?: ListThemesLimit; /** * The token to request the next page of results. */ nextToken?: String; } export interface ListThemesResponse { /** * The list of themes for the Amplify app. */ entities: ThemeSummaryList; /** * The pagination token that's returned if more results are available. */ nextToken?: String; } export interface Predicate { /** * A list of predicates to combine logically. */ and?: PredicateList; /** * The field to query. */ field?: String; /** * The value to use when performing the evaluation. */ operand?: String; /** * The operator to use to perform the evaluation. */ operator?: String; /** * A list of predicates to combine logically. */ or?: PredicateList; } export type PredicateList = Predicate[]; export interface RefreshTokenRequest { /** * The third-party provider for the token. The only valid value is figma. */ provider: TokenProviders; /** * Information about the refresh token request. */ refreshTokenBody: RefreshTokenRequestBody; } export interface RefreshTokenRequestBody { /** * The token to use to refresh a previously issued access token that might have expired. */ token: SyntheticRefreshTokenRequestBodyString; } export interface RefreshTokenResponse { /** * The access token. */ accessToken: SyntheticRefreshTokenResponseString; /** * The date and time when the new access token expires. */ expiresIn: Integer; } export type SortDirection = "ASC"|"DESC"|string; export interface SortProperty { /** * The direction of the sort, either ascending or descending. */ direction: SortDirection; /** * The field to perform the sort on. */ field: String; } export type SortPropertyList = SortProperty[]; export type String = string; export type SyntheticExchangeCodeForTokenRequestBodyString = string; export type SyntheticExchangeCodeForTokenResponseString = string; export type SyntheticRefreshTokenRequestBodyString = string; export type SyntheticRefreshTokenResponseString = string; export type SyntheticTimestamp_date_time = Date; export type TagKey = string; export type TagValue = string; export type Tags = {[key: string]: TagValue}; export interface Theme { /** * The unique ID for the Amplify app associated with the theme. */ appId: String; /** * The time that the theme was created. */ createdAt: SyntheticTimestamp_date_time; /** * The name of the backend environment that is a part of the Amplify app. */ environmentName: String; /** * The ID for the theme. */ id: Uuid; /** * The time that the theme was modified. */ modifiedAt?: SyntheticTimestamp_date_time; /** * The name of the theme. */ name: ThemeName; /** * Describes the properties that can be overriden to customize a theme. */ overrides?: ThemeValuesList; /** * One or more key-value pairs to use when tagging the theme. */ tags?: Tags; /** * A list of key-value pairs that defines the properties of the theme. */ values: ThemeValuesList; } export type ThemeList = Theme[]; export type ThemeName = string; export interface ThemeSummary { /** * The unique ID for the app associated with the theme summary. */ appId: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; /** * The ID of the theme. */ id: Uuid; /** * The name of the theme. */ name: ThemeName; } export type ThemeSummaryList = ThemeSummary[]; export interface ThemeValue { /** * A list of key-value pairs that define the theme's properties. */ children?: ThemeValuesList; /** * The value of a theme property. */ value?: String; } export interface ThemeValues { /** * The name of the property. */ key?: String; /** * The value of the property. */ value?: ThemeValue; } export type ThemeValuesList = ThemeValues[]; export type TokenProviders = "figma"|string; export interface UpdateComponentData { /** * The data binding information for the component's properties. */ bindingProperties?: ComponentBindingProperties; /** * The components that are instances of the main component. */ children?: ComponentChildList; /** * The configuration for binding a component's properties to a data model. Use this for a collection component. */ collectionProperties?: ComponentCollectionProperties; /** * The type of the component. This can be an Amplify custom UI component or another custom component. */ componentType?: ComponentType; /** * The unique ID of the component to update. */ id?: Uuid; /** * The name of the component to update. */ name?: ComponentName; /** * Describes the properties that can be overriden to customize the component. */ overrides?: ComponentOverrides; /** * Describes the component's properties. */ properties?: ComponentProperties; /** * The unique ID of the component in its original source system, such as Figma. */ sourceId?: String; /** * A list of the unique variants of the main component being updated. */ variants?: ComponentVariants; } export interface UpdateComponentRequest { /** * The unique ID for the Amplify app. */ appId: String; /** * The unique client token. */ clientToken?: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; /** * The unique ID for the component. */ id: Uuid; /** * The configuration of the updated component. */ updatedComponent: UpdateComponentData; } export interface UpdateComponentResponse { /** * Describes the configuration of the updated component. */ entity?: Component; } export interface UpdateThemeData { /** * The unique ID of the theme to update. */ id?: Uuid; /** * The name of the theme to update. */ name?: ThemeName; /** * Describes the properties that can be overriden to customize the theme. */ overrides?: ThemeValuesList; /** * A list of key-value pairs that define the theme's properties. */ values: ThemeValuesList; } export interface UpdateThemeRequest { /** * The unique ID for the Amplify app. */ appId: String; /** * The unique client token. */ clientToken?: String; /** * The name of the backend environment that is part of the Amplify app. */ environmentName: String; /** * The unique ID for the theme. */ id: Uuid; /** * The configuration of the updated theme. */ updatedTheme: UpdateThemeData; } export interface UpdateThemeResponse { /** * Describes the configuration of the updated theme. */ entity?: Theme; } export type Uuid = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2021-08-11"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the AmplifyUIBuilder client. */ export import Types = AmplifyUIBuilder; } export = AmplifyUIBuilder;
the_stack
import { Button, FormControl, FormHelperText, FormLabel, Input, Select, } from "@chakra-ui/react"; import { OWNER_ROLE } from "@/features/roles"; import { Organization, OrganizationUser, Role, User } from "@prisma/client"; import { PlusIcon } from "@heroicons/react/outline"; import { isUndefined } from "lodash"; import { useBoolean } from "react-use"; import { useGetOrganizationQuery, useRemoveMemberMutation, useUpdateMemberRoleMutation, } from "@/features/organizations/api-slice"; import { useInviteMemberMutation } from "@/features/organizations/api-slice"; import { useOrganizationFromProfile, useProfile, useSegment } from "@/hooks"; import { useRouter } from "next/router"; import ColumnListItem from "@/components/ColumnListItem"; import Layout from "@/components/Layout"; import OrganizationSidebar from "@/components/OrganizationSidebar"; import PageWrapper from "@/components/PageWrapper"; import React, { useEffect, useMemo, useState } from "react"; type CustomOrganization = Organization & { users: User[]; roles: Role[] }; const ADD_NEW_ROLE_ID = "addNewRole"; const RolesSelector = ({ roleId, roles, onChange, organizationSlug, }: { roleId?: number; roles: Role[]; onChange: (e: any) => void; organizationSlug: string; }) => { const router = useRouter(); const { role: profileRole } = useProfile(); const handleChange = async (e: any) => { if (e.currentTarget.value === ADD_NEW_ROLE_ID) { await router.push(`/organizations/${organizationSlug}/roles`); } else { onChange(e); } }; useSegment("Visited members page", { page: "members", }); return ( <FormControl id="role"> <FormLabel>Role</FormLabel> <Select value={roleId} onChange={handleChange}> {roles .filter( (role: Record<string, any>) => profileRole.name === OWNER_ROLE || (profileRole.name !== OWNER_ROLE && role.name !== OWNER_ROLE) ) .map((role: Record<string, any>) => ( <option key={role.id} value={role.id}> {role.name} </option> ))} <optgroup label="-"></optgroup> <option value={ADD_NEW_ROLE_ID}>+ Add new role</option> </Select> </FormControl> ); }; const EditCurrentUser = ({ organizationUser, organization, }: { organizationUser?: any; organization: CustomOrganization; }) => { const user = useMemo(() => organizationUser?.user, [organizationUser]); const [updateUserRole, { isLoading }] = useUpdateMemberRoleMutation(); const changeUserRole = async (roleId: string) => { await updateUserRole({ organizationId: organization?.id?.toString(), userId: organizationUser?.id?.toString(), body: { roleId: parseInt(roleId), }, }); }; const [removeMember, { isLoading: isRemoving }] = useRemoveMemberMutation(); const handleDelete = async () => { if (isRemoving) return; if (confirm("Are you sure you want to remove this member?")) { await removeMember({ organizationId: organization?.id?.toString(), userId: organizationUser.id, }); } }; return ( <div className="w-full h-full flex flex-col justify-between"> <div> {user && ( <> <PageWrapper.Section> <PageWrapper.Heading> {user.firstName} {user.lastName} </PageWrapper.Heading> <div className="mb-2">Email: {user.email}</div> <RolesSelector organizationSlug={organization.slug} roleId={organizationUser.role?.id} roles={organization?.roles} onChange={(e: any) => changeUserRole(e.currentTarget.value)} /> </PageWrapper.Section> </> )} </div> <div className="grid grid-cols-3"> <div> {organizationUser?.role?.name !== OWNER_ROLE && ( <a className="text-red-600 text-sm cursor-pointer" onClick={handleDelete} > Remove member </a> )} </div> {/* <Button colorScheme="blue" size="sm" width="300px" onClick={handleSave}> Save </Button> */} <div className="flex justify-end"></div> </div> </div> ); }; const CreateUser = ({ organization }: { organization: CustomOrganization }) => { const [user, setUser] = useState({ email: "", roleId: organization?.roles[0]?.id, }); const [inviteMember, { isLoading }] = useInviteMemberMutation(); const handleInvite = async (e: any) => { e.preventDefault(); await inviteMember({ organizationId: organization.id.toString(), body: user, }); setUser({ email: "", roleId: organization?.roles[0]?.id, }); }; return ( <form onSubmit={handleInvite} className="h-full"> <div className="w-full h-full flex flex-col justify-between"> <div> {user && ( <> <PageWrapper.Section> <PageWrapper.Heading>Invite member</PageWrapper.Heading> <div className="space-y-4"> <FormControl id="email"> <FormLabel>Email address</FormLabel> <Input type="email" value={user.email} placeholder="tim@apple.com" onChange={(e) => setUser({ ...user, email: e.currentTarget.value, }) } /> <FormHelperText>Your teammates work email.</FormHelperText> </FormControl> <RolesSelector organizationSlug={organization.slug} roleId={user.roleId} roles={organization?.roles} onChange={(e: any) => setUser({ ...user, roleId: parseInt(e.currentTarget.value), }) } /> </div> </PageWrapper.Section> </> )} </div> <div className="grid grid-cols-3"> <div></div> <Button colorScheme="blue" size="sm" width="300px" type="submit" isLoading={isLoading} > Invite </Button> <div></div> </div> </div> </form> ); }; function Members() { const router = useRouter(); const [addNew, toggleAddNew] = useBoolean(false); const temporaryOrganization = useOrganizationFromProfile({ slug: router.query.organizationSlug as string, }); const { data: organizationsResponse, isLoading, isFetching, } = useGetOrganizationQuery( { organizationId: temporaryOrganization?.id?.toString() }, { skip: !temporaryOrganization?.id } ); const organization = useMemo( () => organizationsResponse?.data, [organizationsResponse] ); const [currentUserId, setCurrentUserId] = useState<number>(); const currentOrganizationUser = useMemo( () => organization?.users.find( (orgUser: any) => orgUser.user.id === currentUserId ), [currentUserId, organization?.users] ); const currentUser = useMemo( () => currentOrganizationUser?.user, [currentOrganizationUser] ); const [localOrgUser, setLocalOrgUser] = useState(); const userLabel = (user: { user: { firstName?: string; lastName?: string; email: string; }; }) => { if (user?.user?.firstName && user?.user?.lastName) { return `${user?.user?.firstName} ${user?.user?.lastName}`; } return user?.user?.email; }; useEffect(() => { if (isUndefined(currentUserId) && organization?.users?.length > 0) { setCurrentUserId(organization.users[0]?.user?.id); } }, []); useEffect(() => { setLocalOrgUser(currentOrganizationUser); }, [currentOrganizationUser]); return ( <Layout sidebar={<OrganizationSidebar organization={organization} />}> <PageWrapper crumbs={[organization?.name, "Members"]} flush={true} isLoading={isLoading || isFetching} > <div className="relative flex-1 max-w-full w-full flex"> <div className="flex flex-shrink-0 w-1/4 border-r"> <div className="w-full relative p-4"> <div className="mb-2">Members</div> {organization?.users && organization?.users.map( (user: OrganizationUser & { user: User }, idx: number) => ( <ColumnListItem key={user?.user?.id} active={user?.user?.id === currentUserId && !addNew} onClick={() => { setCurrentUserId(user?.user?.id); toggleAddNew(false); }} > {userLabel(user as any)} </ColumnListItem> ) )} <div className="mt-2"> <ColumnListItem active={addNew} icon={<PlusIcon className="h-4" />} onClick={() => toggleAddNew(true)} > Invite member </ColumnListItem> </div> </div> </div> <div className="flex-1 p-4"> {!addNew && localOrgUser && organization && ( <EditCurrentUser organizationUser={localOrgUser} organization={organization} /> )} {addNew && organization && ( <CreateUser organization={organization} /> )} </div> </div> </PageWrapper> </Layout> ); } export default Members;
the_stack
import { Injectable } from "@angular/core"; import { createWorker, ITypedWorker } from "typed-web-workers"; import { getUrl } from "./main.service"; import { EnemyManager } from "./model/enemy/enemyManager"; import { BattleRequest, ShipData } from "./workers/battleRequest"; import { Emitters } from "./emitters"; import { Enemy } from "./model/enemy/enemy"; declare let MyFromDecimal: (arg: any) => Decimal; @Injectable({ providedIn: "root" }) export class BattleService { private static instance: BattleService; battleWorker: ITypedWorker<BattleRequest, BattleResult>; em: Emitters; enemy: Enemy; constructor() { BattleService.instance = this; const url = getUrl(); this.battleWorker = createWorker({ workerFunction: this.doBattle, onMessage: this.onBattleEnd.bind(this), onError: error => {}, importScripts: [ url + "break_infinity.min.js", url + "assets/is.js" // url + "assets/ship.js", // url + "assets/battleResult.js", // url + "assets/myUtility.js" ] }); } static getInstance(): BattleService { return BattleService.instance; } doBattle(input: BattleRequest, cb: (_: BattleResult) => void): void { // console.log(input); const initial = Date.now(); const playerShips = new Array<Ship>(); const enemyShip = new Array<Ship>(); //#region Initialize Fleets const fleets: Array<[Ship[], ShipData[]]> = [ [enemyShip, input.enemyFleet], [playerShips, input.playerFleet] ]; fleets.forEach(toMake => { const ships = toMake[0]; const design = toMake[1]; design.forEach(ds => { const ship = new Ship(); ship.id = ds.id; ship.class = ds.class; ship.isDefense = ds.isDefense; ship.armor = MyFromDecimal(ds.totalArmor); ship.originalArmor = MyFromDecimal(ship.armor); ship.shield = MyFromDecimal(ds.totalShield); ship.originalShield = MyFromDecimal(ship.shield); ship.explosionLevel = ds.explosionLevel / 100; ship.armorReduction = MyFromDecimal(ds.armorReduction); ship.shieldReduction = MyFromDecimal(ds.shieldReduction); ship.shieldCharger = MyFromDecimal(ds.shieldCharger); ds.modules.forEach(dl => { if (MyFromDecimal(dl.computedDamage).gt(0)) { ship.modules.push({ damage: MyFromDecimal(dl.computedDamage), shieldPercent: dl.shieldPercent, armorPercent: dl.armorPercent }); } }); const qta = MyFromDecimal(ds.quantity).toNumber(); for (let num = 0; num < qta; num++) { const copy = ship.getCopy(); copy.fleetIndex = ships.push(copy) - 1; } }); }); // console.log("player ships: " + playerShips.length); // console.log("enemy ships: " + enemyShip.length); //#endregion //#region Battle // Up to 5 rounds const battleFleets = [playerShips, enemyShip]; // for each round // Ships are assumed to all attack at the same time for (let round = 0; round < 5; round++) { // for both player and enemy fleets for (let num = 0; num < 2; num++) { const ships = battleFleets[num]; const targets = battleFleets[(num + 1) % 2]; // Create a copy of targets so it's simpler to implement const all = []; const defenders = []; const ground = []; for (const target of targets) { all.push(target); if (target.class === "3") { defenders.push(target); } if (target.isDefense) { ground.push(target); } } // console.log(defenders.length); for (const ship of ships) { let availableTargets = all; // Bomber can only hit grounded target if (ship.class === "2") { // skip early if there no ground unit if (ground.length === 0) continue; availableTargets = ground; } else if ( // 80% chance of hitting a defender defenders.length > 0 && Math.random() < 0.8 ) { availableTargets = defenders; } if (availableTargets.length === 0) continue; for (const weapon of ship.modules) { const target = availableTargets[ Math.floor(Math.random() * availableTargets.length) ]; // targeted dead ship, consider attack as missed if (target.armor.lt(0)) continue; let damageToDo = weapon.damage; // Damage to shield if (target.shield.gt(0)) { const shieldPercent = weapon.shieldPercent / 100; const maxShieldDamage = damageToDo .times(shieldPercent) .minus(target.shieldReduction) .max(0); // Skip if damage <0.1% shield if (maxShieldDamage.lt(target.shield.div(1000))) continue; target.shield = target.shield.minus(maxShieldDamage); if (target.shield.gte(0)) continue; damageToDo = target.shield .minus(target.shieldReduction) .abs() .div(shieldPercent); // console.log(damageToDo.toNumber()); } // Damage to Armor if (damageToDo.gt(0)) { const maxArmorDamage = damageToDo .times(weapon.armorPercent / 100) .minus(target.armorReduction) .max(0); // Skip if damage < 0.1% armor if (maxArmorDamage.lt(target.armor.div(1000))) continue; target.armor = target.armor.minus(maxArmorDamage); // Check explosion // console.log( // target.armor.div(target.originalArmor).toNumber() + // " - " + // target.explosionLevel // ); if ( target.armor.gt(0) && target.armor.div(target.originalArmor).toNumber() < target.explosionLevel ) { const prob = 1 - target.armor .div(target.originalArmor.times(target.explosionLevel)) .toNumber(); // console.log( // "Expl:" + // target.armor.toNumber() + // " " + // target.originalArmor.toNumber() + // " " + // target.explosionLevel + // " " + // prob // ); if (Math.random() < prob) { // Explode target.armor.fromNumber(-1); } } // Remove dead ship if (target.armor.lt(0)) { target.free(); const last_target = targets.pop(); // Modify target array inplace without shifting every item (optimization) if (target !== last_target) { // Take the last target in array and put it where the target was. last_target.fleetIndex = target.fleetIndex; targets[target.fleetIndex] = last_target; } } } } // If all target are dead, skip the rest of the ships in fleet. if (targets.length === 0) { // console.log("break"); break; } } } // If one of the fleet is dead if (battleFleets[0].length < 1 || battleFleets[1].length < 1) break; // Recharge shields for (const ships of battleFleets) { let totalCharge = ships.reduce( (p, s) => p.plus(s.shieldCharger), new Decimal(0) ); // console.log("total charge: " + totalCharge.toNumber()); if (totalCharge.gt(0)) { const sorted = ships .filter(s => s.shield.gt(0)) .sort((a, b) => a.shield.div(a.originalShield).cmp(b.shield.div(b.originalShield)) ); for (const ship of sorted) { const missing = ship.originalShield .minus(ship.shield) .min(totalCharge); ship.shield = ship.shield.plus(missing); totalCharge = totalCharge.minus(missing); // console.log(totalCharge.toNumber()); if (totalCharge.lte(0)) break; // console.log("charged: " + missing.toNumber()); } } } // Regenerate shields // playerShips // .concat(enemyShip) // .filter(s => s.shield.gt(0)) // .forEach(s => { // s.shield = new Decimal(s.originalShield); // }); } //#endregion //#region Return const ret = new BattleResult(); if (enemyShip.length < 1) ret.result = "1"; const retArr: Array<[ShipData[], Ship[], Array<[string, Decimal]>]> = [ [input.playerFleet, playerShips, ret.playerLost], [input.enemyFleet, enemyShip, ret.enemyLost] ]; retArr.forEach(arr => { const fleetCount = {}; arr[0].forEach(fl => { fleetCount[fl.id] = 0; }); // Count and free the ships object for (const ship of arr[1]) { fleetCount[ship.id] += 1; ship.free(); } arr[0].forEach(fl => { const alive = fleetCount[fl.id]; const qta = MyFromDecimal(fl.quantity); if (qta.gt(alive)) { arr[2].push([fl.id, qta.minus(alive)]); } }); }); const diff = Math.max(input.minTime * 1000 - Date.now() + initial, 5); if (diff > 0) { // console.log("wait:" + diff); setTimeout(() => cb(ret), diff); } else { cb(ret); } //#endregion } onBattleEnd(result: BattleResult): void { EnemyManager.getInstance().onBattleEnd(result); if (this.em) { this.em.updateEmitter.emit(2); this.em.battleEndEmitter.emit(1); } } }
the_stack
import * as React from 'react' import Editor from 'draft-js-plugins-editor' import { EditorState, SelectionState, ContentState, RichUtils, getDefaultKeyBinding, KeyBindingUtil, Modifier, genKey, ContentBlock, DefaultDraftBlockRenderMap, convertFromHTML } from 'draft-js' import createMarkdownPlugin from 'draft-js-markdown-plugin' import { List, Map, Set } from 'immutable' import { CodeCell } from './CodeCell' import { WorkbookSession, SessionEvent, SessionEventKind } from '../WorkbookSession' import { MonacoCellMapper, WorkbookCompletionItemProvider, WorkbookHoverProvider, WorkbookSignatureHelpProvider } from '../utils/MonacoUtils' import { EditorMessage, EditorMessageType, EditorKeys } from '../utils/EditorMessages' import { getNextBlockFor, getPrevBlockFor, isBlockBackwards } from '../utils/DraftStateUtils' import { EditorMenu, getBlockStyle, styleMap } from './Menu' import { WorkbookShellContext } from './WorkbookShell'; import { convertToMarkdown, convertFromMarkdown } from '../utils/DraftSaveLoadUtils' import './WorkbookEditor.scss' interface WorkbooksEditorProps { shellContext: WorkbookShellContext content: string | undefined } interface WorkbooksEditorState { editorState: EditorState, plugins: any[], readOnly: boolean } interface WorkbookCellIdMapping { codeCellId: string monacoModelId: string } const blockRenderMap = DefaultDraftBlockRenderMap.merge(Map({ 'code-block': { element: 'div' } })); type DraftBlockType = "header-one" | "header-two" | "header-three" | "header-four" | "header-five" | "header-six" | "blockquote" | "code-block" | "atomic" | "unordered-list-item" | "ordered-list-item" | "unstyled"; export class WorkbookEditor extends React.Component<WorkbooksEditorProps, WorkbooksEditorState> implements MonacoCellMapper { subscriptors: ((m: EditorMessage) => void)[]; monacoProviderTickets: monaco.IDisposable[] = []; cellIdMappings: WorkbookCellIdMapping[] = []; focusedCodeEditors: Set<string> = Set() editorContainer: HTMLDivElement | null = null constructor(props: WorkbooksEditorProps) { super(props); this.onSessionEvent = this.onSessionEvent.bind(this) this.subscriptors = [] const editorState = EditorState.createEmpty() this.state = { editorState: editorState, plugins: [createMarkdownPlugin()], readOnly: true } // Monaco intellisense providers must be registered globally, not on a // per-editor basis. This is why the providers need a mapping from // Monaco model ID to Workbook cell ID. this.monacoProviderTickets.push( monaco.languages.registerCompletionItemProvider( "csharp", new WorkbookCompletionItemProvider(this.props.shellContext, this))) this.monacoProviderTickets.push( monaco.languages.registerHoverProvider( "csharp", new WorkbookHoverProvider(this.props.shellContext, this))) this.monacoProviderTickets.push( monaco.languages.registerSignatureHelpProvider( "csharp", new WorkbookSignatureHelpProvider(this.props.shellContext, this))) } private onSessionEvent(session: WorkbookSession, sessionEvent: SessionEvent) { this.setState({ readOnly: sessionEvent.kind !== SessionEventKind.Ready }) } componentDidMount() { this.props.shellContext.session.sessionEvent.addListener(this.onSessionEvent) this.focus() } componentWillUnmount() { this.props.shellContext.session.sessionEvent.removeListener(this.onSessionEvent) for (let ticket of this.monacoProviderTickets) ticket.dispose() } focus(e?: React.MouseEvent<{}>) { (this.refs.editor as any).focus(); // Only do this if the editor container was clicked. if (e && this.editorContainer && e.target === this.editorContainer) { // Select the last block let editorState = this.state.editorState; const currentContent = editorState.getCurrentContent(); let lastBlock = currentContent.getBlocksAsArray().slice(-1)[0]; if (lastBlock.getType() === "code-block") { lastBlock = this.createNewEmptyBlock("unstyled"); editorState = this.insertBlockIntoState(lastBlock, "last", false); } const nextSelection = (SelectionState.createEmpty(lastBlock.getKey()) .set('anchorOffset', lastBlock.getText().length) .set('focusOffset', lastBlock.getText().length) as SelectionState); editorState = EditorState.forceSelection(editorState, nextSelection); this.onChange(editorState); } } onChange(editorState: EditorState) { this.setState({ editorState }) } blockRenderer(block: Draft.ContentBlock) { if (block.getType() === 'code-block') { const codeCellId: string = block.getData().get("codeCellId"); return { component: CodeCell, editable: false, props: { shellContext: this.props.shellContext, rendererRegistry: this.props.shellContext.rendererRegistry, sendEditorMessage: (message: EditorMessage) => this.sendMessage(message), cellMapper: this, codeCellId, codeCellBlurred: (currentKey: string) => this.codeCellBlurred(currentKey), codeCellFocused: (currentKey: string) => this.codeCellFocused(currentKey), subscribeToEditor: (callback: () => void) => this.addMessageSubscriber(callback), selectNext: (currentKey: string) => this.selectNext(currentKey), selectPrevious: (currentKey: string) => this.selectPrevious(currentKey), updateTextContentOfBlock: (blockKey: string, textContent: string) => this.updateTextContentOfBlock(blockKey, textContent), setSelection: (anchorKey: string, offset: number) => this.setSelection(anchorKey, offset), getPreviousCodeBlock: (currentBlock: string) => this.getPreviousCodeBlock(currentBlock), updateBlockCodeCellId: (currentBlock: string, codeCellId: string) => this.updateBlockCodeCellId(currentBlock, codeCellId), appendNewCodeCell: () => this.appendNewCodeCell(), } } } return null } // Blur event for old cell may come in after focus event for new cell, so // we need to actually track the collection of code cells that claim to be // focused. Markdown content needs to be in read-only mode whenever a code // cell has focus. codeCellBlurred(currentKey: string) { this.focusedCodeEditors = this.focusedCodeEditors.remove(currentKey) this.editorReadOnly(!this.focusedCodeEditors.isEmpty()) } codeCellFocused(currentKey: string) { this.focusedCodeEditors = this.focusedCodeEditors.add(currentKey) this.editorReadOnly(!this.focusedCodeEditors.isEmpty()) } registerCellInfo(codeCellId: string, monacoModelId: string) { this.cellIdMappings.push({ codeCellId: codeCellId, monacoModelId: monacoModelId }) } getCodeCellId(monacoModelId: string) { for (let mapping of this.cellIdMappings) if (mapping.monacoModelId == monacoModelId) return mapping.codeCellId return null } updateBlockCodeCellId(currentBlock: string, codeCellId: string) { // FIXME: In the future, we should try not to reconstruct the entire state. const content = this.state.editorState.getCurrentContent(); const block = content.getBlockForKey(currentBlock); const newBlockData = (block.get("data") as Map<string, any>).set("codeCellId", codeCellId); const newBlock = block.set("data", newBlockData) as ContentBlock; const newBlockMap = content.getBlockMap().set(currentBlock, newBlock); const newContent = ContentState.createFromBlockArray(newBlockMap.toArray()); this.onChange(EditorState.push(this.state.editorState, newContent, "change-block-data")); } getPreviousCodeBlock(currentBlock: string) { const codeBlocks = this.state.editorState.getCurrentContent().getBlocksAsArray().filter((block: ContentBlock) => { return block.getType() === "code-block" }); const currentBlockIndex = codeBlocks.findIndex((block: ContentBlock) => block.getKey() == currentBlock); return codeBlocks[currentBlockIndex - 1]; } setUpInitialState(): any { const newBlocks = convertFromHTML("<h1>Welcome to Workbooks!</h1>").contentBlocks.concat( this.createNewEmptyBlock("code-block")) const newContentState = ContentState.createFromBlockArray(newBlocks); const newEditorState = EditorState.createWithContent(newContentState); this.onChange(newEditorState); } appendNewCodeCell() { const lastBlock = this.state.editorState.getCurrentContent().getBlocksAsArray().slice(-1)[0]; let editorState = this.state.editorState; if (lastBlock.getType() === "code-block") editorState = this.insertBlockIntoState(this.createNewEmptyBlock("unstyled"), "last", false); editorState = this.insertBlockIntoState(this.createNewEmptyBlock("code-block"), "last", false); this.onChange(editorState) } createNewEmptyBlock(blockType: DraftBlockType): ContentBlock { const newBlock = new ContentBlock({ key: genKey(), type: blockType, text: "", characterList: List() }); return newBlock; } insertBlockIntoState(block: ContentBlock, insertPosition: "first" | "last" | Number, updateState: boolean): EditorState { const currentContent = this.state.editorState.getCurrentContent() const newBlockMap = currentContent.getBlockMap().set(block.getKey(), block) const blockArray = newBlockMap.toArray() const newBlockIndex = -1 if (typeof insertPosition === "string") { if (insertPosition === "first") blockArray.unshift(block); else blockArray.push(block); } else if (typeof insertPosition === "number") { blockArray.splice(insertPosition, 0, block); } const contentState = ContentState.createFromBlockArray(blockArray); const newState = EditorState.push(this.state.editorState, contentState, "insert-fragment"); if (updateState) this.onChange(newState); return newState; } selectNext(currentKey: string): boolean { this.editorReadOnly(false) const currentContent = this.getSelectionContext().currentContent let nextBlock = getNextBlockFor(currentContent, currentKey) let editorState = this.state.editorState; if (!nextBlock) { const currentBlockType = currentContent.getBlockForKey(currentKey).getType(); if (currentBlockType !== "code-block") return false; nextBlock = this.createNewEmptyBlock("unstyled"); editorState = this.insertBlockIntoState(nextBlock, "last", false); } let nextSelection: SelectionState = (SelectionState.createEmpty(nextBlock.getKey()) .set('anchorOffset', 0) .set('focusOffset', 0) as SelectionState) editorState = EditorState.forceSelection(editorState, nextSelection) this.onChange(editorState); if (nextBlock.getType() !== "code-block") this.focus() return true } selectPrevious(currentKey: string): boolean { this.editorReadOnly(false) const currentContent = this.getSelectionContext().currentContent; let nextBlock = getPrevBlockFor(currentContent, currentKey) let editorState = this.state.editorState if (!nextBlock) { const currentBlockType = currentContent.getBlockForKey(currentKey).getType(); if (currentBlockType !== "code-block") return false; nextBlock = this.createNewEmptyBlock("unstyled"); editorState = this.insertBlockIntoState(nextBlock, "first", false); } let nextSelection: SelectionState = (SelectionState.createEmpty(nextBlock.getKey()) .set('anchorOffset', nextBlock.getText().length) .set('focusOffset', nextBlock.getText().length) as SelectionState) editorState = EditorState.forceSelection(editorState, nextSelection) this.onChange(editorState) if (nextBlock.getType() !== "code-block") this.focus() return true } /** * Set readonly editor to fix bad behaviours moving focus between code blocks and text * https://draftjs.org/docs/advanced-topics-block-components.html#recommendations-and-other-notes * @param {boolean} readOnly */ editorReadOnly(readOnly: boolean) { this.setState({ readOnly }) } updateTextContentOfBlock(blockKey: string, textContent: string) { // Create a selection of the hole block and replace it with new text const content = this.state.editorState.getCurrentContent() const end = content.getBlockForKey(blockKey).getText().length const selection = SelectionState.createEmpty(blockKey) .set("anchorOffset", 0) .set("focusKey", blockKey) .set("focusOffset", end) const newContent = Modifier.replaceText(content, selection as SelectionState, textContent) // apply changes const newState = EditorState.push( this.state.editorState, newContent, "insert-characters" ) this.onChange(newState) } setSelection(anchorKey: string, offset: number) { offset = offset | 0 const selection = SelectionState.createEmpty(anchorKey) .set("anchorOffset", 0) this.onChange(EditorState.forceSelection(this.state.editorState, selection as SelectionState)) } editorKeyBinding(e: React.KeyboardEvent<{}>) { const keyCode = e.keyCode if (keyCode === EditorKeys.LEFT || keyCode === EditorKeys.RIGHT) this.onArrow(keyCode, e) if (keyCode === EditorKeys.BACKSPACE) { const selectionContext = this.getSelectionContext(); const targetBlock = selectionContext.currentContent.getBlockBefore(selectionContext.selectionState.getFocusKey()); const selectionIsStartOfLine = selectionContext.selectionState.getStartOffset() === 0; if (targetBlock && targetBlock.getType() === "code-block" && selectionIsStartOfLine) { this.sendMessage({ type: EditorMessageType.setSelection, target: targetBlock.getKey(), data: { isBackwards: true, keyCode: e.keyCode } }) return null; } else { return "backspace"; } } return getDefaultKeyBinding(e) } /** * Add a subscriber to custom messages/events of editor. * @param {fn} callback */ addMessageSubscriber(callback: () => void) { this.subscriptors.push(callback) } /** * Send a message to subscribers * @param {EditorMessage} message */ sendMessage(message: EditorMessage) { this.subscriptors.forEach(function (callback) { callback(message) }) } getSelectionContext(): { selectionState: Draft.SelectionState, currentContent: Draft.ContentState, } { var selectionState = this.state.editorState.getSelection() var anchorKey = selectionState.getAnchorKey() var currentContent = this.state.editorState.getCurrentContent() return { selectionState, currentContent } } /** * Handle heyboard arrow navigation * @param {KeyboardArrows|number} dir Arrow keycode * @param {Event} e Event */ onArrow(dir: number, e?: React.KeyboardEvent<{}>) { var selectionContext = this.getSelectionContext() var targetBlock = null const selection = window.getSelection(); switch (dir) { case EditorKeys.UP: targetBlock = selectionContext.currentContent.getBlockBefore(selectionContext.selectionState.getFocusKey()) break case EditorKeys.DOWN: targetBlock = selectionContext.currentContent.getBlockAfter(selectionContext.selectionState.getFocusKey()) break case EditorKeys.RIGHT: const selectionIsEndOfLine = selection && selection.anchorNode && selection.anchorNode.textContent && selection.anchorOffset === selection.anchorNode.textContent.length if (selectionIsEndOfLine) targetBlock = selectionContext.currentContent.getBlockAfter(selectionContext.selectionState.getFocusKey()) break case EditorKeys.LEFT: const selectionIsStartOfLine = selectionContext.selectionState.getStartOffset() === 0 if (selectionIsStartOfLine) targetBlock = selectionContext.currentContent.getBlockBefore(selectionContext.selectionState.getFocusKey()) break default: break } if (!targetBlock) { return } const isBackwards = isBlockBackwards(this.state.editorState, targetBlock.getKey()) this.sendMessage({ type: EditorMessageType.setSelection, target: targetBlock.getKey(), data: { isBackwards: isBackwards, keyCode: e ? e.keyCode : undefined } }) } handleKeyCommand(command: string): "handled" | "not-handled" { const newState = RichUtils.handleKeyCommand(this.state.editorState, command) if (newState) { this.onChange(newState) return "handled" } return "not-handled" } /** * Change the type of block on current selection * @param {string} blockType */ toggleBlockType(blockType: string) { this.onChange( RichUtils.toggleBlockType( this.state.editorState, blockType ) ) } /** * Change the type of inline block on current selection * @param {*} blockType */ toggleInlineStyle(inlineStyle: string) { this.onChange( RichUtils.toggleInlineStyle( this.state.editorState, inlineStyle ) ) } getContentToSave(): string { return convertToMarkdown(this.state.editorState.getCurrentContent()); } loadNewContent(newContent: string): Promise<any> { return convertFromMarkdown(newContent, this.props.shellContext.session).then(contentState => { this.onChange(EditorState.createWithContent(contentState)); }); } render() { return ( <div className='WorkbookEditor-container' ref={div => this.editorContainer = div} onClick={(e) => this.focus(e)}> <Editor ref="editor" placeholder="Author content in markdown and use ``` to insert a new code cell" spellCheck={false} readOnly={this.state.readOnly} blockRenderMap={blockRenderMap} blockRendererFn={(block: Draft.ContentBlock) => this.blockRenderer(block)} blockStyleFn={getBlockStyle} customStyleMap={styleMap} editorState={this.state.editorState} onChange={(s: EditorState) => this.onChange(s)} plugins={this.state.plugins} keyBindingFn={(e: React.KeyboardEvent<{}>) => this.editorKeyBinding(e)} handleKeyCommand={(e: string) => this.handleKeyCommand(e)} onUpArrow={(e: React.KeyboardEvent<{}>) => this.onArrow(EditorKeys.UP, e)} onDownArrow={(e: React.KeyboardEvent<{}>) => this.onArrow(EditorKeys.DOWN, e)} /> </div> ) } logContent() { console.log("______editor content______") this.state.editorState.getCurrentContent().getBlockMap().forEach((e: any) => console.log(`${e.key}(${e.type}): "${e.text}"`)) console.log("______editor selection______") console.log( `${this.state.editorState.getSelection().getAnchorKey()}[${this.state.editorState.getSelection().getAnchorOffset()}]-` + `${this.state.editorState.getSelection().getFocusKey()}[${this.state.editorState.getSelection().getFocusOffset()}]` ) } }
the_stack
declare module EZGUI { var Easing: { Linear: { None: (k: any) => any; }; Quadratic: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Cubic: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Quartic: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Quintic: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Sinusoidal: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Exponential: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Circular: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Elastic: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Back: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; Bounce: { In: (k: any) => number; Out: (k: any) => number; InOut: (k: any) => number; }; }; } declare module EZGUI { var Interpolation: { Linear: (v: any, k: any) => any; Bezier: (v: any, k: any) => number; CatmullRom: (v: any, k: any) => any; Utils: { Linear: (p0: any, p1: any, t: any) => any; Bernstein: (n: any, i: any) => number; Factorial: (n: any) => number; CatmullRom: (p0: any, p1: any, p2: any, p3: any, t: any) => any; }; }; } /** * This is a part of Tween.js converted to TypeScript * * Tween.js - Licensed under the MIT license * https://github.com/sole/tween.js */ declare module EZGUI { class Tween { static _tweens: any[]; static getAll(): any[]; static removeAll(): void; static add(tween: any): void; static remove(tween: any): void; static update(time?: any): boolean; private _object; private _valuesStart; private _valuesEnd; private _valuesStartRepeat; private _duration; private _repeat; private _yoyo; private _isPlaying; private _reversed; private _delayTime; private _startTime; private _easingFunction; private _interpolationFunction; private _chainedTweens; private _onStartCallback; private _onStartCallbackFired; private _onUpdateCallback; private _onCompleteCallback; private _onStopCallback; constructor(object: any); to(properties: any, duration: any): Tween; start(time?: any): Tween; stop(): Tween; stopChainedTweens(): void; delay(amount: any): Tween; repeat(times: any): Tween; yoyo(yoyo: any): Tween; easing(easing: any): Tween; interpolation(interpolation: any): Tween; chain(): Tween; onStart(callback: any): Tween; onUpdate(callback: any): Tween; onComplete(callback: any): Tween; onStop(callback: any): Tween; update(time: any): boolean; } } declare module EZGUI.utils { class EventHandler { private _events; bind(event: any, fct: any): void; on(event: any, fct: any, nbcalls?: any): void; unbind(event: any, fct: any): void; unbindEvent(event: any): void; unbindAll(): void; trigger(event: any, ...args: any[]): void; } } declare module EZGUI.Compatibility { var PIXIVersion: number; var isPhaser: boolean; var isPhaser24: boolean; var BitmapText: any; class TilingSprite { constructor(texture: PIXI.Texture, width: number, height: number); } class GUIContainer extends PIXI.Container { } class GUIDisplayObjectContainer extends GUIContainer { phaserGroup: any; static globalPhaserGroup: any; _listeners: any; constructor(); } function createRenderTexture(width: any, height: any): any; function fixCache(resources: any): void; } declare var Phaser: any; declare module EZGUI { class Theme { themeConfig: any; static imageComponents: string[]; static imageStates: string[]; static imageVariants: string[]; private _theme; private _default; private _listeners; ready: boolean; id: string; private url; private path; constructor(themeConfig: any); override(themeConfig: any): void; private fixLimits(target, source); private initThemeConfig(themeConfig); private parseResources(); private parseComponents(theme); private normalizeResPath(str); static load(themes: any[], cb?: any): void; onReady(cb: any): void; private preload(); private loadResources(resources, cb); private parseFont(resource, texture); getSkin(skinId: any): any; applySkin(settings: any): any; } } declare module EZGUI { var VERSION: string; var tilingRenderer: any; var dragging: any; var dsx: number; var dsy: number; var startDrag: { x: any; y: any; t: any; }; var focused: any; var game: any; var themes: {}; var components: any; var radioGroups: any; var EventsHelper: utils.EventHandler; /** * generic settings object * accepted parameters * crossOrigin : true/false */ var settings: any; function registerComponents(cpt: any, id?: any): void; function create(settings: any, theme: any): any; } declare module EZGUI { class MultistateSprite extends PIXI.Sprite { stateTextures: any; constructor(texture: PIXI.Texture, states?: any); addState(id: any, texture: any): void; setState(state?: string): void; } } declare module EZGUI { class GUIObject extends EZGUI.Compatibility.GUIDisplayObjectContainer { guiID: string; Id: string; userData: any; container: PIXI.Container; guiParent: GUISprite; constructor(); protected setupEvents(): void; originalAddChildAt(child: any, index: any): PIXI.DisplayObject; originalAddChild(child: any): PIXI.DisplayObject; addChild(child: any): PIXI.DisplayObject; removeChild(child: any): PIXI.DisplayObject; mouseInObj(event: any, guiSprite: any): boolean; canTrigger(event: any, guiSprite: any): boolean; on(event: any, fn: any, context?: any): any; off(event: any, fn?: any, context?: any): any; bindChildren(event: any, fn: any): void; bindChildrenOfType(_type: any, event: any, fn: any): void; unbindChildren(event: any, fn?: any): void; unbindChildrenOfType(_type: any, event: any, fn?: any): void; preUpdate(): void; update(): void; postUpdate(): void; destroy(): void; } } declare module EZGUI { class GUISprite extends GUIObject { settings: any; themeId: any; guiID: string; userData: any; draggable: PIXI.Container; draghandle: any; dragConstraint: string; dragXInterval: number[]; dragYInterval: number[]; theme: Theme; protected textObj: any; protected rootSprite: any; text: string; protected _settings: any; constructor(settings: any, themeId: any); erase(): void; rebuild(): void; protected parsePercentageValue(str: any): number; protected parseSettings(): void; protected prepareChildSettings(settings: any): any; setDraggable(val?: boolean): void; protected handleEvents(): void; /** * Main draw function */ protected draw(): void; protected sortChildren(): void; /** * Text draw function * shared by all components */ protected drawText(): void; createChild(childSettings: any, order?: any): any; /** * */ setState(state?: string): void; animatePosTo(x: any, y: any, time?: number, easing?: (k: any) => any, callback?: any): Tween; animateSizeTo(w: any, h: any, time?: number, easing?: (k: any) => any, callback?: any): Tween; /** * */ protected getFrameConfig(config: any, state: any): any; protected getComponentConfig(component: any, part: any, side: any, state: any): any; protected createThemeCorner(settings: any, part: any, side: any, state: any): PIXI.Sprite; protected createThemeSide(settings: any, side: any, state: any): PIXI.Sprite; protected createThemeBorder(settings: any, part: any, side: any, state: any): any; protected createThemeTilableBackground(settings: any, state: any): any; protected createThemeBackground(settings: any, state: any, leftSide: any, rightSide?: any): any; protected createThemeImage(settings: any, state: any, imagefield?: string): PIXI.Sprite; protected createVisuals(settings: any, state: any): any[]; } } declare module EZGUI.Component { class Input extends GUISprite { settings: any; themeId: any; private guiMask; private domInput; focused: boolean; text: string; private setTextWithCaret(val, event?); constructor(settings: any, themeId: any); protected draw(): void; protected drawText(): void; protected setupEvents(): void; protected handleEvents(): void; private getCaretPosition(); private setCaretPosition(pos); } } declare module EZGUI.Component { class Label extends GUISprite { settings: any; themeId: any; constructor(settings: any, themeId: any); protected setupEvents(): void; protected handleEvents(): void; protected drawText(): void; protected draw(): void; } } declare module EZGUI.Component { class Slider extends GUISprite { settings: any; themeId: any; value: number; private slide; private horizontalSlide; constructor(settings: any, themeId: any); protected setupEvents(): void; protected drawText(): void; protected handleEvents(): void; protected draw(): void; } } declare module EZGUI.Component { class Tabs extends GUISprite { settings: any; themeId: any; activeChild: any; private tabsBar; constructor(settings: any, themeId: any); protected handleEvents(): void; protected draw(): void; private setTaskbarChildState(idx, state); createChild(childSettings: any, order?: any): any; activate(idx: any): void; } } declare module EZGUI.Device { /** * Return true if the browser is Chrome or compatible. * * @method isChrome */ var isChrome: any; /** * Return true if the browser is Firefox. * * @method isFirefox */ var isFirefox: any; /** * Return true if the browser is using the Gecko engine. * * This is probably a better way to identify Firefox and other browsers * that use XulRunner. * * @method isGecko */ var isGecko: any; /** * Return true if the browser is Internet Explorer. * * @method isIE */ var isIE: () => boolean; /** * Return true if the browser is running on Kindle. * * @method isKindle */ var isKindle: any; /** * Return true if the browser is running on a mobile device. * * @method isMobile */ var isMobile: any; /** * Return true if we are running on Opera. * * @method isOpera */ var isOpera: any; /** * Return true if the browser is Safari. * * @method isSafari */ var isSafari: any; /** * Return true if the browser is running on a tablet. * * One way to distinguish Android mobiles from tablets is that the * mobiles contain the string "mobile" in their UserAgent string. * If the word "Android" isn't followed by "mobile" then its a * tablet. * * @method isTablet */ var isTablet: any; /** * Return true if the browser is running on a TV! * * @method isTV */ var isTV: any; /** * Return true if the browser is running on a WebKit browser. * * @method isWebKit */ var isWebKit: any; /** * Return true if the browser is running on an Android browser. * * @method isAndroid */ var isAndroid: any; /** * Return true if the browser is running on any iOS device. * * @method isIOS */ var isIOS: any; /** * Return true if the browser is running on an iPad. * * @method isIPad */ var isIPad: any; /** * Return true if the browser is running on an iPhone. * * @method isIPhone */ var isIPhone: any; /** * Return true if the browser is running on an iPod touch. * * @method isIPod */ var isIPod: any; var isMobile: any; /** * Return the complete UserAgent string verbatim. * * @method whoami */ var whoami: () => string; } declare module EZGUI.Component { class Layout extends GUISprite { settings: any; themeId: any; guiMask: any; constructor(settings: any, themeId: any); protected handleEvents(): void; protected draw(): void; createChild(childSettings: any, order?: any): any; addChild(child: any): PIXI.DisplayObject; addChildAt(child: any, index: any): PIXI.DisplayObject; } } declare module EZGUI.Component { class Window extends Layout { settings: any; themeId: any; guiMask: any; private titleBar; constructor(settings: any, themeId: any); protected draw(): void; protected handleEvents(): void; setDraggable(val?: boolean): void; } } declare module EZGUI.Kit { class MainScreen extends EZGUI.Component.Window { settings: any; themeId: any; private buttonsEvents; constructor(settings: any, themeId: any); protected parseSettings(): void; protected handleEvents(): void; } } declare module EZGUI.utils.ColorParser { function parseToPixiColor(str: any): any; function parseToRGB(str: any): any; } declare module EZGUI.Component { class Button extends GUISprite { settings: any; themeId: any; constructor(settings: any, themeId: any); protected handleEvents(): void; } } declare module EZGUI.Component { class Checkbox extends Button { settings: any; themeId: any; protected _checked: boolean; protected _checkmark: any; checked: boolean; text: string; constructor(settings: any, themeId: any); protected handleEvents(): void; protected draw(): void; protected drawText(): void; } } declare module EZGUI.Component { class Radio extends Checkbox { settings: any; themeId: any; group: any; static groups: any; checked: boolean; constructor(settings: any, themeId: any); private clearGroup(); protected handleEvents(): void; protected draw(): void; } } declare module EZGUI.Component { class List extends Layout { settings: any; themeId: any; private decelerationItv; private decelerationSpeed; private tween; private slotSize; private horizontalSlide; constructor(settings: any, themeId: any); protected handleEvents(): void; private decelerateScroll(endPos); addChildAt(child: any, index: any): PIXI.DisplayObject; removeChild(child: any): PIXI.DisplayObject; slideBy(value: any, delay?: any): void; slideTo(value: any, delay?: any): void; } } declare module EZGUI { class MultistateTilingSprite extends EZGUI.Compatibility.TilingSprite { stateTextures: any; private currentState; constructor(texture: PIXI.Texture, width: number, height: number, states?: any); setState(state?: string): void; } } declare module EZGUI.utils { /** * check if the the point defined by x and y outside a visible gui element * */ function isMasked(x: any, y: any, obj: any): any; function getAbsPos(obj: any, from?: any): any; function getClientXY(event: any): { x: any; y: any; }; function getRealPos(event: any): { x: number; y: number; }; function distance(x: any, y: any, x0: any, y0: any): number; function extendJSON(target: any, source: any): void; function loadJSON(url: any, cb: any, crossOrigin?: boolean): void; function loadXML(url: any, cb: any, crossOrigin?: boolean): void; }
the_stack
import { AEventDispatcher, ISequence, similar, fixCSS, IEventListener } from '../internal'; import { isSortingAscByDefault } from './annotations'; import { IColumnDump, ISortCriteria, defaultGroup, ECompareValueType, IColumnDesc, IDataRow, IGroup, IColumnParent, IColumnMetaData, IFlatColumn, ICompareValue, ITypeFactory, } from './interfaces'; import type Ranking from './Ranking'; /** * default color that should be used * @type {string} */ export const DEFAULT_COLOR = '#C1C1C1'; /** * emitted when the width property changes * @asMemberOf Column * @event */ export declare function widthChanged(previous: number, current: number): void; /** * emitted when the label property changes * @asMemberOf Column * @event */ export declare function labelChanged(previous: string, current: string): void; /** * emitted when the meta data property changes * @asMemberOf Column * @event */ export declare function metaDataChanged(previous: IColumnMetaData, current: IColumnMetaData): void; /** * emitted when state of the column is dirty * @asMemberOf Column * @event */ export declare function dirty(): void; /** * emitted when state of the column related to its header is dirty * @asMemberOf Column * @event */ export declare function dirtyHeader(): void; /** * emitted when state of the column related to its values is dirty * @asMemberOf Column * @event */ export declare function dirtyValues(): void; /** * emitted when state of the column related to cached values (hist, compare, ...) is dirty * @asMemberOf Column * @event */ export declare function dirtyCaches(): void; /** * emitted when the renderer type property changes * @asMemberOf Column * @event */ export declare function rendererTypeChanged(previous: string, current: string): void; /** * emitted when the group renderer property changes * @asMemberOf Column * @event */ export declare function groupRendererChanged(previous: string, current: string): void; /** * emitted when the pattern property changes * @asMemberOf Column * @event */ export declare function summaryRendererChanged(previous: string, current: string): void; /** * emitted when the visibility of this column changes * @asMemberOf Column * @event */ export declare function visibilityChanged(previous: boolean, current: boolean): void; /** * a column in LineUp */ export default class Column extends AEventDispatcher { /** * magic variable for showing all columns * @type {number} */ static readonly FLAT_ALL_COLUMNS = -1; static readonly EVENT_WIDTH_CHANGED = 'widthChanged'; static readonly EVENT_LABEL_CHANGED = 'labelChanged'; static readonly EVENT_METADATA_CHANGED = 'metaDataChanged'; static readonly EVENT_DIRTY = 'dirty'; static readonly EVENT_DIRTY_HEADER = 'dirtyHeader'; static readonly EVENT_DIRTY_VALUES = 'dirtyValues'; static readonly EVENT_DIRTY_CACHES = 'dirtyCaches'; static readonly EVENT_RENDERER_TYPE_CHANGED = 'rendererTypeChanged'; static readonly EVENT_GROUP_RENDERER_TYPE_CHANGED = 'groupRendererChanged'; static readonly EVENT_SUMMARY_RENDERER_TYPE_CHANGED = 'summaryRendererChanged'; static readonly EVENT_VISIBILITY_CHANGED = 'visibilityChanged'; /** * the id of this column */ private uid: string; /** * width of the column * @type {number} * @private */ private width = 100; /** * parent column of this column, set when added to a ranking or combined column */ parent: Readonly<IColumnParent> | null = null; private metadata: Readonly<IColumnMetaData>; private renderer: string; private groupRenderer: string; private summaryRenderer: string; private visible: boolean; constructor(id: string, public readonly desc: Readonly<IColumnDesc>) { super(); this.uid = fixCSS(id); this.renderer = this.desc.renderer || this.desc.type; this.groupRenderer = this.desc.groupRenderer || this.desc.type; this.summaryRenderer = this.desc.summaryRenderer || this.desc.type; this.width = this.desc.width != null && this.desc.width > 0 ? this.desc.width : 100; this.visible = this.desc.visible !== false; this.metadata = { label: desc.label || this.id, summary: desc.summary || '', description: desc.description || '', }; } get fixed() { return Boolean(this.desc.fixed); } get frozen() { return Boolean(this.desc.frozen); } get id() { return this.uid; } assignNewId(idGenerator: () => string) { this.uid = fixCSS(idGenerator()); } get label() { return this.metadata.label; } get description() { return this.metadata.description; } /** * returns the fully qualified id i.e. path the parent * @returns {string} */ get fqid() { return this.parent ? `${this.parent.fqid}_${this.id}` : this.id; } get fqpath() { return this.parent ? `${this.parent.fqpath}@${this.parent.indexOf(this)}` : ''; } protected createEventList() { return super .createEventList() .concat([ Column.EVENT_WIDTH_CHANGED, Column.EVENT_LABEL_CHANGED, Column.EVENT_METADATA_CHANGED, Column.EVENT_VISIBILITY_CHANGED, Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, Column.EVENT_RENDERER_TYPE_CHANGED, Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, ]); } on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this; on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this; on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this; on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this; on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { return super.on(type, listener); } getWidth() { return this.width; } hide() { this.setVisible(false); } show() { this.setVisible(true); } isVisible() { return this.visible; } getVisible() { return this.isVisible(); } setVisible(value: boolean) { if (this.visible === value) { return; } this.fire( [Column.EVENT_VISIBILITY_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.visible, (this.visible = value) ); } /** * visitor pattern for flattening the columns * @param {IFlatColumn} r the result array * @param {number} offset left offset * @param {number} _levelsToGo how many levels down * @param {number} _padding padding between columns * @returns {number} the used width by this column */ flatten(r: IFlatColumn[], offset: number, _levelsToGo = 0, _padding = 0): number { const w = this.getWidth(); r.push({ col: this, offset, width: w }); return w; } setWidth(value: number) { if (similar(this.width, value, 0.5)) { return; } this.fire( [Column.EVENT_WIDTH_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.width, (this.width = value) ); } setWidthImpl(value: number) { this.width = value; } setMetaData(value: Readonly<IColumnMetaData>) { if ( value.label === this.label && this.description === value.description && this.metadata.summary === value.summary ) { return; } const bak = this.getMetaData(); //copy to avoid reference this.metadata = { label: value.label, summary: value.summary, description: value.description, }; this.fire( [Column.EVENT_LABEL_CHANGED, Column.EVENT_METADATA_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY], bak, this.getMetaData() ); } getMetaData(): Readonly<IColumnMetaData> { return Object.assign({}, this.metadata); } /** * triggers that the ranking is sorted by this column * @param ascending ascending order? * @param priority sorting priority * @returns {boolean} was successful */ sortByMe(ascending = isSortingAscByDefault(this), priority = 0) { const r = this.findMyRanker(); if (r) { return r.sortBy(this, ascending, priority); } return false; } groupByMe(): boolean { const r = this.findMyRanker(); if (r) { return r.toggleGrouping(this); } return false; } /** * * @return {number} */ isGroupedBy(): number { const r = this.findMyRanker(); if (!r) { return -1; } return r.getGroupCriteria().indexOf(this); } /** * toggles the sorting order of this column in the ranking * @returns {boolean} was successful */ toggleMySorting() { const r = this.findMyRanker(); if (r) { return r.toggleSorting(this); } return false; } private isSortedByMeImpl(selector: (r: Ranking) => ISortCriteria[]): { asc: 'asc' | 'desc' | undefined; priority: number | undefined; } { const ranker = this.findMyRanker(); if (!ranker) { return { asc: undefined, priority: undefined }; } const criterias = selector(ranker); const index = criterias.findIndex((c) => c.col === this); if (index < 0) { return { asc: undefined, priority: undefined }; } return { asc: criterias[index].asc ? 'asc' : 'desc', priority: index, }; } isSortedByMe() { return this.isSortedByMeImpl((r) => r.getSortCriteria()); } groupSortByMe(ascending = isSortingAscByDefault(this), priority = 0) { const r = this.findMyRanker(); if (r) { return r.groupSortBy(this, ascending, priority); } return false; } toggleMyGroupSorting() { const r = this.findMyRanker(); if (r) { return r.toggleGroupSorting(this); } return false; } isGroupSortedByMe() { return this.isSortedByMeImpl((r) => r.getGroupSortCriteria()); } /** * removes the column from the ranking * @returns {boolean} was successful */ removeMe() { if (this.fixed) { return false; } if (this.parent) { return this.parent.remove(this); } return false; } /** * called when the columns added to a ranking */ attach(parent: IColumnParent) { this.parent = parent; } /** * called when the column is removed from the ranking */ detach() { this.parent = null; } /** * inserts the given column after itself * @param col the column to insert * @returns {boolean} was successful */ insertAfterMe(col: Column) { if (this.parent) { return this.parent.insertAfter(col, this) != null; } return false; } /** * finds the underlying ranking column * @returns {Ranking|null} my current ranking */ findMyRanker(): Ranking | null { if (this.parent) { return this.parent.findMyRanker(); } return null; } /** * dumps this column to JSON compatible format * @param toDescRef helper mapping function * @returns {any} dump of this column */ dump(toDescRef: (desc: any) => any): any { const r: IColumnDump = { id: this.id, desc: toDescRef(this.desc), width: this.width, }; if (this.label !== (this.desc.label || this.id)) { r.label = this.label; } if (this.metadata.summary) { r.summary = this.metadata.summary; } if (this.getRenderer() !== this.desc.type) { r.renderer = this.getRenderer(); } if (this.getGroupRenderer() !== this.desc.type) { r.groupRenderer = this.getGroupRenderer(); } if (this.getSummaryRenderer() !== this.desc.type) { r.summaryRenderer = this.getSummaryRenderer(); } return r; } /** * restore the column content from a dump * @param dump column dump * @param _factory helper for creating columns */ restore(dump: IColumnDump, _factory: ITypeFactory) { this.uid = dump.id; this.width = dump.width || this.width; this.metadata = { label: dump.label || this.label, summary: dump.summary || '', description: this.description, }; if (dump.renderer || dump.rendererType) { this.renderer = dump.renderer || dump.rendererType || this.renderer; } if (dump.groupRenderer) { this.groupRenderer = dump.groupRenderer; } if (dump.summaryRenderer) { this.summaryRenderer = dump.summaryRenderer; } } /** * return the label of a given row for the current column * @param row the current row * @return {string} the label of this column at the specified row */ getLabel(row: IDataRow): string { const v = this.getValue(row); return v == null ? '' : String(v); } /** * return the value of a given row for the current column * @param _row the current row * @return the value of this column at the specified row */ getValue(_row: IDataRow): any | null { return ''; //no value } /** * returns the value to be used when exporting * @param format format hint */ getExportValue(row: IDataRow, format: 'text' | 'json'): any { return format === 'text' ? this.getLabel(row) : this.getValue(row); } getColor(_row: IDataRow) { return DEFAULT_COLOR; } toCompareValue(_row: IDataRow, _valueCache?: any): ICompareValue | ICompareValue[] { return 0; } toCompareValueType(): ECompareValueType | ECompareValueType[] { return ECompareValueType.UINT8; } /** * group the given row into a bin/group * @param _row * @return {IGroup} */ group(_row: IDataRow, _valueCache?: any): IGroup { return Object.assign({}, defaultGroup); } toCompareGroupValue( _rows: ISequence<IDataRow>, group: IGroup, _valueCache?: ISequence<any> ): ICompareValue | ICompareValue[] { return group.name.toLowerCase(); } toCompareGroupValueType(): ECompareValueType | ECompareValueType[] { return ECompareValueType.STRING; } /** * flag whether any filter is applied * @return {boolean} */ isFiltered() { return false; } /** * clear the filter * @return {boolean} whether the filtered needed to be reset */ clearFilter() { // hook to clear the filter return false; } /** * predicate whether the current row should be included * @param row * @return {boolean} */ filter(row: IDataRow, _valueCache?: any) { return row != null; } /** * determines the renderer type that should be used to render this column. By default the same type as the column itself * @return {string} */ getRenderer(): string { return this.renderer; } getGroupRenderer(): string { return this.groupRenderer; } getSummaryRenderer(): string { return this.summaryRenderer; } setRenderer(renderer: string) { if (renderer === this.renderer) { // nothing changes return; } this.fire( [Column.EVENT_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.renderer, (this.renderer = renderer) ); } setGroupRenderer(renderer: string) { if (renderer === this.groupRenderer) { // nothing changes return; } this.fire( [Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.groupRenderer, (this.groupRenderer = renderer) ); } setSummaryRenderer(renderer: string) { if (renderer === this.summaryRenderer) { // nothing changes return; } this.fire( [Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY], this.summaryRenderer, (this.summaryRenderer = renderer) ); } /** * marks the header, values, or both as dirty such that the values are reevaluated * @param type specify in more detail what is dirty, by default whole column */ markDirty(type: 'header' | 'values' | 'all' = 'all') { switch (type) { case 'header': return this.fire([Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY]); case 'values': return this.fire([Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY]); default: return this.fire([ Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ]); } } }
the_stack
import { getVoidLogger } from '@backstage/backend-common'; import { BitbucketDiscoveryProcessor } from './BitbucketDiscoveryProcessor'; import { ConfigReader } from '@backstage/config'; import { LocationSpec } from '@backstage/catalog-model'; import { BitbucketRepository20, BitbucketRepositoryParser, PagedResponse, PagedResponse20, } from './bitbucket'; import { results } from './index'; import { RequestHandler, rest } from 'msw'; import { setupServer } from 'msw/node'; const server = setupServer(); function setupStubs(projects: any[]) { function pagedResponse(values: any): PagedResponse<any> { return { values: values, isLastPage: true, } as PagedResponse<any>; } function stubbedProject( project: string, repos: string[], ): RequestHandler<any, any> { return rest.get( `https://bitbucket.mycompany.com/api/rest/1.0/projects/${project}/repos`, (_, res, ctx) => { const response = []; for (const repo of repos) { response.push({ slug: repo, links: { self: [ { href: `https://bitbucket.mycompany.com/projects/${project}/repos/${repo}/browse`, }, ], }, }); } return res(ctx.json(pagedResponse(response))); }, ); } server.use( rest.get( `https://bitbucket.mycompany.com/api/rest/1.0/projects`, (_, res, ctx) => { return res( ctx.json( pagedResponse( projects.map(p => { return { key: p.key }; }), ), ), ); }, ), ); for (const project of projects) { server.use(stubbedProject(project.key, project.repos)); } } function setupBitbucketCloudStubs( workspace: string, repositories: Pick<BitbucketRepository20, 'slug' | 'project'>[], ) { const stubCallerFn = jest.fn(); function pagedResponse(values: any): PagedResponse20<any> { return { values: values, page: 1, } as PagedResponse20<any>; } server.use( rest.get( `https://api.bitbucket.org/2.0/repositories/${workspace}`, (req, res, ctx) => { stubCallerFn(req); return res( ctx.json( pagedResponse( repositories.map(r => ({ ...r, links: { html: { href: `https://bitbucket.org/${workspace}/${r.slug}`, }, }, })), ), ), ); }, ), ); return stubCallerFn; } describe('BitbucketDiscoveryProcessor', () => { beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); afterEach(() => jest.resetAllMocks()); describe('reject unrelated entries', () => { it('rejects unknown types', async () => { const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ integrations: { bitbucket: [{ host: 'bitbucket.mycompany.com', token: 'blob' }], }, }), { logger: getVoidLogger() }, ); const location: LocationSpec = { type: 'not-bitbucket-discovery', target: 'https://bitbucket.mycompany.com', }; await expect( processor.readLocation(location, false, () => {}), ).resolves.toBeFalsy(); }); it('rejects unknown targets', async () => { const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ integrations: { bitbucket: [ { host: 'bitbucket.org', token: 'blob' }, { host: 'bitbucket.mycompany.com', token: 'blob' }, ], }, }), { logger: getVoidLogger() }, ); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://not.bitbucket.mycompany.com/foobar', }; await expect( processor.readLocation(location, false, () => {}), ).rejects.toThrow( /There is no Bitbucket integration that matches https:\/\/not.bitbucket.mycompany.com\/foobar/, ); }); }); describe('handles organisation repositories', () => { const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ integrations: { bitbucket: [ { host: 'bitbucket.mycompany.com', token: 'blob', apiBaseUrl: 'https://bitbucket.mycompany.com/api/rest/1.0', }, ], }, }), { logger: getVoidLogger() }, ); it('output all repositories', async () => { setupStubs([ { key: 'backstage', repos: ['backstage'] }, { key: 'demo', repos: ['demo'] }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.mycompany.com/projects/*/repos/*/catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/backstage/browse/catalog.yaml', }, optional: true, }); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.mycompany.com/projects/demo/repos/demo/browse/catalog.yaml', }, optional: true, }); }); it('output repositories with wildcards', async () => { setupStubs([ { key: 'backstage', repos: ['backstage', 'techdocs-cli'] }, { key: 'demo', repos: ['demo'] }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/techdocs-*/catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/techdocs-cli/browse/catalog.yaml', }, optional: true, }); }); it('filter unrelated repositories', async () => { setupStubs([{ key: 'backstage', repos: ['test', 'abctest', 'testxyz'] }]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/test/catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/test/browse/catalog.yaml', }, optional: true, }); }); it.each` target ${'https://bitbucket.mycompany.com/projects/backstage/repos/*'} ${'https://bitbucket.mycompany.com/projects/backstage/repos/*/'} ${'https://bitbucket.mycompany.com/projects/backstage/repos/techdocs-*/'} `("target '$target' adds default path to catalog", async ({ target }) => { setupStubs([{ key: 'backstage', repos: ['techdocs-cli'] }]); const location: LocationSpec = { type: 'bitbucket-discovery', target: target, }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/techdocs-cli/browse/catalog-info.yaml', }, optional: true, }); }); }); describe('handles cloud repositories', () => { const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ integrations: { bitbucket: [ { host: 'bitbucket.org', username: 'myuser', appPassword: 'blob', }, ], }, }), { logger: getVoidLogger() }, ); it('output all repositories by default', async () => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, { project: { key: 'prj-two' }, slug: 'repository-two' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(2); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/catalog-info.yaml', }, optional: true, }); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-two/src/master/catalog-info.yaml', }, optional: true, }); }); it('uses provided catalog path', async () => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, { project: { key: 'prj-two' }, slug: 'repository-two' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace?catalogPath=my/nested/path/catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(2); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/my/nested/path/catalog.yaml', }, optional: true, }); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-two/src/master/my/nested/path/catalog.yaml', }, optional: true, }); }); it('output all repositories', async () => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, { project: { key: 'prj-two' }, slug: 'repository-two' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace/projects/*/repos/*?catalogPath=catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(2); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/catalog.yaml', }, optional: true, }); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-two/src/master/catalog.yaml', }, optional: true, }); }); it('output repositories with wildcards', async () => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, { project: { key: 'prj-two' }, slug: 'repository-two' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace/projects/prj-one/repos/*?catalogPath=catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/catalog.yaml', }, optional: true, }); }); it('filter unrelated repositories', async () => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, { project: { key: 'prj-one' }, slug: 'repository-two' }, { project: { key: 'prj-one' }, slug: 'repository-three' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace/projects/prj-one/repos/repository-three?catalogPath=catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-three/src/master/catalog.yaml', }, optional: true, }); }); it('submits query', async () => { const mockCall = setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.org/workspaces/myworkspace?q=project.key ~ "prj-one"', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toBeCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/catalog-info.yaml', }, optional: true, }); expect(mockCall).toBeCalledTimes(1); // it should be possible to do this via an `expect.objectContaining` check but seems to fail with some encoding issue. expect(mockCall.mock.calls[0][0].url).toMatchInlineSnapshot( `"https://api.bitbucket.org/2.0/repositories/myworkspace?page=1&pagelen=100&q=project.key+%7E+%22prj-one%22"`, ); }); it.each` target ${'https://bitbucket.org/workspaces/myworkspace/projects/prj-one/repos/*'} ${'https://bitbucket.org/workspaces/myworkspace/projects/prj-one/repos/*/'} ${'https://bitbucket.org/workspaces/myworkspace/projects/prj-one/repos/repository-*/'} `("target '$target' adds default path to catalog", async ({ target }) => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: target, }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'url', target: 'https://bitbucket.org/myworkspace/repository-one/src/master/catalog-info.yaml', }, optional: true, }); }); it.each` target ${'https://bitbucket.org/test'} `("target '$target' is rejected", async ({ target }) => { setupBitbucketCloudStubs('myworkspace', [ { project: { key: 'prj-one' }, slug: 'repository-one' }, ]); const location: LocationSpec = { type: 'bitbucket-discovery', target: target, }; const emitter = jest.fn(); await expect( processor.readLocation(location, false, emitter), ).rejects.toThrow(/Failed to parse /); }); }); describe('Custom repository parser', () => { const customRepositoryParser: BitbucketRepositoryParser = async function* customRepositoryParser({}) { yield results.location( { type: 'custom-location-type', target: 'custom-target', }, true, ); }; const processor = BitbucketDiscoveryProcessor.fromConfig( new ConfigReader({ integrations: { bitbucket: [ { host: 'bitbucket.mycompany.com', token: 'blob', apiBaseUrl: 'https://bitbucket.mycompany.com/api/rest/1.0', }, ], }, }), { parser: customRepositoryParser, logger: getVoidLogger() }, ); it('use custom repository parser', async () => { setupStubs([{ key: 'backstage', repos: ['test'] }]); const location: LocationSpec = { type: 'bitbucket-discovery', target: 'https://bitbucket.mycompany.com/projects/backstage/repos/test/catalog.yaml', }; const emitter = jest.fn(); await processor.readLocation(location, false, emitter); expect(emitter).toHaveBeenCalledTimes(1); expect(emitter).toHaveBeenCalledWith({ type: 'location', location: { type: 'custom-location-type', target: 'custom-target', }, optional: true, }); }); }); });
the_stack
import BN from 'bn.js' import chai from 'chai' import { ether, expectEvent, expectRevert } from '@openzeppelin/test-helpers' import { deployHub, evmMine, setNextBlockTimestamp } from './TestUtils' import chaiAsPromised from 'chai-as-promised' import { constants, defaultEnvironment, getEip712Signature, splitRelayUrlForRegistrar, toNumber } from '@opengsn/common/dist' import { ForwarderInstance, PenalizerInstance, RelayHubInstance, StakeManagerInstance, TestPaymasterEverythingAcceptedInstance, TestRecipientInstance, TestTokenInstance } from '@opengsn/contracts/types/truffle-contracts' import { RelayRequest } from '@opengsn/common/dist/EIP712/RelayRequest' import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil' import { TypedRequestData } from '@opengsn/common/dist/EIP712/TypedRequestData' import { RelayRegistrarInstance } from '@opengsn/contracts' import { cleanValue } from './utils/chaiHelper' const { assert } = chai.use(chaiAsPromised) const StakeManager = artifacts.require('StakeManager') const Forwarder = artifacts.require('Forwarder') const Penalizer = artifacts.require('Penalizer') const TestPaymasterEverythingAccepted = artifacts.require('TestPaymasterEverythingAccepted') const TestRecipient = artifacts.require('TestRecipient') const TestToken = artifacts.require('TestToken') const RelayRegistrar = artifacts.require('RelayRegistrar') contract('RelayHub Configuration', function ([relayHubDeployer, relayOwner, relayManager, relayWorker, senderAddress, other, dest, incorrectOwner]) { // eslint-disable-line no-unused-vars const message = 'Configuration' const unstakeDelay = 15000 const chainId = defaultEnvironment.chainId const baseRelayFee = new BN('300') const pctRelayFee = new BN('10') const gasPrice = new BN(1e9) const maxFeePerGas = new BN(1e9) const maxPriorityFeePerGas = new BN(1e9) const gasLimit = new BN('1000000') const externalGasLimit = 5e6.toString() const paymasterData = '0x' const apporovalData = '0x' const clientId = '1' const senderNonce = new BN('0') const maxAcceptanceBudget = 10e6 const deprecationTimeInSeconds = 100 const stake = ether('2') let relayHub: RelayHubInstance let relayRegistrar: RelayRegistrarInstance let stakeManager: StakeManagerInstance let penalizer: PenalizerInstance let recipient: TestRecipientInstance let paymaster: TestPaymasterEverythingAcceptedInstance let forwarderInstance: ForwarderInstance let testToken: TestTokenInstance let encodedFunction let signature: string let relayRequest: RelayRequest let forwarder: string let relayHubOwner: string beforeEach(async function prepareForHub () { testToken = await TestToken.new() forwarderInstance = await Forwarder.new() forwarder = forwarderInstance.address recipient = await TestRecipient.new(forwarder) paymaster = await TestPaymasterEverythingAccepted.new() stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS) penalizer = await Penalizer.new( defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, defaultEnvironment.penalizerConfiguration.penalizeBlockExpiration) relayHub = await deployHub(stakeManager.address, penalizer.address, constants.ZERO_ADDRESS, testToken.address, stake.toString()) relayRegistrar = await RelayRegistrar.at(await relayHub.getRelayRegistrar()) await paymaster.setTrustedForwarder(forwarder) await paymaster.setRelayHub(relayHub.address) // Register hub's RelayRequest with forwarder, if not already done. await registerForwarderForGsn(forwarderInstance) await relayHub.depositFor(paymaster.address, { value: ether('1'), from: other }) await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.setRelayManagerOwner(relayOwner, { from: relayManager }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, unstakeDelay, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) await relayHub.addRelayWorkers([relayWorker], { from: relayManager }) await relayRegistrar.registerRelayServer(relayHub.address, 0, pctRelayFee, splitRelayUrlForRegistrar(''), { from: relayManager }) encodedFunction = recipient.contract.methods.emitMessage(message).encodeABI() relayRequest = { request: { to: recipient.address, data: encodedFunction, from: senderAddress, nonce: senderNonce.toString(), value: '0', gas: gasLimit.toString(), validUntilTime: '0' }, relayData: { baseRelayFee: baseRelayFee.toString(), pctRelayFee: pctRelayFee.toString(), transactionCalldataGasUsed: '0', maxFeePerGas: maxFeePerGas.toString(), maxPriorityFeePerGas: maxPriorityFeePerGas.toString(), relayWorker, forwarder, paymaster: paymaster.address, paymasterData, clientId } } const dataToSign = new TypedRequestData( chainId, forwarder, relayRequest ) signature = await getEip712Signature( web3, dataToSign ) relayHubOwner = await relayHub.owner() assert.equal(relayHubDeployer, relayHubOwner) }) describe('#deprecateHub', function () { it('should let owner set hub deprecation block', async function () { const deprecationTime = 0xef.toString() const res = await relayHub.deprecateHub(deprecationTime, { from: relayHubOwner }) expectEvent( res, 'HubDeprecated', { deprecationTime }) const deprecationTimeFromHub = (await relayHub.getDeprecationTime()).toString() assert.equal(deprecationTime, deprecationTimeFromHub) }) it('should not let non owners set hub deprecation block', async function () { await expectRevert( relayHub.deprecateHub(1, { from: incorrectOwner }), 'caller is not the owner') }) it('should let owner re-set deprecation only before it\'s due block', async function () { // Setting deprecation time let deprecationTime = toNumber((await web3.eth.getBlock('latest')).timestamp) + deprecationTimeInSeconds let res = await relayHub.deprecateHub(deprecationTime, { from: relayHubOwner }) expectEvent( res, 'HubDeprecated', { deprecationTime: deprecationTime.toString() }) await evmMine() // Resetting deprecation time before it's due deprecationTime = toNumber((await web3.eth.getBlock('latest')).timestamp) + deprecationTimeInSeconds res = await relayHub.deprecateHub(deprecationTime, { from: relayHubOwner }) expectEvent( res, 'HubDeprecated', { deprecationTime: deprecationTime.toString() }) await setNextBlockTimestamp(deprecationTime) // Resetting deprecation time after it's due await expectRevert( relayHub.deprecateHub(deprecationTime, { from: relayHubOwner }), 'Already deprecated') }) }) describe('#isDeprecated', function () { it('should return true only after deprecation time set and passed', async function () { // Before deprecation block set let isDeprecated = await relayHub.isDeprecated() assert.isFalse(isDeprecated) let deprecationTime = (await relayHub.getDeprecationTime()) const maxUint256 = 'f'.repeat(64) assert.equal(deprecationTime.toString(16), maxUint256) // After deprecation time set but not yet passed const newDeprecationTime = toNumber((await web3.eth.getBlock('latest')).timestamp) + deprecationTimeInSeconds await relayHub.deprecateHub(newDeprecationTime) isDeprecated = await relayHub.isDeprecated() assert.isFalse(isDeprecated) deprecationTime = (await relayHub.getDeprecationTime()) assert.equal(deprecationTime.toNumber(), newDeprecationTime) // After deprecation time set and passed await setNextBlockTimestamp(deprecationTime) await evmMine() isDeprecated = await relayHub.isDeprecated() assert.isTrue(isDeprecated) }) }) describe('#relayCall', function () { it('should revert if deprecationBlock set and passed', async function () { const deprecationTime = toNumber((await web3.eth.getBlock('latest')).timestamp) + deprecationTimeInSeconds await relayHub.deprecateHub(deprecationTime) await setNextBlockTimestamp(deprecationTime) await expectRevert( relayHub.relayCall(maxAcceptanceBudget, relayRequest, signature, apporovalData, { from: relayWorker, gasPrice, gas: externalGasLimit }), 'hub deprecated') }) it('should not revert before deprecationBlock set', async function () { const res = await relayHub.relayCall(maxAcceptanceBudget, relayRequest, signature, apporovalData, { from: relayWorker, gasPrice, gas: externalGasLimit }) expectEvent(res, 'TransactionRelayed', { status: '0' }) }) it('should not revert before deprecationBlock passed', async function () { const newDeprecationTime = toNumber((await web3.eth.getBlock('latest')).timestamp) + deprecationTimeInSeconds await relayHub.deprecateHub(newDeprecationTime) const res = await relayHub.relayCall(maxAcceptanceBudget, relayRequest, signature, apporovalData, { from: relayWorker, gasPrice, gas: externalGasLimit }) expectEvent(res, 'TransactionRelayed', { status: '0' }) }) }) describe('RelayHubConfig', function () { describe('#setConfiguration', function () { it('should not let non owner change configuration', async function () { const config = { ...defaultEnvironment.relayHubConfiguration } await expectRevert( relayHub.setConfiguration(config, { from: incorrectOwner }), 'caller is not the owner') }) it('should let owner change configuration', async function () { const config = { gasOverhead: 0xef.toString(), postOverhead: 0xef.toString(), gasReserve: 0xef.toString(), maxWorkerCount: 0xef.toString(), minimumUnstakeDelay: 0xef.toString(), devAddress: '0xeFEfeFEfeFeFEFEFEfefeFeFefEfEfEfeFEFEFEf', devFee: 0x11.toString() } let configFromHub = await relayHub.getConfiguration() // relayHub.getConfiguration() returns an array, so we need to construct an object with its fields to compare to config. expect({ ...configFromHub }).to.not.include(config) const res = await relayHub.setConfiguration(config, { from: relayHubOwner }) expectEvent(res, 'RelayHubConfigured') configFromHub = cleanValue(await relayHub.getConfiguration()) expect(configFromHub).to.deep.include(config) }) it('should not set dev fee to over 100% of charge', async function () { const config = { gasOverhead: 0xef.toString(), postOverhead: 0xef.toString(), gasReserve: 0xef.toString(), maxWorkerCount: 0xef.toString(), minimumStake: 0xef.toString(), minimumUnstakeDelay: 0xef.toString(), devAddress: '0xeFEfeFEfeFeFEFEFEfefeFeFefEfEfEfeFEFEFEf', devFee: '101' } await expectRevert( relayHub.setConfiguration(config, { from: relayHubOwner }), 'dev fee too high') }) }) }) })
the_stack
import { UnitScaleDefinition, toBase, convertUnit, toBest } from '../../src/core/utils/unit-scale'; describe('unit-scale', () => { // SI (International system of units) https://physics.nist.gov/cuu/Units/prefixes.html const siScale: UnitScaleDefinition = { base: '', scale: { n: 0.000000001, µ: 0.000001, m: 0.001, c: 0.01, d: 0.1, ['']: 1, da: 10, h: 100, k: 1000, M: 1000000, G: 1000000000, T: 1000000000000, }, }; const timeScale: UnitScaleDefinition = { // Using 'min' as base for testing downscaling with not power of ten base: 'min', scale: { ns: (1/60)/1000000000, mu: (1/60)/1000000, ms: (1/60)/1000, s: 1/60, min: 1, h: 60, d: 60 * 24, week: 60 * 24 * 7, month: 60 * 24 * 365.25 / 12, year: 60 * 24 * 365.25, }, }; describe('toBase', () => { it('should properly transform the number to its unit scale base', () => { const tests: any[] = [ // -- Positive numbers // Base [1, '', siScale, 1], // Scale bigger than 1 [1, 'da', siScale, 10], [1, 'h', siScale, 100], [1, 'k', siScale, 1000], [1, 'M', siScale, 1000000], [1, 'G', siScale, 1000000000], [1, 'T', siScale, 1000000000000], // Scale between 0 and 1 [1, 'd', siScale, 0.1], [1, 'c', siScale, 0.01], [1, 'm', siScale, 0.001], [1, 'µ', siScale, 0.000001], [1, 'n', siScale, 0.000000001], // -- Negative numbers // Base [-1, '', siScale, -1], // Scale bigger than 1 [-1, 'da', siScale, -10], [-1, 'h', siScale, -100], [-1, 'k', siScale, -1000], [-1, 'M', siScale, -1000000], [-1, 'G', siScale, -1000000000], [-1, 'T', siScale, -1000000000000], // Scale between 0 and 1 [-1, 'd', siScale, -0.1], [-1, 'c', siScale, -0.01], [-1, 'm', siScale, -0.001], [-1, 'µ', siScale, -0.000001], [-1, 'n', siScale, -0.000000001], ]; tests.forEach(([value, unit, scaleDefinition, expectedResult]) => { expect([value, unit, toBase(value, unit, scaleDefinition)]) .toEqual([value, unit, expectedResult]); }); }); it('should properly transform the number to its unit scale base (with a non power of ten based scale)', () => { const tests: any[] = [ // -- Positive numbers // Base [1, 'min', timeScale, 1], // Scale bigger than 1 [1, 'h', timeScale, 60], [1, 'd', timeScale, 1440], [1, 'week', timeScale, 10080], [1, 'month', timeScale, 43830], [1, 'year', timeScale, 525960], // Scale between 0 and 1 [1, 's', timeScale, 0.016666666666666666], [1, 'ms', timeScale, 0.000016666666666666667], [1, 'mu', timeScale, 1.6666666666666667e-8], [1, 'ns', timeScale, 1.6666666666666667e-11], // -- Negative numbers // Base [-1, 'min', timeScale, -1], // Scale bigger than 1 [-1, 'h', timeScale, -60], [-1, 'd', timeScale, -1440], [-1, 'week', timeScale, -10080], [-1, 'month', timeScale, -43830], [-1, 'year', timeScale, -525960], // Scale between 0 and 1 [-1, 's', timeScale, -0.016666666666666666], [-1, 'ms', timeScale, -0.000016666666666666667], [-1, 'mu', timeScale, -1.6666666666666667e-8], [-1, 'ns', timeScale, -1.6666666666666667e-11], ]; tests.forEach(([value, unit, scaleDefinition, expectedResult]) => { expect([value, unit, toBase(value, unit, scaleDefinition)]) .toEqual([value, unit, expectedResult]); }); }); it('should handle values different than 1 and -1', () => { const tests: any[] = [ // SI scale [58.858, '', siScale, 58.858], [2.1, 'da', siScale, 21], [58.858, 'k', siScale, 58858], [-0.53, 'M', siScale, -530000], [12.989, 'G', siScale, 12989000000], [1.879765, 'T', siScale, 1879765000000], [-1.2345, 'T', siScale, -1234500000000], [1.2345, 'c', siScale, 0.012345], [0.1345, 'm', siScale, 0.0001345], [-987.23, 'µ', siScale, -0.00098723], // Time scale [35.5, 'min', timeScale, 35.5], [1.2, 'h', timeScale, 72], [-0.5, 'd', timeScale, -720], [123.89, 'week', timeScale, 1248811.2], [0.012, 'month', timeScale, 525.96], [-99, 'year', timeScale, -52070040], [1.1, 's', timeScale, 0.018333333333333333], [-60, 's', timeScale, -1], [0.505, 'ms', timeScale, 0.000008416666666666667], ]; tests.forEach(([value, unit, scaleDefinition, expectedResult]) => { expect([value, unit, toBase(value, unit, scaleDefinition)]) .toEqual([value, unit, expectedResult]); }); }); it('should handle non-finite numbers value (return same value)', () => { expect(toBase(NaN, 'm', timeScale)).toBe(NaN); expect(toBase(NaN, 'k', siScale)).toBe(NaN); expect(toBase(Infinity, 's', timeScale)).toBe(Infinity); expect(toBase(Infinity, '', siScale)).toBe(Infinity); expect(toBase(-Infinity, 'year', timeScale)).toBe(-Infinity); expect(toBase(-Infinity, 'm', siScale)).toBe(-Infinity); }); it('should handle not found valueUnit (return NaN)', () => { expect(toBase(1, 'momo', timeScale)).toBe(NaN); expect(toBase(123456, 'kasdf', siScale)).toBe(NaN); expect(toBase(-1, 'swerwer', timeScale)).toBe(NaN); expect(toBase(-1, 'swerwer', { base: 's', scale: {} })).toBe(NaN); }); }); describe('convertUnit', () => { it('should properly transform the origin unit to the target unit', () => { const tests: any[] = [ [1, '', 'm', siScale, 1000], [1, 'µ', 'da', siScale, 0.0000001], [-1, 'M', 'k', siScale, -1000], [123, 'G', 'k', siScale, 123000000], [-9, 'T', 'd', siScale, -90000000000000], [0.1, 'd', 'k', siScale, 0.00001], [1, 'k', '', siScale, 1000], [35.5, 'min', 's', timeScale, 2130], [1.2, 'h', 'ms', timeScale, 4320000], [-1, 'd', 'week', timeScale, -0.14285714285714285], [123.89, 'week', 'year', timeScale, 2.374346338124572], [-365.25, 'd', 'year', timeScale, -1], ]; tests.forEach(([value, originUnit, targetUnit, scaleDefinition, expectedResult]) => { expect([value, originUnit, targetUnit, convertUnit(value, originUnit, targetUnit, scaleDefinition)]) .toEqual([value, originUnit, targetUnit, expectedResult]); }); }); it('should handle non-finite numbers value (return same value)', () => { expect(convertUnit(NaN, 'm', 'day', timeScale)).toBe(NaN); expect(convertUnit(NaN, 'k', '', siScale)).toBe(NaN); expect(convertUnit(Infinity, 's', 'm', timeScale)).toBe(Infinity); expect(convertUnit(Infinity, '', 'M', siScale)).toBe(Infinity); expect(convertUnit(-Infinity, 'year', 'month', timeScale)).toBe(-Infinity); expect(convertUnit(-Infinity, 'm', 'm', siScale)).toBe(-Infinity); }); it('should handle not found valueUnit or targetUnit (return NaN) ', () => { expect(convertUnit(1, 'momo', 'm', timeScale)).toBe(NaN); expect(convertUnit(123456, 'kasdf', 'k', siScale)).toBe(NaN); expect(convertUnit(-1, 'h', 'swerwer', timeScale)).toBe(NaN); expect(convertUnit(-1, 's', 'swerwer', { base: 's', scale: {} })).toBe(NaN); }); }); describe('toBest', () => { it('should return the smallest unit with a value above 1', () => { const tests: any[] = [ [1, '', siScale, [1, '']], [999999, '', siScale, [999.999, 'k']], [-1000, '', siScale, [-1, 'k']], [1000000, '', siScale, [1, 'M']], [-1000000000, '', siScale, [-1, 'G']], [1000000000000, '', siScale, [1, 'T']], [1000000000000000, '', siScale, [1000, 'T']], [1000, 'm', siScale, [1, '']], [0.001, '', siScale, [1, 'm']], [0.1, '', siScale, [1, 'd']], [0.01, '', siScale, [1, 'c']], [0.0001, '', siScale, [100, 'µ']], ]; tests.forEach(([value, unit, scaleDefinition, expectedResult, options]) => { expect([value, unit, toBest(value, unit, scaleDefinition, options)]) .toEqual([value, unit, expectedResult]); }); }); it('should match a scale whose number is greater than the specified cutOffNumber in the options', () => { expect(toBest(1000000, '', siScale, { cutOffNumber: 1.2 })).toEqual([1000, 'k']); expect(toBest(1199000, '', siScale, { cutOffNumber: 1.2 })).toEqual([1199, 'k']); expect(toBest(1200000, '', siScale, { cutOffNumber: 1.2 })).toEqual([1.2, 'M']); expect(toBest(-1199000, '', siScale, { cutOffNumber: 1.2 })).toEqual([-1199, 'k']); expect(toBest(-1200000, '', siScale, { cutOffNumber: 1.2 })).toEqual([-1.2, 'M']); }); it('should exclude the scales that are contained in the exclude array in the options', () => { // Without expect(toBest(999, '', siScale, { exclude: [] })).toEqual([9.99, 'h']); // With exclude expect(toBest(999, '', siScale, { exclude: ['da', 'h'] })).toEqual([999, '']); }); }); });
the_stack
import assert from 'assert' import GherkinDocumentWalker, { rejectAllFilters } from '../src/GherkinDocumentWalker' import pretty from '../src/pretty' import parse from './parse' describe('GherkinDocumentWalker', () => { let walker: GherkinDocumentWalker beforeEach(() => { walker = new GherkinDocumentWalker() }) function assertCopy(copy: any, source: any) { assert.deepEqual(copy, source) assert.notEqual(copy, source) } it('returns a deep copy', () => { const gherkinDocument = parse(`@featureTag Feature: hello This feature has a description Background: Base Background This is a described background Given a passed step @scenarioTag Scenario: salut Yes, there is a description here too @ruleTag Rule: roule Can we describe a Rule ? Background: poupidou Scenario: pouet `) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) assertCopy(newGherkinDocument, gherkinDocument) assertCopy(newGherkinDocument.feature, gherkinDocument.feature) assertCopy( newGherkinDocument.feature.children[0].background, gherkinDocument.feature.children[0].background ) assertCopy( newGherkinDocument.feature.children[1].scenario, gherkinDocument.feature.children[1].scenario ) assertCopy( newGherkinDocument.feature.children[2].rule, gherkinDocument.feature.children[2].rule ) assertCopy( newGherkinDocument.feature.children[2].rule.children[1], gherkinDocument.feature.children[2].rule.children[1] ) assertCopy( newGherkinDocument.feature.children[0].background.steps, gherkinDocument.feature.children[0].background.steps ) }) context('filtering objects', () => { it('filters one scenario', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptScenario: (scenario) => scenario.name === 'Earth' }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Scenario: Earth Given is a planet with liquid water ` assert.strictEqual(newSource, expectedNewSource) }) it('keeps scenario with search hit in step', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptStep: (step) => step.text.includes('liquid') }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Scenario: Earth Given is a planet with liquid water ` assert.strictEqual(newSource, expectedNewSource) }) it('does not leave null object as a feature child', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptScenario: (scenario) => scenario.name === 'Earth' }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) assert.deepStrictEqual( newGherkinDocument.feature.children.filter((child) => child === null), [] ) }) it('keeps a hit scenario even when no steps match', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptScenario: (scenario) => scenario.name === 'Saturn' }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun ` assert.strictEqual(newSource, expectedNewSource) }) // TODO before merging https://github.com/cucumber/cucumber/pull/1419 xit('keeps a hit background', () => { const gherkinDocument = parse(`Feature: Solar System Background: Space Given space is real Rule: Galaxy Background: Milky Way Given it contains our system Rule: Black Hole Background: TON 618 Given it exists `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptBackground: (background) => background.name === 'Milky Way', }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Background: Space Given space is real Rule: Galaxy Background: Milky Way Given it contains our system ` assert.strictEqual(newSource, expectedNewSource) }) it('keeps a hit in background step', () => { const gherkinDocument = parse(`Feature: Solar System Background: Space Given space is real Rule: Galaxy Background: Milky Way Given it contains our system Rule: Black Hole Background: TON 618 Given it exists `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptStep: (step) => step.text.includes('space') }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Background: Space Given space is real Rule: Galaxy Background: Milky Way Given it contains our system Rule: Black Hole Background: TON 618 Given it exists ` assert.strictEqual(newSource, expectedNewSource) }) // TODO before merging https://github.com/cucumber/cucumber/pull/1419 xit('keeps scenario in rule', () => { const gherkinDocument = parse(`Feature: Solar System Rule: Galaxy Background: TON 618 Given it's a black hole Scenario: Milky Way Given it contains our system Scenario: Andromeda Given it exists `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptScenario: (scenario) => scenario.name === 'Andromeda' }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Rule: Galaxy Background: TON 618 Given it's a black hole Scenario: Andromeda Given it exists ` assert.strictEqual(newSource, expectedNewSource) }) it('keeps scenario and background in rule', () => { const gherkinDocument = parse(`Feature: Solar System Rule: Galaxy Background: TON 618 Given it's a black hole Scenario: Milky Way Given it contains our system Scenario: Andromeda Given it exists `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptRule: (rule) => rule.name === 'Galaxy' }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Rule: Galaxy Background: TON 618 Given it's a black hole Scenario: Milky Way Given it contains our system Scenario: Andromeda Given it exists ` assert.strictEqual(newSource, expectedNewSource) }) it('only keeps rule and its content', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Milky Way Given it contains our system Rule: Galaxy Scenario: Andromeda Given it exists `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, ...{ acceptRule: () => true }, }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Rule: Galaxy Scenario: Andromeda Given it exists ` assert.strictEqual(newSource, expectedNewSource) }) it('return a feature and keep scenario', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker({ ...rejectAllFilters, acceptFeature: (feature) => feature.name === 'Solar System', }) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) const newSource = pretty(newGherkinDocument, 'gherkin') const expectedNewSource = `Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water ` assert.deepStrictEqual(newSource, expectedNewSource) }) it('returns null when no hit found', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Saturn Given is the sixth planet from the Sun Scenario: Earth Given is a planet with liquid water `) const walker = new GherkinDocumentWalker(rejectAllFilters) const newGherkinDocument = walker.walkGherkinDocument(gherkinDocument) assert.deepEqual(newGherkinDocument, null) }) }) context('handling objects', () => { describe('handleStep', () => { it('is called for each steps', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Earth Given it is a planet `) const stepText: string[] = [] const astWalker = new GherkinDocumentWalker( {}, { handleStep: (step) => stepText.push(step.text), } ) astWalker.walkGherkinDocument(gherkinDocument) assert.deepEqual(stepText, ['it is a planet']) }) }) describe('handleScenario', () => { it('is called for each scenarios', () => { const gherkinDocument = parse(`Feature: Solar System Scenario: Earth Given it is a planet Scenario: Saturn Given it's not a liquid planet `) const scenarioName: string[] = [] const astWalker = new GherkinDocumentWalker( {}, { handleScenario: (scenario) => scenarioName.push(scenario.name), } ) astWalker.walkGherkinDocument(gherkinDocument) assert.deepEqual(scenarioName, ['Earth', 'Saturn']) }) }) describe('handleBackground', () => { it('is called for each backgrounds', () => { const gherkinDocument = parse(`Feature: Solar System Background: Milky Way Scenario: Earth Given it is our galaxy `) const backgroundName: string[] = [] const astWalker = new GherkinDocumentWalker( {}, { handleBackground: (background) => backgroundName.push(background.name), } ) astWalker.walkGherkinDocument(gherkinDocument) assert.deepEqual(backgroundName, ['Milky Way']) }) }) describe('handleRule', () => { it('is called for each rules', () => { const gherkinDocument = parse(`Feature: Solar System Rule: On a planet Scenario: There is life Given there is water Rule: On an exoplanet Scenario: There is extraterrestrial life Given there is a non-humanoid form of life `) const ruleName: string[] = [] const astWalker = new GherkinDocumentWalker( {}, { handleRule: (rule) => ruleName.push(rule.name), } ) astWalker.walkGherkinDocument(gherkinDocument) assert.deepEqual(ruleName, ['On a planet', 'On an exoplanet']) }) }) describe('handleFeature', () => { it('is called for each features', () => { const gherkinDocument = parse(`Feature: Solar System Rule: On a planet Scenario: There is life Given there is water Rule: On an exoplanet Scenario: There is extraterrestrial life Given there is a non-humanoid form of life `) const featureName: string[] = [] const astWalker = new GherkinDocumentWalker( {}, { handleFeature: (feature) => featureName.push(feature.name), } ) astWalker.walkGherkinDocument(gherkinDocument) assert.deepEqual(featureName, ['Solar System']) }) }) }) describe('regression tests', () => { it('does not fail with empty/commented documents', () => { const gherkinDocument = parse('# Feature: Solar System') const astWalker = new GherkinDocumentWalker() astWalker.walkGherkinDocument(gherkinDocument) }) }) })
the_stack
import * as coreClient from "@azure/core-client"; export interface ProductResultValue { value?: Product[]; nextLink?: string; } export interface Product { properties?: ProductProperties; } export interface ProductProperties { id?: number; name?: string; } export interface ProductResult { values?: Product[]; nextLink?: string; } export interface OdataProductResult { values?: Product[]; odataNextLink?: string; } export interface ProductResultValueWithXMSClientName { indexes?: Product[]; nextLink?: string; } export interface OperationResult { /** The status of the request */ status?: OperationResultStatus; } /** Parameter group */ export interface PagingGetMultiplePagesOptions { /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Parameter group */ export interface PagingGetOdataMultiplePagesOptions { /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Parameter group */ export interface PagingGetMultiplePagesWithOffsetOptions { /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Offset of return value */ offset: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Parameter group */ export interface CustomParameterGroup { /** Sets the api version to use. */ apiVersion: string; /** Sets the tenant to use. */ tenant: string; } /** Parameter group */ export interface PagingGetMultiplePagesLroOptions { /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Known values of {@link OperationResultStatus} that the service accepts. */ export enum KnownOperationResultStatus { Succeeded = "Succeeded", Failed = "Failed", Canceled = "canceled", Accepted = "Accepted", Creating = "Creating", Created = "Created", Updating = "Updating", Updated = "Updated", Deleting = "Deleting", Deleted = "Deleted", OK = "OK" } /** * Defines values for OperationResultStatus. \ * {@link KnownOperationResultStatus} can be used interchangeably with OperationResultStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Failed** \ * **canceled** \ * **Accepted** \ * **Creating** \ * **Created** \ * **Updating** \ * **Updated** \ * **Deleting** \ * **Deleted** \ * **OK** */ export type OperationResultStatus = string; /** Optional parameters. */ export interface PagingGetNoItemNamePagesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNoItemNamePages operation. */ export type PagingGetNoItemNamePagesResponse = ProductResultValue; /** Optional parameters. */ export interface PagingGetNullNextLinkNamePagesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNullNextLinkNamePages operation. */ export type PagingGetNullNextLinkNamePagesResponse = ProductResult; /** Optional parameters. */ export interface PagingGetSinglePagesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSinglePages operation. */ export type PagingGetSinglePagesResponse = ProductResult; /** Optional parameters. */ export interface PagingFirstResponseEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the firstResponseEmpty operation. */ export type PagingFirstResponseEmptyResponse = ProductResultValue; /** Optional parameters. */ export interface PagingGetMultiplePagesOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetMultiplePagesOptions?: PagingGetMultiplePagesOptions; clientRequestId?: string; } /** Contains response data for the getMultiplePages operation. */ export type PagingGetMultiplePagesResponse = ProductResult; /** Optional parameters. */ export interface PagingGetWithQueryParamsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getWithQueryParams operation. */ export type PagingGetWithQueryParamsResponse = ProductResult; /** Optional parameters. */ export interface PagingNextOperationWithQueryParamsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the nextOperationWithQueryParams operation. */ export type PagingNextOperationWithQueryParamsResponse = ProductResult; /** Optional parameters. */ export interface PagingGetOdataMultiplePagesOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetOdataMultiplePagesOptions?: PagingGetOdataMultiplePagesOptions; clientRequestId?: string; } /** Contains response data for the getOdataMultiplePages operation. */ export type PagingGetOdataMultiplePagesResponse = OdataProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesWithOffsetOptionalParams extends coreClient.OperationOptions { clientRequestId?: string; /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Contains response data for the getMultiplePagesWithOffset operation. */ export type PagingGetMultiplePagesWithOffsetResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesRetryFirstOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesRetryFirst operation. */ export type PagingGetMultiplePagesRetryFirstResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesRetrySecondOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesRetrySecond operation. */ export type PagingGetMultiplePagesRetrySecondResponse = ProductResult; /** Optional parameters. */ export interface PagingGetSinglePagesFailureOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSinglePagesFailure operation. */ export type PagingGetSinglePagesFailureResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFailureOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFailure operation. */ export type PagingGetMultiplePagesFailureResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFailureUriOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFailureUri operation. */ export type PagingGetMultiplePagesFailureUriResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFragmentNextLinkOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFragmentNextLink operation. */ export type PagingGetMultiplePagesFragmentNextLinkResponse = OdataProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFragmentWithGroupingNextLinkOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFragmentWithGroupingNextLink operation. */ export type PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse = OdataProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesLROOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetMultiplePagesLroOptions?: PagingGetMultiplePagesLroOptions; clientRequestId?: string; /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the getMultiplePagesLRO operation. */ export type PagingGetMultiplePagesLROResponse = ProductResult; /** Optional parameters. */ export interface PagingNextFragmentOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the nextFragment operation. */ export type PagingNextFragmentResponse = OdataProductResult; /** Optional parameters. */ export interface PagingNextFragmentWithGroupingOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the nextFragmentWithGrouping operation. */ export type PagingNextFragmentWithGroupingResponse = OdataProductResult; /** Optional parameters. */ export interface PagingGetPagingModelWithItemNameWithXMSClientNameOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getPagingModelWithItemNameWithXMSClientName operation. */ export type PagingGetPagingModelWithItemNameWithXMSClientNameResponse = ProductResultValueWithXMSClientName; /** Optional parameters. */ export interface PagingGetNoItemNamePagesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNoItemNamePagesNext operation. */ export type PagingGetNoItemNamePagesNextResponse = ProductResultValue; /** Optional parameters. */ export interface PagingGetSinglePagesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSinglePagesNext operation. */ export type PagingGetSinglePagesNextResponse = ProductResult; /** Optional parameters. */ export interface PagingFirstResponseEmptyNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the firstResponseEmptyNext operation. */ export type PagingFirstResponseEmptyNextResponse = ProductResultValue; /** Optional parameters. */ export interface PagingGetMultiplePagesNextOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetMultiplePagesOptions?: PagingGetMultiplePagesOptions; clientRequestId?: string; } /** Contains response data for the getMultiplePagesNext operation. */ export type PagingGetMultiplePagesNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetOdataMultiplePagesNextOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetOdataMultiplePagesOptions?: PagingGetOdataMultiplePagesOptions; clientRequestId?: string; } /** Contains response data for the getOdataMultiplePagesNext operation. */ export type PagingGetOdataMultiplePagesNextResponse = OdataProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesWithOffsetNextOptionalParams extends coreClient.OperationOptions { clientRequestId?: string; /** Sets the maximum number of items to return in the response. */ maxresults?: number; /** Sets the maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. */ timeout?: number; } /** Contains response data for the getMultiplePagesWithOffsetNext operation. */ export type PagingGetMultiplePagesWithOffsetNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesRetryFirstNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesRetryFirstNext operation. */ export type PagingGetMultiplePagesRetryFirstNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesRetrySecondNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesRetrySecondNext operation. */ export type PagingGetMultiplePagesRetrySecondNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetSinglePagesFailureNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSinglePagesFailureNext operation. */ export type PagingGetSinglePagesFailureNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFailureNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFailureNext operation. */ export type PagingGetMultiplePagesFailureNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesFailureUriNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getMultiplePagesFailureUriNext operation. */ export type PagingGetMultiplePagesFailureUriNextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetMultiplePagesLRONextOptionalParams extends coreClient.OperationOptions { /** Parameter group */ pagingGetMultiplePagesLroOptions?: PagingGetMultiplePagesLroOptions; clientRequestId?: string; } /** Contains response data for the getMultiplePagesLRONext operation. */ export type PagingGetMultiplePagesLRONextResponse = ProductResult; /** Optional parameters. */ export interface PagingGetPagingModelWithItemNameWithXMSClientNameNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getPagingModelWithItemNameWithXMSClientNameNext operation. */ export type PagingGetPagingModelWithItemNameWithXMSClientNameNextResponse = ProductResultValueWithXMSClientName; /** Optional parameters. */ export interface PagingClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { combinePaths, getDirectoryPath } from '../common/pathUtils'; import { parseAndGetTestState } from './harness/fourslash/testState'; import { testRenameModule } from './renameModuleTestUtils'; test('rename just file name', () => { const code = ` // @filename: empty.py //// # empty // @filename: pathUtils.py //// def getFilename(path): //// [|/*marker*/pass|] // @filename: test1.py //// import [|pathUtils|] as p //// //// p.getFilename("c") // @filename: test2.py //// import [|pathUtils|] //// //// [|pathUtils|].getFilename("c") // @filename: test3.py //// import [|pathUtils|] as [|pathUtils|], empty //// //// [|pathUtils|].getFilename("c") `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule( state, fileName, `${combinePaths(getDirectoryPath(fileName), 'renamedModule.py')}`, 'pathUtils', 'renamedModule' ); }); test('import - move file to nested folder', () => { const code = ` // @filename: common/__init__.py //// def foo(): //// pass // @filename: module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// import [|{|"r":"common.moduleRenamed as moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common', 'moduleRenamed.py')}`); }); test('import - move file to parent folder', () => { const code = ` // @filename: common/__init__.py //// # empty // @filename: common/module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// import [|common.module|] //// //// [|common.module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule( state, fileName, `${combinePaths(getDirectoryPath(fileName), '..', 'moduleRenamed.py')}`, 'common.module', 'moduleRenamed' ); }); test('import - move file to sibling folder', () => { const code = ` // @filename: common/__init__.py //// # empty // @filename: common/module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: common1/__init__.py //// # empty // @filename: test.py //// import [|common.module|] //// //// [|common.module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule( state, fileName, `${combinePaths(getDirectoryPath(fileName), '..', 'common1', 'moduleRenamed.py')}`, 'common.module', 'common1.moduleRenamed' ); }); test('import alias move up file', () => { const code = ` // @filename: common/__init__.py //// def foo(): //// pass // @filename: module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// import [|{|"r":"common.moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"common.moduleRenamed"|}module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule( state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common', 'moduleRenamed.py')}`, 'module' ); }); test('import alias move down file', () => { const code = ` // @filename: common/__init__.py //// def foo(): //// pass // @filename: common/module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// import [|{|"r":"moduleRenamed"|}common.module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"moduleRenamed"|}common.module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), '..', 'moduleRenamed.py')}`); }); test('import alias rename file', () => { const code = ` // @filename: module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// import [|{|"r":"moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"moduleRenamed"|}module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'moduleRenamed.py')}`, 'module'); }); test('import alias move sibling file', () => { const code = ` // @filename: common1/__init__.py //// def foo(): //// pass // @filename: common2/__init__.py //// def foo(): //// pass // @filename: common1/module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// import [|{|"r":"common2.moduleRenamed"|}common1.module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"common2.moduleRenamed"|}common1.module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule( state, fileName, `${combinePaths(getDirectoryPath(fileName), '..', 'common2', 'moduleRenamed.py')}` ); }); test('re-export import alias through __all__', () => { const code = ` // @filename: common1/__init__.py //// import [|{|"r":"common2.moduleRenamed as moduleRenamed"|}module|] //// __all__ = ["[|{|"r":"moduleRenamed"|}module|]"] // @filename: common2/__init__.py //// def foo(): //// pass // @filename: module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// from common1 import [|{|"r":"moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"common2.moduleRenamed"|}module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common2', 'moduleRenamed.py')}`); }); test('re-export import alias', () => { const code = ` // @filename: common1/__init__.py //// import [|{|"r":"common2.moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] // @filename: common2/__init__.py //// def foo(): //// pass // @filename: module.py //// [|/*marker*/|] //// # empty // @filename: test.py //// from common1 import [|{|"r":"moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] //// //// [|{|"r":"moduleRenamed"|}module|].foo() // @filename: test1.py //// import [|{|"r":"common2.moduleRenamed"|}module|] as m //// //// m.foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common2', 'moduleRenamed.py')}`); }); test('update module symbol exposed through call 1', () => { const code = ` // @filename: lib.py //// import reexport //// //// def foo(): //// return reexport // @filename: reexport.py //// import [|{|"r":"moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] // @filename: module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// from lib import foo //// //// foo().[|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'moduleRenamed.py')}`); }); test('update module symbol exposed through call 2', () => { const code = ` // @filename: lib.py //// import reexport //// //// def foo(): //// return reexport // @filename: reexport.py //// import [|{|"r":"common.moduleRenamed"|}module|] as [|{|"r":"moduleRenamed"|}module|] // @filename: module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// from lib import foo //// //// foo().[|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common', 'moduleRenamed.py')}`); }); test('update module symbol exposed through __all__ 1', () => { const code = ` // @filename: lib.py //// import reexport //// //// def foo(): //// return reexport // @filename: reexport.py //// import [|{|"r":"moduleRenamed"|}module|] //// __all__ = ["[|{|"r":"moduleRenamed"|}module|]"] // @filename: module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// from lib import foo //// //// foo().[|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'moduleRenamed.py')}`); }); test('update module symbol exposed through __all__ 2', () => { const code = ` // @filename: lib.py //// import reexport //// //// def foo(): //// return reexport // @filename: reexport.py //// import [|{|"r":"common.moduleRenamed as moduleRenamed"|}module|] //// __all__ = ["[|{|"r":"moduleRenamed"|}module|]"] // @filename: module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// from lib import foo //// //// foo().[|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), 'common', 'moduleRenamed.py')}`); }); test('update module symbol exposed through __all__ 3', () => { const code = ` // @filename: lib.py //// import reexport //// //// def foo(): //// return reexport // @filename: reexport.py //// import [|{|"r":"moduleRenamed"|}common.module|] as [|{|"r":"moduleRenamed"|}module|] //// __all__ = ["[|{|"r":"moduleRenamed"|}module|]"] // @filename: common/module.py //// [|/*marker*/|] //// def foo(): //// pass // @filename: test.py //// from lib import foo //// //// foo().[|{|"r":"moduleRenamed"|}module|].foo() `; const state = parseAndGetTestState(code).state; const fileName = state.getMarkerByName('marker').fileName; testRenameModule(state, fileName, `${combinePaths(getDirectoryPath(fileName), '..', 'moduleRenamed.py')}`); });
the_stack
import {expect} from 'chai'; import {Stats} from 'fs'; import * as TestOverrides from '../test-related-lib/TestOverrides'; import {CustomRulePathManager} from '../../src/lib/CustomRulePathManager'; import {PmdEngine} from '../../src/lib/pmd/PmdEngine'; import {FileHandler} from '../../src/lib/util/FileHandler'; import path = require('path'); import Sinon = require('sinon'); import { Controller } from '../../src/Controller'; /** * Unit tests to verify CustomRulePathManager * TODO: Add tests to cover exception scenarios when CustomPath.json does not exist */ describe('CustomRulePathManager tests', () => { // File exists, but content has been somehow cleared const emptyFile = ''; // One entry for apex, two for java const populatedFile = '{"pmd": {"apex": ["/some/user/path/customRule.jar"],"java": ["/abc/def/ghi","/home/lib/jars"]}}'; // Most tests rely on the singletons being clean beforeEach(() => TestOverrides.initializeTestSetup()); describe('Rule path entries creation', () => { describe('with pre-populated file', () => { let readStub; beforeEach(() => { readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(populatedFile); }); afterEach(() => { readStub.restore(); }); it('should read CustomPaths.json to get Rule Path Entries', async () => { const manager = await Controller.createRulePathManager(); // Execute test const rulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate run expect(readStub.calledOnce).to.be.true; expect(rulePathMap).to.be.lengthOf(2); //Validate each entry expect(rulePathMap).has.keys('apex', 'java'); const apexPaths = rulePathMap.get('apex'); expect(apexPaths).to.be.lengthOf(1); expect(apexPaths).deep.contains('/some/user/path/customRule.jar'); const javaPaths = rulePathMap.get('java'); expect(javaPaths).to.be.lengthOf(2); expect(javaPaths).deep.contains('/abc/def/ghi'); expect(javaPaths).deep.contains('/home/lib/jars'); }); it('should initialize only once', async () => { const manager = await Controller.createRulePathManager(); // Execute test await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Rerun same end point again. This time, it shouldn't have read file await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate expect(readStub.calledOnce).to.be.true; }); }); it('should handle empty Rule Path file gracefully', async () => { const readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(emptyFile); try { const manager = await Controller.createRulePathManager(); const rulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); expect(readStub.calledOnce).to.be.true; expect(rulePathMap).is.not.null; expect(rulePathMap).to.be.lengthOf(0); } finally { readStub.restore(); } }); }); describe('Adding new Rule path entries', () => { // For all tests, we'll want to stub out the writeFile and mkdir methods with no-ops. before(() => { Sinon.stub(FileHandler.prototype, 'writeFile').resolves(); Sinon.stub(FileHandler.prototype, 'mkdirIfNotExists').resolves(); }); after(() => { Sinon.restore(); }); describe('Test Case: Adding individual files', () => { // For these tests, we'll want to stub out stats so we can simulate a file. let statsStub; before(() => { const mockFileStats = new Stats(); // Force our fake stat to look like a file. mockFileStats.isDirectory = (): boolean => false; mockFileStats.isFile = (): boolean => true; statsStub = Sinon.stub(FileHandler.prototype, 'stats').resolves(mockFileStats); }); after(() => { statsStub.restore(); }); it('Should reflect any new entries', async () => { const readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(emptyFile); try { const manager = await Controller.createRulePathManager(); const language = 'javascript'; const paths = ['/absolute/path/to/SomeJar.jar', '/another/absolute/path/to/AnotherJar.jar']; // Execute test - fetch original state of Map, add entries, check state of updated Map const originalRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); await manager.addPathsForLanguage(language, paths); const updatedRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate expect(originalRulePathMap).to.be.empty; expect(updatedRulePathMap).to.have.keys(language); const pathFromRun = updatedRulePathMap.get(language); expect(pathFromRun.size).to.equal(2, 'Should be four paths added'); expect(pathFromRun).to.contain(paths[0], `Updated path set was missing expected path`); expect(pathFromRun).to.contain(paths[1], `Updated path set was missing expected path`); } finally { readStub.restore(); } }); it('Should append new entries to any existing entries for the language', async () => { // Setup stub const fileContent = '{"pmd": {"apex": ["/some/user/path/customRule.jar"]}}'; const readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(fileContent); try { const manager = await Controller.createRulePathManager(); const language = 'apex'; const newPaths = ['/absolute/path/to/SomeJar.jar', '/different/absolute/path/to/OtherJar.jar']; // Execute test const originalRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Pre-validate to make sure test setup is alright, before proceeding expect(originalRulePathMap).has.keys([language]); const originalPathEntries = originalRulePathMap.get(language); expect(originalPathEntries).to.be.lengthOf(1); // Now add more entries to same language await manager.addPathsForLanguage(language, newPaths); // Fetch updated Map to validate const updatedRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate const updatedPathEntries = updatedRulePathMap.get(language); expect(updatedPathEntries).to.be.lengthOf(3, 'Two new paths should be added, for a total of 3'); expect(updatedPathEntries).to.contain(newPaths[0], `Updated path set was missing expected path`); expect(updatedPathEntries).to.contain(newPaths[1], `Updated path set was missing expected path`); } finally { readStub.restore(); } }); }); describe('Test Case: Adding the contents of a folder', () => { // For these tests, we'll want to stub out stats and readDir so we can simulate a directory containing some JARs. const files = ['test1.jar', 'test2.jar']; let statsStub; before(() => { const mockDirStats = new Stats(); // Force our fake stat to look like a directory. mockDirStats.isDirectory = (): boolean => true; mockDirStats.isFile = (): boolean => false; statsStub = Sinon.stub(FileHandler.prototype, 'stats').resolves(mockDirStats); // Our fake directory is pretending to have two JARs in it. Sinon.stub(FileHandler.prototype, 'readDir').resolves(files); }); after(() => { statsStub.restore(); }); it('Should reflect newly added entries', async () => { const readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(emptyFile); try { const manager = await Controller.createRulePathManager(); const language = 'javascript'; const paths = ['path1', 'path2']; // Execute test - fetch original state of Map, add entries, check state of updated Map const originalRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); await manager.addPathsForLanguage(language, paths); const updatedRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate expect(originalRulePathMap).to.be.empty; expect(updatedRulePathMap).to.have.keys(language); const pathFromRun = updatedRulePathMap.get(language); expect(pathFromRun.size).to.equal(4, 'Should be four paths added'); expect(pathFromRun).to.contain(path.resolve(path.join(paths[0], files[0])), `Updated path set was missing expected path`); expect(pathFromRun).to.contain(path.resolve(path.join(paths[0], files[1])), `Updated path set was missing expected path`); expect(pathFromRun).to.contain(path.resolve(path.join(paths[1], files[0])), `Updated path set was missing expected path`); expect(pathFromRun).to.contain(path.resolve(path.join(paths[1], files[1])), `Updated path set was missing expected path`); } finally { readStub.restore(); } }); it('Should append new entries to any existing entries for language', async () => { // Setup stub const fileContent = '{"pmd": {"apex": ["/some/user/path/customRule.jar"]}}'; const readStub = Sinon.stub(CustomRulePathManager.prototype, 'readRulePathFile').resolves(fileContent); try { const manager = await Controller.createRulePathManager(); const language = 'apex'; const newPath = path.resolve('my', 'new', 'path'); // Execute test const originalRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Pre-validate to make sure test setup is alright, before proceeding expect(originalRulePathMap).has.keys([language]); const originalPathEntries = originalRulePathMap.get(language); expect(originalPathEntries).to.be.lengthOf(1); // Now add more entries to same language await manager.addPathsForLanguage(language, [newPath]); // Fetch updated Map to validate const updatedRulePathMap = await manager.getRulePathEntries(PmdEngine.ENGINE_NAME); // Validate const updatedPathEntries = updatedRulePathMap.get(language); expect(updatedPathEntries).to.be.lengthOf(3, 'Two new paths should be added, for a total of 3'); expect(updatedPathEntries).to.contain(path.join(newPath, files[0]), `Updated path set was missing expected path`); expect(updatedPathEntries).to.contain(path.join(newPath, files[1]), `Updated path set was missing expected path`); } finally { readStub.restore(); } }); }); }); });
the_stack
import { parsing } from "@algo-builder/web"; import algosdk, { ALGORAND_MIN_TX_FEE, decodeAddress, decodeUint64, encodeAddress, encodeUint64, getApplicationAddress, isValidAddress, modelsv2, verifyBytes } from "algosdk"; import { ec as EC } from "elliptic"; import { Message, sha256 } from "js-sha256"; import { sha512_256 } from "js-sha512"; import { Keccak } from 'sha3'; import { RUNTIME_ERRORS } from "../errors/errors-list"; import { RuntimeError } from "../errors/runtime-errors"; import { compareArray } from "../lib/compare"; import { ALGORAND_MAX_LOGS_COUNT, ALGORAND_MAX_LOGS_LENGTH, AssetParamMap, GlobalFields, MathOp, MAX_CONCAT_SIZE, MAX_INNER_TRANSACTIONS, MAX_INPUT_BYTE_LEN, MAX_OUTPUT_BYTE_LEN, MAX_UINT64, MAX_UINT128, MaxTEALVersion, TxArrFields, ZERO_ADDRESS } from "../lib/constants"; import { parseEncodedTxnToExecParams, setInnerTxField } from "../lib/itxn"; import { assertLen, assertOnlyDigits, bigEndianBytesToBigInt, bigintToBigEndianBytes, convertToBuffer, convertToString, getEncoding, parseBinaryStrToBigInt } from "../lib/parsing"; import { Stack } from "../lib/stack"; import { txAppArg, txnSpecbyField } from "../lib/txn"; import { DecodingMode, EncodingType, StackElem, TEALStack, TxnType, TxOnComplete, TxReceipt } from "../types"; import { Interpreter } from "./interpreter"; import { Op } from "./opcode"; // Opcodes reference link: https://developer.algorand.org/docs/reference/teal/opcodes/ // Store TEAL version // push to stack [...stack] export class Pragma extends Op { readonly version: number; readonly line: number; /** * Store Pragma version * @param args Expected arguments: ["version", version number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 2, line); if (this.line > 1) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.PRAGMA_NOT_AT_FIRST_LINE, { line: line }); } if (args[0] === "version" && Number(args[1]) <= MaxTEALVersion) { this.version = Number(args[1]); interpreter.tealVersion = this.version; } else { throw new RuntimeError(RUNTIME_ERRORS.TEAL.PRAGMA_VERSION_ERROR, { expected: 'till #4', got: args.join(' '), line: line }); } } // Returns Pragma version getVersion (): number { return this.version; } execute (stack: TEALStack): void {} } // pops string([]byte) from stack and pushes it's length to stack // push to stack [...stack, bigint] export class Len extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBytes(stack.pop(), this.line); stack.push(BigInt(last.length)); } } // pops two unit64 from stack(last, prev) and pushes their sum(last + prev) to stack // panics on overflow (result > max_unit64) // push to stack [...stack, bigint] export class Add extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); const result = prev + last; this.checkOverflow(result, this.line, MAX_UINT64); stack.push(result); } } // pops two unit64 from stack(last, prev) and pushes their diff(last - prev) to stack // panics on underflow (result < 0) // push to stack [...stack, bigint] export class Sub extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); const result = prev - last; this.checkUnderflow(result, this.line); stack.push(result); } } // pops two unit64 from stack(last, prev) and pushes their division(last / prev) to stack // panics if prev == 0 // push to stack [...stack, bigint] export class Div extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (last === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.ZERO_DIV, { line: this.line }); } stack.push(prev / last); } } // pops two unit64 from stack(last, prev) and pushes their mult(last * prev) to stack // panics on overflow (result > max_unit64) // push to stack [...stack, bigint] export class Mul extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); const result = prev * last; this.checkOverflow(result, this.line, MAX_UINT64); stack.push(result); } } // pushes argument[N] from argument array to stack // push to stack [...stack, bytes] export class Arg extends Op { index: number; readonly interpreter: Interpreter; readonly line: number; /** * Gets the argument value from interpreter.args array. * store the value in _arg variable * @param args Expected arguments: [argument number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 1, line); assertOnlyDigits(args[0], this.line); this.index = Number(args[0]); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.checkIndexBound( this.index, this.interpreter.runtime.ctx.args as Uint8Array[], this.line); const argN = this.assertBytes(this.interpreter.runtime.ctx.args?.[this.index], this.line); stack.push(argN); } } // load block of byte-array constants // push to stack [...stack] export class Bytecblock extends Op { readonly bytecblock: Uint8Array[]; readonly interpreter: Interpreter; readonly line: number; /** * Store blocks of bytes in bytecblock * @param args Expected arguments: [bytecblock] // Ex: ["value1" "value2"] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; const bytecblock: Uint8Array[] = []; for (const val of args) { bytecblock.push(parsing.stringToBytes(val)); } this.interpreter = interpreter; this.bytecblock = bytecblock; } execute (stack: TEALStack): void { this.assertArrLength(this.bytecblock, this.line); this.interpreter.bytecblock = this.bytecblock; } } // push bytes constant from bytecblock to stack by index // push to stack [...stack, bytes] export class Bytec extends Op { readonly index: number; readonly interpreter: Interpreter; readonly line: number; /** * Sets index according to arguments passed * @param args Expected arguments: [byteblock index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 1, line); this.index = Number(args[0]); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.checkIndexBound(this.index, this.interpreter.bytecblock, this.line); const bytec = this.assertBytes(this.interpreter.bytecblock[this.index], this.line); stack.push(bytec); } } // load block of uint64 constants // push to stack [...stack] export class Intcblock extends Op { readonly intcblock: Array<bigint>; readonly interpreter: Interpreter; readonly line: number; /** * Stores block of integer in intcblock * @param args Expected arguments: [integer block] // Ex: [100 200] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; const intcblock: Array<bigint> = []; for (const val of args) { assertOnlyDigits(val, this.line); intcblock.push(BigInt(val)); } this.interpreter = interpreter; this.intcblock = intcblock; } execute (stack: TEALStack): void { this.assertArrLength(this.intcblock, this.line); this.interpreter.intcblock = this.intcblock; } } // push value from uint64 intcblock to stack by index // push to stack [...stack, bigint] export class Intc extends Op { readonly index: number; readonly interpreter: Interpreter; readonly line: number; /** * Sets index according to arguments passed * @param args Expected arguments: [intcblock index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 1, line); this.index = Number(args[0]); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.checkIndexBound(this.index, this.interpreter.intcblock, this.line); const intc = this.assertBigInt(this.interpreter.intcblock[this.index], this.line); stack.push(intc); } } // pops two unit64 from stack(last, prev) and pushes their modulo(last % prev) to stack // Panic if B == 0. // push to stack [...stack, bigint] export class Mod extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (last === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.ZERO_DIV, { line: this.line }); } stack.push(prev % last); } } // pops two unit64 from stack(last, prev) and pushes their bitwise-or(last | prev) to stack // push to stack [...stack, bigint] export class BitwiseOr extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); stack.push(prev | last); } } // pops two unit64 from stack(last, prev) and pushes their bitwise-and(last & prev) to stack // push to stack[...stack, bigint] export class BitwiseAnd extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); stack.push(prev & last); } } // pops two unit64 from stack(last, prev) and pushes their bitwise-xor(last ^ prev) to stack // push to stack [...stack, bigint] export class BitwiseXor extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); stack.push(prev ^ last); } } // pop unit64 from stack and push it's bitwise-invert(~last) to stack // push to stack [...stack, bigint] export class BitwiseNot extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); stack.push(~last); } } // pop last value from the stack and store to scratch space // push to stack [...stack] export class Store extends Op { readonly index: number; readonly interpreter: Interpreter; readonly line: number; /** * Stores index number according to arguments passed * @param args Expected arguments: [index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 1, this.line); assertOnlyDigits(args[0], this.line); this.index = Number(args[0]); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.checkIndexBound(this.index, this.interpreter.scratch, this.line); this.assertMinStackLen(stack, 1, this.line); const top = stack.pop(); this.interpreter.scratch[this.index] = top; } } // copy ith value from scratch space to the stack // push to stack [...stack, bigint/bytes] export class Load extends Op { index: number; readonly interpreter: Interpreter; readonly line: number; /** * Stores index number according to arguments passed. * @param args Expected arguments: [index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 1, this.line); assertOnlyDigits(args[0], this.line); this.index = Number(args[0]); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.checkIndexBound(this.index, this.interpreter.scratch, this.line); stack.push(this.interpreter.scratch[this.index]); } } // err opcode : Error. Panic immediately. // push to stack [...stack] export class Err extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { throw new RuntimeError(RUNTIME_ERRORS.TEAL.TEAL_ENCOUNTERED_ERR, { line: this.line }); } } // SHA256 hash of value X, yields [32]byte // push to stack [...stack, bytes] export class Sha256 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const hash = sha256.create(); const val = this.assertBytes(stack.pop(), this.line) as Message; hash.update(val); const hashedOutput = Buffer.from(hash.hex(), 'hex'); const arrByte = Uint8Array.from(hashedOutput); stack.push(arrByte); } } // SHA512_256 hash of value X, yields [32]byte // push to stack [...stack, bytes] export class Sha512_256 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const hash = sha512_256.create(); const val = this.assertBytes(stack.pop(), this.line) as Message; hash.update(val); const hashedOutput = Buffer.from(hash.hex(), 'hex'); const arrByte = Uint8Array.from(hashedOutput); stack.push(arrByte); } } // Keccak256 hash of value X, yields [32]byte // https://github.com/phusion/node-sha3#example-2 // push to stack [...stack, bytes] export class Keccak256 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBytes(stack.pop(), this.line); const hash = new Keccak(256); hash.update(convertToString(top)); const arrByte = Uint8Array.from(hash.digest()); stack.push(arrByte); } } // for (data A, signature B, pubkey C) verify the signature of // ("ProgData" || program_hash || data) against the pubkey => {0 or 1} // push to stack [...stack, bigint] export class Ed25519verify extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const pubkey = this.assertBytes(stack.pop(), this.line); const signature = this.assertBytes(stack.pop(), this.line); const data = this.assertBytes(stack.pop(), this.line); const addr = encodeAddress(pubkey); const isValid = verifyBytes(data, signature, addr); if (isValid) { stack.push(1n); } else { stack.push(0n); } } } // If A < B pushes '1' else '0' // push to stack [...stack, bigint] export class LessThan extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (prev < last) { stack.push(1n); } else { stack.push(0n); } } } // If A > B pushes '1' else '0' // push to stack [...stack, bigint] export class GreaterThan extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (prev > last) { stack.push(1n); } else { stack.push(0n); } } } // If A <= B pushes '1' else '0' // push to stack [...stack, bigint] export class LessThanEqualTo extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (prev <= last) { stack.push(1n); } else { stack.push(0n); } } } // If A >= B pushes '1' else '0' // push to stack [...stack, bigint] export class GreaterThanEqualTo extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (prev >= last) { stack.push(1n); } else { stack.push(0n); } } } // If A && B is true pushes '1' else '0' // push to stack [...stack, bigint] export class And extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (last && prev) { stack.push(1n); } else { stack.push(0n); } } } // If A || B is true pushes '1' else '0' // push to stack [...stack, bigint] export class Or extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = this.assertBigInt(stack.pop(), this.line); const prev = this.assertBigInt(stack.pop(), this.line); if (prev || last) { stack.push(1n); } else { stack.push(0n); } } } // If A == B pushes '1' else '0' // push to stack [...stack, bigint] export class EqualTo extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = stack.pop(); const prev = stack.pop(); if (typeof last !== typeof prev) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_TYPE, { expected: typeof prev, actual: typeof last, line: this.line }); } if (typeof last === "bigint") { stack = this.pushBooleanCheck(stack, (last === prev)); } else { stack = this.pushBooleanCheck(stack, compareArray(this.assertBytes(last, this.line), this.assertBytes(prev, this.line))); } } } // If A != B pushes '1' else '0' // push to stack [...stack, bigint] export class NotEqualTo extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const last = stack.pop(); const prev = stack.pop(); if (typeof last !== typeof prev) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_TYPE, { expected: typeof prev, actual: typeof last, line: this.line }); } if (typeof last === "bigint") { stack = this.pushBooleanCheck(stack, last !== prev); } else { stack = this.pushBooleanCheck(stack, !compareArray(this.assertBytes(last, this.line), this.assertBytes(prev, this.line))); } } } // X == 0 yields 1; else 0 // push to stack [...stack, bigint] export class Not extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); if (last === 0n) { stack.push(1n); } else { stack.push(0n); } } } // converts uint64 X to big endian bytes // push to stack [...stack, big endian bytes] export class Itob extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const uint64 = this.assertBigInt(stack.pop(), this.line); stack.push(encodeUint64(uint64)); } } // converts bytes X as big endian to uint64 // btoi panics if the input is longer than 8 bytes. // push to stack [...stack, bigint] export class Btoi extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const bytes = this.assertBytes(stack.pop(), this.line); const uint64 = decodeUint64(bytes, DecodingMode.BIGINT); stack.push(uint64); } } // A plus B out to 128-bit long result as sum (top) and carry-bit uint64 values on the stack // push to stack [...stack, bigint] export class Addw extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const valueA = this.assertBigInt(stack.pop(), this.line); const valueB = this.assertBigInt(stack.pop(), this.line); let valueC = valueA + valueB; if (valueC > MAX_UINT64) { valueC -= MAX_UINT64; stack.push(1n); stack.push(valueC - 1n); } else { stack.push(0n); stack.push(valueC); } } } // A times B out to 128-bit long result as low (top) and high uint64 values on the stack // push to stack [...stack, bigint] export class Mulw extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const valueA = this.assertBigInt(stack.pop(), this.line); const valueB = this.assertBigInt(stack.pop(), this.line); const result = valueA * valueB; const low = result & MAX_UINT64; this.checkOverflow(low, this.line, MAX_UINT64); const high = result >> BigInt('64'); this.checkOverflow(high, this.line, MAX_UINT64); stack.push(high); stack.push(low); } } // Pop one element from stack // [...stack] // pop value. export class Pop extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); stack.pop(); } } // duplicate last value on stack // push to stack [...stack, duplicate value] export class Dup extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const lastValue = stack.pop(); stack.push(lastValue); stack.push(lastValue); } } // duplicate two last values on stack: A, B -> A, B, A, B // push to stack [...stack, B, A, B, A] export class Dup2 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const lastValueA = stack.pop(); const lastValueB = stack.pop(); stack.push(lastValueB); stack.push(lastValueA); stack.push(lastValueB); stack.push(lastValueA); } } // pop two byte strings A and B and join them, push the result // concat panics if the result would be greater than 4096 bytes. // push to stack [...stack, string] export class Concat extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const valueA = this.assertBytes(stack.pop(), this.line); const valueB = this.assertBytes(stack.pop(), this.line); if (valueA.length + valueB.length > MAX_CONCAT_SIZE) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.CONCAT_ERROR, { line: this.line }); } const c = new Uint8Array(valueB.length + valueA.length); c.set(valueB); c.set(valueA, valueB.length); stack.push(c); } } // pop last byte string X. For immediate values in 0..255 M and N: // extract last range of bytes from it starting at M up to but not including N, // push the substring result. If N < M, or either is larger than the string length, // the program fails // push to stack [...stack, substring] export class Substring extends Op { readonly start: bigint; readonly end: bigint; readonly line: number; /** * Stores values of `start` and `end` according to arguments passed. * @param args Expected arguments: [start index number, end index number] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 2, line); assertOnlyDigits(args[0], line); assertOnlyDigits(args[1], line); this.start = BigInt(args[0]); this.end = BigInt(args[1]); }; execute (stack: TEALStack): void { const end = this.assertUint8(this.end, this.line); const start = this.assertUint8(this.start, this.line); const byteString = this.assertBytes(stack.pop(), this.line); const subString = this.subString(byteString, start, end, this.line); stack.push(subString); } } // pop a byte-array A and two integers B and C. // Extract a range of bytes from A starting at B up to but not including C, // push the substring result. If C < B, or either is larger than the array length, // the program fails // push to stack [...stack, substring] export class Substring3 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { const end = this.assertBigInt(stack.pop(), this.line); const start = this.assertBigInt(stack.pop(), this.line); const byteString = this.assertBytes(stack.pop(), this.line); const subString = this.subString(byteString, start, end, this.line); stack.push(subString); } } // push field from current transaction to stack // push to stack [...stack, transaction field] export class Txn extends Op { readonly field: string; readonly idx: number | undefined; readonly interpreter: Interpreter; readonly line: number; /** * Set transaction field according to arguments passed * @param args Expected arguments: [transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.idx = undefined; this.assertTxFieldDefined(args[0], interpreter.tealVersion, line); if (TxArrFields[interpreter.tealVersion].has(args[0])) { // eg. txn Accounts 1 assertLen(args.length, 2, line); assertOnlyDigits(args[1], line); this.idx = Number(args[1]); } else { assertLen(args.length, 1, line); } this.assertTxFieldDefined(args[0], interpreter.tealVersion, line); this.field = args[0]; // field this.interpreter = interpreter; } execute (stack: TEALStack): void { let result; if (this.idx !== undefined) { // if field is an array use txAppArg (with "Accounts"/"ApplicationArgs"/'Assets'..) result = txAppArg(this.field, this.interpreter.runtime.ctx.tx, this.idx, this, this.interpreter.tealVersion, this.line); } else { result = txnSpecbyField( this.field, this.interpreter.runtime.ctx.tx, this.interpreter.runtime.ctx.gtxs, this.interpreter.tealVersion); } stack.push(result); } } // push field to the stack from a transaction in the current transaction group // If this transaction is i in the group, gtxn i field is equivalent to txn field. // push to stack [...stack, transaction field] export class Gtxn extends Op { readonly field: string; readonly txFieldIdx: number | undefined; readonly interpreter: Interpreter; readonly line: number; protected txIdx: number; /** * Sets `field`, `txIdx` values according to arguments passed. * @param args Expected arguments: [transaction group index, transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.txFieldIdx = undefined; if (TxArrFields[interpreter.tealVersion].has(args[1])) { assertLen(args.length, 3, line); // eg. gtxn 0 Accounts 1 assertOnlyDigits(args[2], line); this.txFieldIdx = Number(args[2]); } else { assertLen(args.length, 2, line); } assertOnlyDigits(args[0], line); this.assertTxFieldDefined(args[1], interpreter.tealVersion, line); this.txIdx = Number(args[0]); // transaction group index this.field = args[1]; // field this.interpreter = interpreter; } execute (stack: TEALStack): void { this.assertUint8(BigInt(this.txIdx), this.line); this.checkIndexBound(this.txIdx, this.interpreter.runtime.ctx.gtxs, this.line); let result; if (this.txFieldIdx !== undefined) { const tx = this.interpreter.runtime.ctx.gtxs[this.txIdx]; // current tx result = txAppArg(this.field, tx, this.txFieldIdx, this, this.interpreter.tealVersion, this.line); } else { result = txnSpecbyField( this.field, this.interpreter.runtime.ctx.gtxs[this.txIdx], this.interpreter.runtime.ctx.gtxs, this.interpreter.tealVersion); } stack.push(result); } } /** * push value of an array field from current transaction to stack * push to stack [...stack, value of an array field ] * NOTE: a) for arg="Accounts" index 0 means sender's address, and index 1 means first address * from accounts array (eg. txna Accounts 1: will push 1st address from Accounts[] to stack) * b) for arg="ApplicationArgs" index 0 means first argument for application array (normal indexing) */ export class Txna extends Op { readonly field: string; readonly interpreter: Interpreter; readonly line: number; idx: number; /** * Sets `field` and `idx` values according to arguments passed. * @param args Expected arguments: [transaction field, transaction field array index] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 2, line); assertOnlyDigits(args[1], line); this.assertTxArrFieldDefined(args[0], interpreter.tealVersion, line); this.field = args[0]; // field this.idx = Number(args[1]); this.interpreter = interpreter; } execute (stack: TEALStack): void { const result = txAppArg(this.field, this.interpreter.runtime.ctx.tx, this.idx, this, this.interpreter.tealVersion, this.line); stack.push(result); } } /** * push value of a field to the stack from a transaction in the current transaction group * push to stack [...stack, value of field] * NOTE: for arg="Accounts" index 0 means sender's address, and index 1 means first address from accounts * array (eg. gtxna 0 Accounts 1: will push 1st address from Accounts[](from the 1st tx in group) to stack) * b) for arg="ApplicationArgs" index 0 means first argument for application array (normal indexing) */ export class Gtxna extends Op { readonly field: string; readonly interpreter: Interpreter; readonly line: number; idx: number; // array index protected txIdx: number; // transaction group index /** * Sets `field`(Transaction Field), `idx`(Array Index) and * `txIdx`(Transaction Group Index) values according to arguments passed. * @param args Expected arguments: * [transaction group index, transaction field, transaction field array index] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 3, line); assertOnlyDigits(args[0], line); assertOnlyDigits(args[2], line); this.assertTxArrFieldDefined(args[1], interpreter.tealVersion, line); this.txIdx = Number(args[0]); // transaction group index this.field = args[1]; // field this.idx = Number(args[2]); // transaction field array index this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertUint8(BigInt(this.txIdx), this.line); this.checkIndexBound(this.txIdx, this.interpreter.runtime.ctx.gtxs, this.line); const tx = this.interpreter.runtime.ctx.gtxs[this.txIdx]; const result = txAppArg(this.field, tx, this.idx, this, this.interpreter.tealVersion, this.line); stack.push(result); } } // represents branch name of a new branch // push to stack [...stack] export class Label extends Op { readonly label: string; readonly line: number; /** * Sets `label` according to arguments passed. * @param args Expected arguments: [label] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); assertLen(args.length, 1, line); this.label = args[0].split(':')[0]; this.line = line; }; execute (stack: TEALStack): void {} } // branch unconditionally to label - Tealv <= 3 // push to stack [...stack] export class Branch extends Op { readonly label: string; readonly interpreter: Interpreter; readonly line: number; /** * Sets `label` according to arguments passed. * @param args Expected arguments: [label of branch] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 1, line); this.label = args[0]; this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.interpreter.jumpForward(this.label, this.line); } } // branch unconditionally to label - TEALv4 // can also jump backward // push to stack [...stack] export class Branchv4 extends Branch { execute (stack: TEALStack): void { this.interpreter.jumpToLabel(this.label, this.line); } } // branch conditionally if top of stack is zero - Teal version <= 3 // push to stack [...stack] export class BranchIfZero extends Op { readonly label: string; readonly interpreter: Interpreter; readonly line: number; /** * Sets `label` according to arguments passed. * @param args Expected arguments: [label of branch] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 1, line); this.label = args[0]; this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); if (last === 0n) { this.interpreter.jumpForward(this.label, this.line); } } } // branch conditionally if top of stack is zero - Tealv4 // can jump forward also // push to stack [...stack] export class BranchIfZerov4 extends BranchIfZero { execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); if (last === 0n) { this.interpreter.jumpToLabel(this.label, this.line); } } } // branch conditionally if top of stack is non zero // push to stack [...stack] export class BranchIfNotZero extends Op { readonly label: string; readonly interpreter: Interpreter; readonly line: number; /** * Sets `label` according to arguments passed. * @param args Expected arguments: [label of branch] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 1, line); this.label = args[0]; this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); if (last !== 0n) { this.interpreter.jumpForward(this.label, this.line); } } } // branch conditionally if top of stack is non zero - Tealv4 // can jump forward as well // push to stack [...stack] export class BranchIfNotZerov4 extends BranchIfNotZero { execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = this.assertBigInt(stack.pop(), this.line); if (last !== 0n) { this.interpreter.jumpToLabel(this.label, this.line); } } } // use last value on stack as success value; end // push to stack [...stack, last] export class Return extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const last = stack.pop(); while (stack.length()) { stack.pop(); } stack.push(last); // use last value as success this.interpreter.instructionIndex = this.interpreter.instructions.length; // end execution } } // push field from current transaction to stack export class Global extends Op { readonly field: string; readonly interpreter: Interpreter; readonly line: number; /** * Stores global field to query as string * @param args Expected arguments: [field] // Ex: ["GroupSize"] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 1, line); this.assertGlobalDefined(args[0], interpreter.tealVersion, line); this.field = args[0]; // global field this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { let result; switch (this.field) { case 'GroupSize': { result = this.interpreter.runtime.ctx.gtxs.length; break; } case 'CurrentApplicationID': { result = this.interpreter.runtime.ctx.tx.apid; this.interpreter.runtime.assertAppDefined( result as number, this.interpreter.getApp(result as number, this.line), this.line); break; } case 'Round': { result = this.interpreter.runtime.getRound(); break; } case 'LatestTimestamp': { result = this.interpreter.runtime.getTimestamp(); break; } case 'CreatorAddress': { const appID = this.interpreter.runtime.ctx.tx.apid; const app = this.interpreter.getApp(appID as number, this.line); result = decodeAddress(app.creator).publicKey; break; } case 'GroupID': { result = Uint8Array.from(this.interpreter.runtime.ctx.tx.grp ?? ZERO_ADDRESS); break; } case 'CurrentApplicationAddress': { const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; result = decodeAddress(getApplicationAddress(appID)).publicKey; break; } default: { result = GlobalFields[this.interpreter.tealVersion][this.field]; } } if (typeof result === 'number') { stack.push(BigInt(result)); } else { stack.push(result); } } } // check if account specified by Txn.Accounts[A] opted in for the application B => {0 or 1} // params: account index, application id (top of the stack on opcode entry). // push to stack [...stack, 1] if opted in // push to stack[...stack, 0] 0 otherwise export class AppOptedIn extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const appRef = this.assertBigInt(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); // index to tx.accounts[] OR an address directly const account = this.interpreter.getAccount(accountRef, this.line); const localState = account.appsLocalState; const appID = this.interpreter.getAppIDByReference(Number(appRef), false, this.line, this); const isOptedIn = localState.get(appID); if (isOptedIn) { stack.push(1n); } else { stack.push(0n); } } } // read from account specified by Txn.Accounts[A] from local state of the current application key B => value // push to stack [...stack, bigint/bytes] If key exist // push to stack [...stack, 0] otherwise export class AppLocalGet extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const key = this.assertBytes(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); const account = this.interpreter.getAccount(accountRef, this.line); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; const val = account.getLocalState(appID, key); if (val) { stack.push(val); } else { stack.push(0n); // The value is zero if the key does not exist. } } } // read from application local state at Txn.Accounts[A] => app B => key C from local state. // push to stack [...stack, value, 1] (Note: value is 0 if key does not exist) export class AppLocalGetEx extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const key = this.assertBytes(stack.pop(), this.line); const appRef = this.assertBigInt(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); const appID = this.interpreter.getAppIDByReference(Number(appRef), false, this.line, this); const account = this.interpreter.getAccount(accountRef, this.line); const val = account.getLocalState(appID, key); if (val) { stack.push(val); stack.push(1n); } else { stack.push(0n); // The value is zero if the key does not exist. stack.push(0n); // did_exist_flag } } } // read key A from global state of a current application => value // push to stack[...stack, 0] if key doesn't exist // otherwise push to stack [...stack, value] export class AppGlobalGet extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const key = this.assertBytes(stack.pop(), this.line); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; const val = this.interpreter.getGlobalState(appID, key, this.line); if (val) { stack.push(val); } else { stack.push(0n); // The value is zero if the key does not exist. } } } // read from application Txn.ForeignApps[A] global state key B pushes to the stack // push to stack [...stack, value, 1] (Note: value is 0 if key does not exist) // A is specified as an account index in the ForeignApps field of the ApplicationCall transaction, // zero index means this app export class AppGlobalGetEx extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const key = this.assertBytes(stack.pop(), this.line); // appRef could be index to foreign apps array, // or since v4 an application id that appears in Txn.ForeignApps const appRef = this.assertBigInt(stack.pop(), this.line); const appID = this.interpreter.getAppIDByReference(Number(appRef), true, this.line, this); const val = this.interpreter.getGlobalState(appID, key, this.line); if (val) { stack.push(val); stack.push(1n); } else { stack.push(0n); // The value is zero if the key does not exist. stack.push(0n); // did_exist_flag } } } // write to account specified by Txn.Accounts[A] to local state of a current application key B with value C // pops from stack [...stack, value, key] // pushes nothing to stack, updates the app user local storage export class AppLocalPut extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const value = stack.pop(); const key = this.assertBytes(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); const account = this.interpreter.getAccount(accountRef, this.line); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; // get updated local state for account const localState = account.setLocalState(appID, key, value, this.line); const acc = this.interpreter.runtime.assertAccountDefined(account.address, this.interpreter.runtime.ctx.state.accounts.get(account.address), this.line); acc.appsLocalState.set(appID, localState); } } // write key A and value B to global state of the current application // push to stack [...stack] export class AppGlobalPut extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const value = stack.pop(); const key = this.assertBytes(stack.pop(), this.line); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; // if undefined use 0 as default this.interpreter.setGlobalState(appID, key, value, this.line); } } // delete from account specified by Txn.Accounts[A] local state key B of the current application // push to stack [...stack] export class AppLocalDel extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const key = this.assertBytes(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; const account = this.interpreter.getAccount(accountRef, this.line); const localState = account.appsLocalState.get(appID); if (localState) { localState["key-value"].delete(key.toString()); // delete from local state let acc = this.interpreter.runtime.ctx.state.accounts.get(account.address); acc = this.interpreter.runtime.assertAccountDefined(account.address, acc, this.line); acc.appsLocalState.set(appID, localState); } } } // delete key A from a global state of the current application // push to stack [...stack] export class AppGlobalDel extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const key = this.assertBytes(stack.pop(), this.line); const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; const app = this.interpreter.getApp(appID, this.line); if (app) { const globalState = app["global-state"]; globalState.delete(key.toString()); } } } // get balance for the requested account specified // by Txn.Accounts[A] in microalgos. A is specified as an account // index in the Accounts field of the ApplicationCall transaction, // zero index means the sender // push to stack [...stack, bigint] export class Balance extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts if arguments length is zero * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter Interpreter Object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.interpreter = interpreter; this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const accountRef: StackElem = stack.pop(); const acc = this.interpreter.getAccount(accountRef, this.line); stack.push(BigInt(acc.balance())); } } // For Account A, Asset B (txn.accounts[A]) pushes to the // push to stack [...stack, value(bigint/bytes), 1] // NOTE: if account has no B holding then value = 0, did_exist = 0, export class GetAssetHolding extends Op { readonly interpreter: Interpreter; readonly field: string; readonly line: number; /** * Sets field according to arguments passed. * @param args Expected arguments: [Asset Holding field] * // Note: Asset holding field will be string * For ex: `AssetBalance` is correct `0` is not. * @param line line number in TEAL file * @param interpreter Interpreter Object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.interpreter = interpreter; this.line = line; assertLen(args.length, 1, line); this.field = args[0]; }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const assetRef = this.assertBigInt(stack.pop(), this.line); const accountRef: StackElem = stack.pop(); const account = this.interpreter.getAccount(accountRef, this.line); const assetID = this.interpreter.getAssetIDByReference(Number(assetRef), false, this.line, this); const assetInfo = account.assets.get(assetID); if (assetInfo === undefined) { stack.push(0n); stack.push(0n); return; } let value: StackElem; switch (this.field) { case "AssetBalance": value = BigInt(assetInfo.amount); break; case "AssetFrozen": value = assetInfo["is-frozen"] ? 1n : 0n; break; default: throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_FIELD_TYPE, { line: this.line }); } stack.push(value); stack.push(1n); } } // get Asset Params Info for given account // For Index in ForeignAssets array // push to stack [...stack, value(bigint/bytes), did_exist] // NOTE: if asset doesn't exist, then did_exist = 0, value = 0 export class GetAssetDef extends Op { readonly interpreter: Interpreter; readonly field: string; readonly line: number; /** * Sets transaction field according to arguments passed * @param args Expected arguments: [Asset Params field] * // Note: Asset Params field will be string * For ex: `AssetTotal` is correct `0` is not. * @param line line number in TEAL file * @param interpreter Interpreter Object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.interpreter = interpreter; assertLen(args.length, 1, line); if (AssetParamMap[interpreter.tealVersion][args[0]] === undefined) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.UNKNOWN_ASSET_FIELD, { field: args[0], line: line, tealV: interpreter.tealVersion }); } this.field = args[0]; }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const assetRef = this.assertBigInt(stack.pop(), this.line); const assetID = this.interpreter.getAssetIDByReference(Number(assetRef), true, this.line, this); const AssetDefinition = this.interpreter.getAssetDef(assetID); let def: string; if (AssetDefinition === undefined) { stack.push(0n); stack.push(0n); } else { let value: StackElem; const s = AssetParamMap[this.interpreter.tealVersion][this.field] as keyof modelsv2.AssetParams; switch (this.field) { case "AssetTotal": value = BigInt(AssetDefinition.total); break; case "AssetDecimals": value = BigInt(AssetDefinition.decimals); break; case "AssetDefaultFrozen": value = AssetDefinition.defaultFrozen ? 1n : 0n; break; default: def = AssetDefinition[s] as string; if (isValidAddress(def)) { value = decodeAddress(def).publicKey; } else { value = parsing.stringToBytes(def); } break; } stack.push(value); stack.push(1n); } } } /** Pseudo-Ops **/ // push integer to stack // push to stack [...stack, integer value] export class Int extends Op { readonly uint64: bigint; readonly line: number; /** * Sets uint64 variable according to arguments passed. * @param args Expected arguments: [number] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); let uint64; const intConst = TxOnComplete[args[0] as keyof typeof TxOnComplete] || TxnType[args[0] as keyof typeof TxnType]; // check if string is keyof TxOnComplete or TxnType if (intConst !== undefined) { uint64 = BigInt(intConst); } else { assertOnlyDigits(args[0], line); uint64 = BigInt(args[0]); } this.checkOverflow(uint64, line, MAX_UINT64); this.uint64 = uint64; } execute (stack: TEALStack): void { stack.push(this.uint64); } } // push bytes to stack // push to stack [...stack, converted data] export class Byte extends Op { readonly str: string; readonly encoding: EncodingType; readonly line: number; /** * Sets `str` and `encoding` values according to arguments passed. * @param args Expected arguments: [data string] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; [this.str, this.encoding] = getEncoding(args, line); } execute (stack: TEALStack): void { const buffer = convertToBuffer(this.str, this.encoding); stack.push(new Uint8Array(buffer)); } } // decodes algorand address to bytes and pushes to stack // push to stack [...stack, address] export class Addr extends Op { readonly addr: string; readonly line: number; /** * Sets `addr` value according to arguments passed. * @param args Expected arguments: [Address] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); assertLen(args.length, 1, line); if (!isValidAddress(args[0])) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_ADDR, { addr: args[0], line: line }); } this.addr = args[0]; this.line = line; }; execute (stack: TEALStack): void { const addr = decodeAddress(this.addr); stack.push(addr.publicKey); } } /* TEALv3 Ops */ // immediately fail unless value top is a non-zero number // pops from stack: [...stack, uint64] export class Assert extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); if (top === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.TEAL_ENCOUNTERED_ERR, { line: this.line }); } } } // push immediate UINT to the stack as an integer // push to stack: [...stack, uint64] export class PushInt extends Op { /** * NOTE: in runtime this class is similar to Int, but from tealv3 perspective this is optimized * because pushint args are not added to the intcblock during assembly processes */ readonly uint64: bigint; readonly line: number; /** * Sets uint64 variable according to arguments passed. * @param args Expected arguments: [number] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); assertOnlyDigits(args[0], line); this.checkOverflow(BigInt(args[0]), line, MAX_UINT64); this.uint64 = BigInt(args[0]); } execute (stack: TEALStack): void { stack.push(this.uint64); } } // push bytes to stack // push to stack [...stack, converted data] export class PushBytes extends Op { /** * NOTE: in runtime this class is similar to Byte, but from tealv3 perspective this is optimized * because pushbytes args are not added to the bytecblock during assembly processes */ readonly str: string; readonly encoding: EncodingType; readonly line: number; /** * Sets `str` and `encoding` values according to arguments passed. * @param args Expected arguments: [data string] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); [this.str, this.encoding] = getEncoding(args, line); if (this.encoding !== EncodingType.UTF8) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.UNKOWN_DECODE_TYPE, { val: args[0], line: line }); } } execute (stack: TEALStack): void { const buffer = convertToBuffer(this.str, this.encoding); stack.push(new Uint8Array(buffer)); } } // swaps two last values on stack: A, B -> B, A (A,B = any) // pops from stack: [...stack, A, B] // pushes to stack: [...stack, B, A] export class Swap extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const a = stack.pop(); const b = stack.pop(); stack.push(a); stack.push(b); } } /** * bit indexing begins with low-order bits in integers. * Setting bit 4 to 1 on the integer 0 yields 16 (int 0x0010, or 2^4). * Indexing begins in the first bytes of a byte-string * (as seen in getbyte and substring). Setting bits 0 through 11 to 1 * in a 4 byte-array of 0s yields byte 0xfff00000 * Pops from stack: [ ... stack, {any A}, {uint64 B}, {uint64 C} ] * Pushes to stack: [ ...stack, uint64 ] * pop a target A, index B, and bit C. Set the Bth bit of A to C, and push the result */ export class SetBit extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const bit = this.assertBigInt(stack.pop(), this.line); const index = this.assertBigInt(stack.pop(), this.line); const target = stack.pop(); if (bit > 1n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.SET_BIT_VALUE_ERROR, { line: this.line }); } if (typeof target === "bigint") { this.assert64BitIndex(index, this.line); const binaryStr = target.toString(2); const binaryArr = [...(binaryStr.padStart(64, "0"))]; const size = binaryArr.length; binaryArr[size - Number(index) - 1] = (bit === 0n ? "0" : "1"); stack.push(parseBinaryStrToBigInt(binaryArr)); } else { const byteIndex = Math.floor(Number(index) / 8); this.assertBytesIndex(byteIndex, target, this.line); const targetBit = Number(index) % 8; // 8th bit in a bytes array will be highest order bit in second element // that's why mask is reversed const mask = 1 << (7 - targetBit); if (bit === 1n) { // set bit target[byteIndex] |= mask; } else { // clear bit const mask = ~(1 << ((7 - targetBit))); target[byteIndex] &= mask; } stack.push(target); } } } /** * pop a target A (integer or byte-array), and index B. Push the Bth bit of A. * Pops from stack: [ ... stack, {any A}, {uint64 B}] * Pushes to stack: [ ...stack, uint64] */ export class GetBit extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const index = this.assertBigInt(stack.pop(), this.line); const target = stack.pop(); if (typeof target === "bigint") { this.assert64BitIndex(index, this.line); const binaryStr = target.toString(2); const size = binaryStr.length; stack.push(BigInt(binaryStr[size - Number(index) - 1])); } else { const byteIndex = Math.floor(Number(index) / 8); this.assertBytesIndex(byteIndex, target, this.line); const targetBit = Number(index) % 8; const binary = target[byteIndex].toString(2); const str = binary.padStart(8, "0"); stack.push(BigInt(str[targetBit])); } } } /** * pop a byte-array A, integer B, and * small integer C (between 0..255). Set the Bth byte of A to C, and push the result * Pops from stack: [ ...stack, {[]byte A}, {uint64 B}, {uint64 C}] * Pushes to stack: [ ...stack, []byte] */ export class SetByte extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const smallInteger = this.assertBigInt(stack.pop(), this.line); const index = this.assertBigInt(stack.pop(), this.line); const target = this.assertBytes(stack.pop(), this.line); this.assertUint8(smallInteger, this.line); this.assertBytesIndex(Number(index), target, this.line); target[Number(index)] = Number(smallInteger); stack.push(target); } } /** * pop a byte-array A and integer B. Extract the Bth byte of A and push it as an integer * Pops from stack: [ ...stack, {[]byte A}, {uint64 B} ] * Pushes to stack: [ ...stack, uint64 ] */ export class GetByte extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const index = this.assertBigInt(stack.pop(), this.line); const target = this.assertBytes(stack.pop(), this.line); this.assertBytesIndex(Number(index), target, this.line); stack.push(BigInt(target[Number(index)])); } } // push the Nth value (0 indexed) from the top of the stack. // pops from stack: [...stack] // pushes to stack: [...stack, any (nth slot from top of stack)] // NOTE: dig 0 is same as dup export class Dig extends Op { readonly line: number; readonly depth: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [ depth ] // slot to duplicate * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); assertOnlyDigits(args[0], line); this.assertUint8(BigInt(args[0]), line); this.depth = Number(args[0]); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, this.depth + 1, this.line); const tempStack = new Stack<StackElem>(this.depth + 1); // depth = 2 means 3rd slot from top of stack let target; for (let i = 0; i <= this.depth; ++i) { target = stack.pop(); tempStack.push(target); } while (tempStack.length()) { stack.push(tempStack.pop()); } stack.push(target as StackElem); } } // selects one of two values based on top-of-stack: A, B, C -> (if C != 0 then B else A) // pops from stack: [...stack, {any A}, {any B}, {uint64 C}] // pushes to stack: [...stack, any (A or B)] export class Select extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const toCheck = this.assertBigInt(stack.pop(), this.line); const notZeroSelection = stack.pop(); const isZeroSelection = stack.pop(); if (toCheck !== 0n) { stack.push(notZeroSelection); } else { stack.push(isZeroSelection); } } } /** * push field F of the Ath transaction (A = top of stack) in the current group * pops from stack: [...stack, uint64] * pushes to stack: [...stack, transaction field] * NOTE: "gtxns field" is equivalent to "gtxn _i_ field" (where _i_ is the index * of transaction in group, fetched from stack). * gtxns exists so that i can be calculated, often based on the index of the current transaction. */ export class Gtxns extends Gtxn { /** * Sets `field`, `txIdx` values according to arguments passed. * @param args Expected arguments: [transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // NOTE: 100 is a mock value (max no of txns in group can be 16 atmost). // In gtxns & gtxnsa opcodes, index is fetched from top of stack. super(["100", ...args], line, interpreter); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); this.assertUint8(top, this.line); this.txIdx = Number(top); super.execute(stack); } } /** * push Ith value of the array field F from the Ath (A = top of stack) transaction in the current group * pops from stack: [...stack, uint64] * push to stack [...stack, value of field] */ export class Gtxnsa extends Gtxna { /** * Sets `field`(Transaction Field), `idx`(Array Index) values according to arguments passed. * @param args Expected arguments: [transaction field(F), transaction field array index(I)] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // NOTE: 100 is a mock value (max no of txns in group can be 16 atmost). // In gtxns & gtxnsa opcodes, index is fetched from top of stack. super(["100", ...args], line, interpreter); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); this.assertUint8(top, this.line); this.txIdx = Number(top); super.execute(stack); } } /** * get minimum required balance for the requested account specified by Txn.Accounts[A] in microalgos. * NOTE: A = 0 represents tx.sender account. Required balance is affected by ASA and App usage. When creating * or opting into an app, the minimum balance grows before the app code runs, therefore the increase * is visible there. When deleting or closing out, the minimum balance decreases after the app executes. * pops from stack: [...stack, uint64(account index)] * push to stack [...stack, uint64(min balance in microalgos)] */ export class MinBalance extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts if arguments length is zero * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter Interpreter Object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.interpreter = interpreter; this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const accountRef: StackElem = stack.pop(); const acc = this.interpreter.getAccount(accountRef, this.line); stack.push(BigInt(acc.minBalance)); } } /** TEALv4 Ops **/ // push Ith scratch space index of the Tth transaction in the current group // push to stack [...stack, bigint/bytes] // Pops nothing // Args expected: [{uint8 transaction group index}(T), // {uint8 position in scratch space to load from}(I)] export class Gload extends Op { readonly scratchIndex: number; txIndex: number; readonly interpreter: Interpreter; readonly line: number; /** * Stores scratch space index and transaction index number according to arguments passed. * @param args Expected arguments: [index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 2, this.line); assertOnlyDigits(args[0], this.line); assertOnlyDigits(args[1], this.line); this.txIndex = Number(args[0]); this.scratchIndex = Number(args[1]); this.interpreter = interpreter; } execute (stack: TEALStack): void { const scratch = this.interpreter.runtime.ctx.sharedScratchSpace.get(this.txIndex); if (scratch === undefined) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.SCRATCH_EXIST_ERROR, { index: this.txIndex, line: this.line } ); } this.checkIndexBound(this.scratchIndex, scratch, this.line); stack.push(scratch[this.scratchIndex]); } } // push Ith scratch space index of the Tth transaction in the current group // push to stack [...stack, bigint/bytes] // Pops uint64(T) // Args expected: [{uint8 position in scratch space to load from}(I)] export class Gloads extends Gload { /** * Stores scratch space index number according to argument passed. * @param args Expected arguments: [index number] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // "11" is mock value, will be updated when poping from stack in execute super(["11", ...args], line, interpreter); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); this.txIndex = Number(this.assertBigInt(stack.pop(), this.line)); super.execute(stack); } } /** * Provide subroutine functionality. When callsub is called, the current location in * the program is saved and immediately jumps to the label passed to the opcode. * Pops: None * Pushes: None * The call stack is separate from the data stack. Only callsub and retsub manipulate it. * Pops: None * Pushes: Pushes current instruction index in call stack */ export class Callsub extends Op { readonly interpreter: Interpreter; readonly label: string; readonly line: number; /** * Sets `label` according to arguments passed. * @param args Expected arguments: [label of branch] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 1, line); this.label = args[0]; this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { // the current location in the program is saved this.interpreter.callStack.push(this.interpreter.instructionIndex); // immediately jumps to the label passed to the opcode. this.interpreter.jumpToLabel(this.label, this.line); } } /** * When the retsub opcode is called, the AVM will resume * execution at the previous saved point. * Pops: None * Pushes: None * The call stack is separate from the data stack. Only callsub and retsub manipulate it. * Pops: index from call stack * Pushes: None */ export class Retsub extends Op { readonly interpreter: Interpreter; readonly line: number; /** * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); assertLen(args.length, 0, line); this.interpreter = interpreter; this.line = line; } execute (stack: TEALStack): void { // get current location from saved point // jump to saved instruction opcode if (this.interpreter.callStack.length() === 0) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.CALL_STACK_EMPTY, { line: this.line }); } this.interpreter.instructionIndex = this.interpreter.callStack.pop(); } } // generic op to execute byteslice arithmetic // `b+`, `b-`, `b*`, `b/`, `b%`, `b<`, `b>`, `b<=`, // `b>=`, `b==`, `b!=`, `b\`, `b&`, `b^`, `b~`, `bzero` export class ByteOp extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack, op: MathOp): void { this.assertMinStackLen(stack, 2, this.line); const byteB = this.assertBytes(stack.pop(), this.line, MAX_INPUT_BYTE_LEN); const byteA = this.assertBytes(stack.pop(), this.line, MAX_INPUT_BYTE_LEN); const bigIntB = bigEndianBytesToBigInt(byteB); const bigIntA = bigEndianBytesToBigInt(byteA); let r: bigint | boolean; switch (op) { case MathOp.Add: { r = bigIntA + bigIntB; break; } case MathOp.Sub: { r = bigIntA - bigIntB; this.checkUnderflow(r, this.line); break; } case MathOp.Mul: { // NOTE: 12n * 0n == 0n, but in bytesclice arithmatic, this is equivalent to // empty bytes (eg. byte "A" * byte "" === byte "") r = bigIntA * bigIntB; break; } case MathOp.Div: { if (bigIntB === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.ZERO_DIV, { line: this.line }); } r = bigIntA / bigIntB; break; } case MathOp.Mod: { if (bigIntB === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.ZERO_DIV, { line: this.line }); } r = bigIntA % bigIntB; break; } case MathOp.LessThan: { r = bigIntA < bigIntB; break; } case MathOp.GreaterThan: { r = bigIntA > bigIntB; break; } case MathOp.LessThanEqualTo: { r = bigIntA <= bigIntB; break; } case MathOp.GreaterThanEqualTo: { r = bigIntA >= bigIntB; break; } case MathOp.EqualTo: { r = bigIntA === bigIntB; break; } case MathOp.NotEqualTo: { r = bigIntA !== bigIntB; break; } case MathOp.BitwiseOr: { r = bigIntA | bigIntB; break; } case MathOp.BitwiseAnd: { r = bigIntA & bigIntB; break; } case MathOp.BitwiseXor: { r = bigIntA ^ bigIntB; break; } default: { throw new Error('Operation not supported'); } } if (typeof r === 'boolean') { stack.push(BigInt(r)); // 0 or 1 } else { const resultAsBytes = r === 0n ? new Uint8Array([]) : bigintToBigEndianBytes(r); if (op === MathOp.BitwiseOr || op === MathOp.BitwiseAnd || op === MathOp.BitwiseXor) { // for bitwise ops, zero's are "left" padded upto length.max(byteB, byteA) // https://developer.algorand.org/docs/reference/teal/specification/#arithmetic-logic-and-cryptographic-operations const maxSize = Math.max(byteA.length, byteB.length); const paddedZeroArr = new Uint8Array(Math.max(0, maxSize - resultAsBytes.length)).fill(0); const mergedArr = new Uint8Array(maxSize); mergedArr.set(paddedZeroArr); mergedArr.set(resultAsBytes, paddedZeroArr.length); stack.push(this.assertBytes(mergedArr, this.line, MAX_OUTPUT_BYTE_LEN)); } else { stack.push(this.assertBytes(resultAsBytes, this.line, MAX_OUTPUT_BYTE_LEN)); } } } } // A plus B, where A and B are byte-arrays interpreted as big-endian unsigned integers // panics on overflow (result > max_uint1024 i.e 128 byte num) // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, []byte] export class ByteAdd extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.Add); } } // A minus B, where A and B are byte-arrays interpreted as big-endian unsigned integers. // Panic on underflow. // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, []byte] export class ByteSub extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.Sub); } } // A times B, where A and B are byte-arrays interpreted as big-endian unsigned integers. // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, []byte] export class ByteMul extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.Mul); } } // A divided by B, where A and B are byte-arrays interpreted as big-endian unsigned integers. // Panic if B is zero. // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, []byte] export class ByteDiv extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.Div); } } // A modulo B, where A and B are byte-arrays interpreted as big-endian unsigned integers. // Panic if B is zero. // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, []byte] export class ByteMod extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.Mod); } } // A is greater than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteGreatorThan extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.GreaterThan); } } // A is less than B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteLessThan extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.LessThan); } } // A is greater than or equal to B, where A and B are byte-arrays interpreted // as big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteGreaterThanEqualTo extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.GreaterThanEqualTo); } } // A is less than or equal to B, where A and B are byte-arrays interpreted as // big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteLessThanEqualTo extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.LessThanEqualTo); } } // A is equals to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteEqualTo extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.EqualTo); } } // A is not equal to B, where A and B are byte-arrays interpreted as big-endian unsigned integers => { 0 or 1} // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteNotEqualTo extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.NotEqualTo); } } // A bitwise-or B, where A and B are byte-arrays, zero-left extended to the greater of their lengths // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteBitwiseOr extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.BitwiseOr); } } // A bitwise-and B, where A and B are byte-arrays, zero-left extended to the greater of their lengths // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteBitwiseAnd extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.BitwiseAnd); } } // A bitwise-xor B, where A and B are byte-arrays, zero-left extended to the greater of their lengths // Pops: ... stack, {[]byte A}, {[]byte B} // push to stack [...stack, uint64] export class ByteBitwiseXor extends ByteOp { execute (stack: TEALStack): void { super.execute(stack, MathOp.BitwiseXor); } } // X (bytes array) with all bits inverted // Pops: ... stack, []byte // push to stack [...stack, byte[]] export class ByteBitwiseInvert extends ByteOp { execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const byteA = this.assertBytes(stack.pop(), this.line, MAX_INPUT_BYTE_LEN); stack.push(byteA.map(b => (255 - b))); } } // push a byte-array of length X, containing all zero bytes // Pops: ... stack, uint64 // push to stack [...stack, byte[]] export class ByteZero extends ByteOp { execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const len = this.assertBigInt(stack.pop(), this.line); const result = new Uint8Array(Number(len)).fill(0); stack.push(this.assertBytes(result, this.line, 4096)); } } /** * Pop four uint64 values. The deepest two are interpreted * as a uint128 dividend (deepest value is high word), * the top two are interpreted as a uint128 divisor. * Four uint64 values are pushed to the stack. * The deepest two are the quotient (deeper value * is the high uint64). The top two are the remainder, low bits on top. * Pops: ... stack, {uint64 A}, {uint64 B}, {uint64 C}, {uint64 D} * Pushes: ... stack, uint64, uint64, uint64, uint64 */ export class DivModw extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { // Go-algorand implementation: https://github.com/algorand/go-algorand/blob/8f743a98827372bfd8928de3e0b70390ff34f407/data/transactions/logic/eval.go#L927 const firstLow = this.assertBigInt(stack.pop(), this.line); const firstHigh = this.assertBigInt(stack.pop(), this.line); let divisor = firstHigh << BigInt('64'); divisor = divisor + firstLow; const secondLow = this.assertBigInt(stack.pop(), this.line); const secondHigh = this.assertBigInt(stack.pop(), this.line); let dividend = secondHigh << BigInt('64'); dividend = dividend + secondLow; const quotient = dividend / divisor; let low = quotient & MAX_UINT64; this.checkOverflow(low, this.line, MAX_UINT64); let high = quotient >> BigInt('64'); this.checkOverflow(high, this.line, MAX_UINT64); stack.push(high); stack.push(low); const remainder = dividend % divisor; low = remainder & MAX_UINT64; this.checkOverflow(low, this.line, MAX_UINT64); high = remainder >> BigInt('64'); this.checkOverflow(high, this.line, MAX_UINT64); stack.push(high); stack.push(low); } } // A raised to the Bth power. Panic if A == B == 0 and on overflow // Pops: ... stack, {uint64 A}, {uint64 B} // Pushes: uint64 export class Exp extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { const b = this.assertBigInt(stack.pop(), this.line); const a = this.assertBigInt(stack.pop(), this.line); if (a === 0n && b === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.EXP_ERROR, { line: this.line }); } const res = a ** b; this.checkOverflow(res, this.line, MAX_UINT64); stack.push(res); } } // A raised to the Bth power as a 128-bit long result as // low (top) and high uint64 values on the stack. // Panic if A == B == 0 or if the results exceeds 2^128-1 // Pops: ... stack, {uint64 A}, {uint64 B} // Pushes: ... stack, uint64, uint64 export class Expw extends Exp { execute (stack: TEALStack): void { const b = this.assertBigInt(stack.pop(), this.line); const a = this.assertBigInt(stack.pop(), this.line); if (a === 0n && b === 0n) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.EXP_ERROR, { line: this.line }); } const res = a ** b; this.checkOverflow(res, this.line, MAX_UINT128); const low = res & MAX_UINT64; this.checkOverflow(low, this.line, MAX_UINT64); const high = res >> BigInt('64'); this.checkOverflow(high, this.line, MAX_UINT64); stack.push(high); stack.push(low); } } // Left shift (A times 2^B, modulo 2^64) // Pops: ... stack, {uint64 A}, {uint64 B} // Pushes: uint64 export class Shl extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { const b = this.assertBigInt(stack.pop(), this.line); const a = this.assertBigInt(stack.pop(), this.line); const res = (a << b) % (2n ** 64n); stack.push(res); } } // Right shift (A divided by 2^B) // Pops: ... stack, {uint64 A}, {uint64 B} // Pushes: uint64 export class Shr extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { const b = this.assertBigInt(stack.pop(), this.line); const a = this.assertBigInt(stack.pop(), this.line); const res = a >> b; stack.push(res); } } // The largest integer B such that B^2 <= X // Pops: ... stack, uint64 // Pushes: uint64 export class Sqrt extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { // https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root const value = this.assertBigInt(stack.pop(), this.line); if (value < 2n) { stack.push(value); return; } if (value < 16n) { stack.push(BigInt(Math.floor(Math.sqrt(Number(value))))); return; } let x1; if (value < (1n << 52n)) { x1 = BigInt(Math.floor(Math.sqrt(Number(value)))) - 3n; } else { x1 = (1n << 52n) - 2n; } let x0 = -1n; while ((x0 !== x1 && x0 !== (x1 - 1n))) { x0 = x1; x1 = ((value / x0) + x0) >> 1n; } stack.push(x0); } } // Pops: None // Pushes: uint64 // push the ID of the asset or application created in the Tth transaction of the current group // gaid fails unless the requested transaction created an asset or application and T < GroupIndex. export class Gaid extends Op { readonly interpreter: Interpreter; readonly line: number; txIndex: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.interpreter = interpreter; assertLen(args.length, 1, line); this.txIndex = Number(args[0]); }; execute (stack: TEALStack): void { const knowableID = this.interpreter.runtime.ctx.knowableID.get(this.txIndex); if (knowableID === undefined) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.GROUP_INDEX_EXIST_ERROR, { index: this.txIndex, line: this.line } ); } stack.push(BigInt(knowableID)); } } // Pops: ... stack, uint64 // Pushes: uint64 // push the ID of the asset or application created in the Xth transaction of the current group // gaid fails unless the requested transaction created an asset or application and X < GroupIndex. export class Gaids extends Gaid { /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // "11" is mock value, will be updated when poping from stack in execute super(["11", ...args], line, interpreter); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); this.txIndex = Number(this.assertBigInt(stack.pop(), this.line)); super.execute(stack); } } // Pops: ... stack, []byte // Pushes: []byte // pop a byte-array A. Op code parameters: // * S: number in 0..255, start index // * L: number in 0..255, length // extracts a range of bytes from A starting at S up to but not including S+L, // push the substring result. If L is 0, then extract to the end of the string. // If S or S+L is larger than the array length, the program fails export class Extract extends Op { readonly line: number; readonly start: number; length: number; /** * Asserts 2 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 2, line); this.start = Number(args[0]); this.length = Number(args[1]); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const array = this.assertBytes(stack.pop(), this.line); // if length is 0, take bytes from start index to the end if (this.length === 0) { this.length = array.length - this.start; } stack.push(this.opExtractImpl(array, this.start, this.length)); } } // Pops: ... stack, {[]byte A}, {uint64 S}, {uint64 L} // Pushes: []byte // pop a byte-array A and two integers S and L (both in 0..255). // Extract a range of bytes from A starting at S up to but not including S+L, // push the substring result. If S+L is larger than the array length, the program fails export class Extract3 extends Op { readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 3, this.line); const length = this.assertUInt8(stack.pop(), this.line); const start = this.assertUInt8(stack.pop(), this.line); const array = this.assertBytes(stack.pop(), this.line); stack.push(this.opExtractImpl(array, start, length)); } } // Pops: ... stack, {[]byte A}, {uint64 S} // Pushes: uint64 // Op code parameters: // * N: number in {2,4,8}, length // Base class to implement the extract_uint16, extract_uint32 and extract_uint64 op codes // for N equal 2, 4, 8 respectively. // pop a byte-array A and integer S (in 0..255). Extracts a range of bytes // from A starting at S up to but not including B+N, // convert bytes as big endian and push the uint(N*8) result. // If B+N is larger than the array length, the program fails class ExtractUintN extends Op { readonly line: number; extractBytes = 2; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 0, line); // this.extractBytes = 2; }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const start = this.assertUInt8(stack.pop(), this.line); const array = this.assertBytes(stack.pop(), this.line); const sliced = this.opExtractImpl(array, start, this.extractBytes); // extract n bytes stack.push(bigEndianBytesToBigInt(sliced)); } } // Pops: ... stack, {[]byte A}, {uint64 B} // Pushes: uint64 // pop a byte-array A and integer B. Extract a range of bytes // from A starting at B up to but not including B+2, // convert bytes as big endian and push the uint64 result. // If B+2 is larger than the array length, the program fails export class ExtractUint16 extends ExtractUintN { extractBytes = 2; execute (stack: TEALStack): void { super.execute(stack); } } // Pops: ... stack, {[]byte A}, {uint64 B} // Pushes: uint64 // pop a byte-array A and integer B. Extract a range of bytes // from A starting at B up to but not including B+4, convert // bytes as big endian and push the uint64 result. // If B+4 is larger than the array length, the program fails export class ExtractUint32 extends ExtractUintN { extractBytes = 4; execute (stack: TEALStack): void { super.execute(stack); } } // Pops: ... stack, {[]byte A}, {uint64 B} // Pushes: uint64 // pop a byte-array A and integer B. Extract a range of bytes from // A starting at B up to but not including B+8, convert bytes as // big endian and push the uint64 result. If B+8 is larger than // the array length, the program fails export class ExtractUint64 extends ExtractUintN { extractBytes = 8; execute (stack: TEALStack): void { super.execute(stack); } } // Pops: ... stack, {[]byte A}, {[]byte B}, {[]byte C}, {[]byte D}, {[]byte E} // Pushes: uint64 // for (data A, signature B, C and pubkey D, E) verify the signature of the // data against the pubkey => {0 or 1} export class EcdsaVerify extends Op { readonly line: number; readonly curveIndex: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); this.curveIndex = Number(args[0]); }; /** * The 32 byte Y-component of a public key is the last element on the stack, * preceded by X-component of a pubkey, preceded by S and R components of a * signature, preceded by the data that is fifth element on the stack. * All values are big-endian encoded. The signed data must be 32 bytes long, * and signatures in lower-S form are only accepted. */ execute (stack: TEALStack): void { this.assertMinStackLen(stack, 5, this.line); const pubkeyE = this.assertBytes(stack.pop(), this.line); const pubkeyD = this.assertBytes(stack.pop(), this.line); const signatureC = this.assertBytes(stack.pop(), this.line); const signatureB = this.assertBytes(stack.pop(), this.line); const data = this.assertBytes(stack.pop(), this.line); if (this.curveIndex !== 0) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.CURVE_NOT_SUPPORTED, { line: this.line, index: this.curveIndex } ); } const ec = new EC('secp256k1'); const pub = { x: Buffer.from(pubkeyD).toString('hex'), y: Buffer.from(pubkeyE).toString('hex') }; const key = ec.keyFromPublic(pub); const signature = { r: signatureB, s: signatureC }; this.pushBooleanCheck(stack, key.verify(data, signature)); } } // Pops: ... stack, []byte // Pushes: ... stack, []byte, []byte // decompress pubkey A into components X, Y => [... stack, X, Y] export class EcdsaPkDecompress extends Op { readonly line: number; readonly curveIndex: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); this.curveIndex = Number(args[0]); }; /** * The 33 byte public key in a compressed form to be decompressed into X and Y (top) * components. All values are big-endian encoded. */ execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const pubkeyCompressed = this.assertBytes(stack.pop(), this.line); if (this.curveIndex !== 0) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.CURVE_NOT_SUPPORTED, { line: this.line, index: this.curveIndex } ); } const ec = new EC('secp256k1'); const publicKeyUncompressed = ec.keyFromPublic(pubkeyCompressed, 'hex').getPublic(); const x = publicKeyUncompressed.getX(); const y = publicKeyUncompressed.getY(); stack.push(x.toBuffer()); stack.push(y.toBuffer()); } } // Pops: ... stack, {[]byte A}, {uint64 B}, {[]byte C}, {[]byte D} // Pushes: ... stack, []byte, []byte // for (data A, recovery id B, signature C, D) recover a public key => [... stack, X, Y] export class EcdsaPkRecover extends Op { readonly line: number; readonly curveIndex: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [txIndex] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); this.curveIndex = Number(args[0]); }; /** * S (top) and R elements of a signature, recovery id and data (bottom) are * expected on the stack and used to deriver a public key. All values are * big-endian encoded. The signed data must be 32 bytes long. */ execute (stack: TEALStack): void { this.assertMinStackLen(stack, 4, this.line); const signatureD = this.assertBytes(stack.pop(), this.line); const signatureC = this.assertBytes(stack.pop(), this.line); const recoverId = this.assertBigInt(stack.pop(), this.line); const data = this.assertBytes(stack.pop(), this.line); if (this.curveIndex !== 0) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.CURVE_NOT_SUPPORTED, { line: this.line, index: this.curveIndex } ); } const ec = new EC('secp256k1'); const signature = { r: signatureC, s: signatureD }; const pubKey = ec.recoverPubKey(data, signature, Number(recoverId)); const x = pubKey.getX(); const y = pubKey.getY(); stack.push(x.toBuffer()); stack.push(y.toBuffer()); } } // Pops: ...stack, any // Pushes: any // remove top of stack, and place it deeper in the stack such that // N elements are above it. Fails if stack depth <= N. export class Cover extends Op { readonly line: number; readonly nthInStack: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [N] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); this.nthInStack = Number(args[0]); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, this.nthInStack + 1, this.line); const top = stack.pop(); const temp = []; for (let count = 1; count <= this.nthInStack; ++count) { temp.push(stack.pop()); } stack.push(top); for (let i = this.nthInStack - 1; i >= 0; --i) { stack.push(temp[i]); } } } // Pops: ... stack, any // Pushes: any // remove the value at depth N in the stack and shift above items down // so the Nth deep value is on top of the stack. Fails if stack depth <= N. export class Uncover extends Op { readonly line: number; readonly nthInStack: number; /** * Asserts 1 arguments are passed. * @param args Expected arguments: [N] * @param line line number in TEAL file */ constructor (args: string[], line: number) { super(); this.line = line; assertLen(args.length, 1, line); this.nthInStack = Number(args[0]); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, this.nthInStack + 1, this.line); const temp = []; for (let count = 1; count < this.nthInStack; ++count) { temp.push(stack.pop()); } const deepValue = stack.pop(); for (let i = this.nthInStack - 2; i >= 0; --i) { stack.push(temp[i]); } stack.push(deepValue); } } // Pops: ... stack, uint64 // Pushes: any // copy a value from the Xth scratch space to the stack. // All scratch spaces are 0 at program start. export class Loads extends Load { /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // "11" is mock value, will be updated when poping from stack in execute super(["11", ...args], line, interpreter); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); this.index = Number(this.assertBigInt(stack.pop(), this.line)); super.execute(stack); } } // Pops: ... stack, {uint64 A}, {any B} // Pushes: None // pop indexes A and B. store B to the Ath scratch space export class Stores extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Stores index number according to arguments passed * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 0, this.line); this.interpreter = interpreter; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const value = stack.pop(); const index = this.assertBigInt(stack.pop(), this.line); this.checkIndexBound(Number(index), this.interpreter.scratch, this.line); this.interpreter.scratch[Number(index)] = value; } } // Pops: None // Pushes: None // Begin preparation of a new inner transaction export class ITxnBegin extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Stores index number according to arguments passed * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 0, this.line); this.interpreter = interpreter; } execute (stack: TEALStack): void { if (typeof this.interpreter.subTxn !== "undefined") { throw new RuntimeError( RUNTIME_ERRORS.TEAL.ITXN_BEGIN_WITHOUT_ITXN_SUBMIT, { line: this.line }); } if (this.interpreter.innerTxns.length >= MAX_INNER_TRANSACTIONS) { throw new RuntimeError( RUNTIME_ERRORS.GENERAL.MAX_INNER_TRANSACTIONS_EXCEEDED, { line: this.line, len: this.interpreter.innerTxns.length + 1, max: MAX_INNER_TRANSACTIONS }); } // get app, assert it exists const appID = this.interpreter.runtime.ctx.tx.apid ?? 0; this.interpreter.runtime.assertAppDefined( appID, this.interpreter.getApp(appID, this.line), this.line ); // get application's account const address = getApplicationAddress(appID); const applicationAccount = this.interpreter.runtime.assertAccountDefined( address, this.interpreter.runtime.ctx.state.accounts.get(address), this.line ); // calculate feeCredit(extra fee) accross all txns let totalFee = 0; for (const t of this.interpreter.runtime.ctx.gtxs) { totalFee += (t.fee ?? 0); }; for (const t of this.interpreter.innerTxns) { totalFee += (t.fee ?? 0); } const totalTxCnt = this.interpreter.runtime.ctx.gtxs.length + this.interpreter.innerTxns.length; const feeCredit = (totalFee - (ALGORAND_MIN_TX_FEE * totalTxCnt)); let txFee; if (feeCredit >= ALGORAND_MIN_TX_FEE) { txFee = 0; // we have enough fee in pool } else { const diff = feeCredit - ALGORAND_MIN_TX_FEE; txFee = (diff >= 0) ? diff : ALGORAND_MIN_TX_FEE; } const txnParams = { // set sender, fee, fv, lv snd: Buffer.from( algosdk.decodeAddress( applicationAccount.address ).publicKey ), fee: txFee, fv: this.interpreter.runtime.ctx.tx.fv, lv: this.interpreter.runtime.ctx.tx.lv, // to avoid type hack gen: this.interpreter.runtime.ctx.tx.gen, gh: this.interpreter.runtime.ctx.tx.gh, txID: "", type: "" }; this.interpreter.subTxn = txnParams; } } // Set field F of the current inner transaction to X(last value fetched from stack) // itxn_field fails if X is of the wrong type for F, including a byte array // of the wrong size for use as an address when F is an address field. // itxn_field also fails if X is an account or asset that does not appear in txn.Accounts // or txn.ForeignAssets of the top-level transaction. // (Setting addresses in asset creation are exempted from this requirement.) // pops from stack [...stack, any] // push to stack [...stack, none] export class ITxnField extends Op { readonly field: string; readonly interpreter: Interpreter; readonly line: number; /** * Set transaction field according to arguments passed * @param args Expected arguments: [transaction field] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.assertTxFieldDefined(args[0], interpreter.tealVersion, line); assertLen(args.length, 1, line); this.field = args[0]; // field this.interpreter = interpreter; } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const valToSet: StackElem = stack.pop(); if (typeof this.interpreter.subTxn === "undefined") { throw new RuntimeError( RUNTIME_ERRORS.TEAL.ITXN_FIELD_WITHOUT_ITXN_BEGIN, { line: this.line }); } const updatedSubTx = setInnerTxField(this.interpreter.subTxn, this.field, valToSet, this, this.interpreter, this.line); this.interpreter.subTxn = updatedSubTx; } } // Pops: None // Pushes: None // Execute the current inner transaction. export class ITxnSubmit extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Stores index number according to arguments passed * @param args Expected arguments: [] * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 0, this.line); this.interpreter = interpreter; } execute (stack: TEALStack): void { if (typeof this.interpreter.subTxn === "undefined") { throw new RuntimeError( RUNTIME_ERRORS.TEAL.ITXN_SUBMIT_WITHOUT_ITXN_BEGIN, { line: this.line }); } // calculate fee accross all txns let totalFee = 0; for (const t of this.interpreter.runtime.ctx.gtxs) { totalFee += (t.fee ?? 0); }; for (const t of this.interpreter.innerTxns) { totalFee += (t.fee ?? 0); } totalFee += (this.interpreter.subTxn.fee ?? 0); const totalTxCnt = this.interpreter.runtime.ctx.gtxs.length + this.interpreter.innerTxns.length + 1; // fee too less accross pool const feeBal = (totalFee - (ALGORAND_MIN_TX_FEE * totalTxCnt)); if (feeBal < 0) { throw new RuntimeError( RUNTIME_ERRORS.TRANSACTION.FEES_NOT_ENOUGH, { required: ALGORAND_MIN_TX_FEE * totalTxCnt, collected: totalFee } ); } // get execution txn params (parsed from encoded sdk txn obj) const execParams = parseEncodedTxnToExecParams(this.interpreter.subTxn, this.interpreter, this.line); const baseCurrTx = this.interpreter.runtime.ctx.tx; const baseCurrTxGrp = this.interpreter.runtime.ctx.gtxs; // execute innner transaction this.interpreter.runtime.ctx.tx = this.interpreter.subTxn; this.interpreter.runtime.ctx.gtxs = [this.interpreter.subTxn]; this.interpreter.runtime.ctx.isInnerTx = true; this.interpreter.runtime.ctx.processTransactions([execParams]); // update current txns to base (top-level) after innerTx execution this.interpreter.runtime.ctx.tx = baseCurrTx; this.interpreter.runtime.ctx.gtxs = baseCurrTxGrp; // save executed tx, reset current tx this.interpreter.runtime.ctx.isInnerTx = false; this.interpreter.innerTxns.push(this.interpreter.subTxn); this.interpreter.subTxn = undefined; } } // push field F of the last inner transaction to stack // push to stack [...stack, transaction field] export class ITxn extends Op { readonly field: string; readonly idx: number | undefined; readonly interpreter: Interpreter; readonly line: number; /** * Set transaction field according to arguments passed * @param args Expected arguments: [transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.idx = undefined; this.assertITxFieldDefined(args[0], interpreter.tealVersion, line); if (TxArrFields[interpreter.tealVersion].has(args[0])) { // eg. itxn Accounts 1 assertLen(args.length, 2, line); assertOnlyDigits(args[1], line); this.idx = Number(args[1]); } else { assertLen(args.length, 1, line); } this.assertITxFieldDefined(args[0], interpreter.tealVersion, line); this.field = args[0]; // field this.interpreter = interpreter; } execute (stack: TEALStack): void { if (this.interpreter.innerTxns.length === 0) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.NO_INNER_TRANSACTION_AVAILABLE, { version: this.interpreter.tealVersion, line: this.line }); } let result; const tx = this.interpreter.innerTxns[this.interpreter.innerTxns.length - 1]; switch (this.field) { case 'Logs': { // TODO handle this after log opcode is implemented // https://www.pivotaltracker.com/story/show/179855820 result = 0n; break; } case 'NumLogs': { // TODO handle this after log opcode is implemented result = 0n; break; } case 'CreatedAssetID': { result = BigInt(this.interpreter.runtime.ctx.createdAssetID); break; } case 'CreatedApplicationID': { result = 0n; // can we create an app in inner-tx? break; } default: { // similarly as Txn Op if (this.idx !== undefined) { // if field is an array use txAppArg (with "Accounts"/"ApplicationArgs"/'Assets'..) result = txAppArg(this.field, tx, this.idx, this, this.interpreter.tealVersion, this.line); } else { result = txnSpecbyField(this.field, tx, [tx], this.interpreter.tealVersion); } break; } } stack.push(result); } } export class ITxna extends Op { readonly field: string; readonly idx: number; readonly interpreter: Interpreter; readonly line: number; /** * Sets `field` and `idx` values according to arguments passed. * @param args Expected arguments: [transaction field, transaction field array index] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; assertLen(args.length, 2, line); assertOnlyDigits(args[1], line); this.assertITxArrFieldDefined(args[0], interpreter.tealVersion, line); this.field = args[0]; // field this.idx = Number(args[1]); this.interpreter = interpreter; } execute (stack: TEALStack): void { if (this.interpreter.innerTxns.length === 0) { throw new RuntimeError(RUNTIME_ERRORS.TEAL.NO_INNER_TRANSACTION_AVAILABLE, { version: this.interpreter.tealVersion, line: this.line }); } const tx = this.interpreter.innerTxns[this.interpreter.innerTxns.length - 1]; const result = txAppArg(this.field, tx, this.idx, this, this.interpreter.tealVersion, this.line); stack.push(result); } } /** * txnas F: * push Xth value of the array field F of the current transaction * pops from stack: [...stack, uint64] * pushes to stack: [...stack, transaction field] */ export class Txnas extends Txna { /** * Sets `field`, `txIdx` values according to arguments passed. * @param args Expected arguments: [transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // NOTE: 100 is a mock value. // In txnas & gtxnas opcodes, index is fetched from top of stack. // eg. [ int 1; txnas Accounts; ], [ txna Accounts 1]. super([...args, "100"], line, interpreter); assertLen(args.length, 1, line); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); this.idx = Number(top); super.execute(stack); } } /** * gtxnas T F: * push Xth value of the array field F from the Tth transaction in the current group * pops from stack: [...stack, uint64] * push to stack [...stack, value of field] */ export class Gtxnas extends Gtxna { /** * Sets `field`(Transaction Field) and * `txIdx`(Transaction Group Index) values according to arguments passed. * @param args Expected arguments: [transaction group index, transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // NOTE: 100 is a mock value. // In txnas & gtxnas opcodes, index is fetched from top of stack. // eg. [ int 1; gtxnas 0 Accounts; ], [ gtxna 0 Accounts 1]. super([...args, "100"], line, interpreter); assertLen(args.length, 2, line); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); this.idx = Number(top); super.execute(stack); } } /** * gtxnsas F: * pop an index A and an index B. push Bth value of the array * field F from the Ath transaction in the current group * pops from stack: [...stack, {uint64 A}, {uint64 B}] * push to stack [...stack, value of field] */ export class Gtxnsas extends Gtxna { /** * Sets `field`(Transaction Field) * @param args Expected arguments: [transaction field] * // Note: Transaction field is expected as string instead of number. * For ex: `Fee` is expected and `0` is not expected. * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { // NOTE: 100 is a mock value. // In gtxnsas opcode, {tx-index, index of array field} is fetched from top of stack. // eg. [ int 0; int 1; gtxnsas Accounts; ], [ gtxna 0 Accounts 1]. super(["100", args[0], "100"], line, interpreter); assertLen(args.length, 1, line); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 2, this.line); const arrFieldIdx = this.assertBigInt(stack.pop(), this.line); const txIdxInGrp = this.assertBigInt(stack.pop(), this.line); this.idx = Number(arrFieldIdx); this.txIdx = Number(txIdxInGrp); super.execute(stack); } } // pushes Arg[N] from LogicSig argument array to stack // Pops: ... stack, uint64 // push to stack [...stack, bytes] export class Args extends Arg { /** * Gets the argument value from interpreter.args array. * store the value in _arg variable * @param args Expected arguments: none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super([...args, "100"], line, interpreter); assertLen(args.length, 0, line); } execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const top = this.assertBigInt(stack.pop(), this.line); this.index = Number(top); super.execute(stack); } } // Write bytes to log state of the current application // pops to stack [...stack, bytes] // Pushes: None export class Log extends Op { readonly interpreter: Interpreter; readonly line: number; /** * Asserts 0 arguments are passed. * @param args Expected arguments: [] // none * @param line line number in TEAL file * @param interpreter interpreter object */ constructor (args: string[], line: number, interpreter: Interpreter) { super(); this.line = line; this.interpreter = interpreter; assertLen(args.length, 0, line); }; execute (stack: TEALStack): void { this.assertMinStackLen(stack, 1, this.line); const logByte = this.assertBytes(stack.pop(), this.line); const txID = this.interpreter.runtime.ctx.tx.txID; const txReceipt = this.interpreter.runtime.ctx.state.txReceipts.get(txID) as TxReceipt; if (txReceipt.logs === undefined) { txReceipt.logs = []; } // max no. of logs exceeded if (txReceipt.logs.length === ALGORAND_MAX_LOGS_COUNT) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.LOGS_COUNT_EXCEEDED_THRESHOLD, { maxLogs: ALGORAND_MAX_LOGS_COUNT, line: this.line } ); } // max "length" of logs exceeded const length = txReceipt.logs.join("").length + logByte.length; if (length > ALGORAND_MAX_LOGS_LENGTH) { throw new RuntimeError( RUNTIME_ERRORS.TEAL.LOGS_LENGTH_EXCEEDED_THRESHOLD, { maxLength: ALGORAND_MAX_LOGS_LENGTH, origLength: length, line: this.line } ); } txReceipt.logs.push(convertToString(logByte)); } }
the_stack
import { GitProcess } from 'dugite' import * as FSE from 'fs-extra' import * as Path from 'path' import { IStatusResult, getChangedFiles } from '../../../../src/lib/git' import { abortRebase, continueRebase, rebase, RebaseResult, } from '../../../../src/lib/git/rebase' import { AppFileStatusKind, CommittedFileChange, } from '../../../../src/models/status' import { createRepository } from '../../../helpers/repository-builder-rebase-test' import { getStatusOrThrow } from '../../../helpers/status' import { getBranchOrError } from '../../../helpers/git' import { IBranchTip } from '../../../../src/models/branch' const baseBranchName = 'base-branch' const featureBranchName = 'this-is-a-feature' describe('git/rebase', () => { describe('detect conflicts', () => { let result: RebaseResult let originalBranchTip: string let baseBranchTip: string let status: IStatusResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) originalBranchTip = featureBranch.tip.sha const baseBranch = await getBranchOrError(repository, baseBranchName) baseBranchTip = baseBranch.tip.sha result = await rebase(repository, baseBranch, featureBranch) status = await getStatusOrThrow(repository) }) it('returns a value indicating conflicts were encountered', async () => { expect(result).toBe(RebaseResult.ConflictsEncountered) }) it('status detects REBASE_HEAD', async () => { expect(status.rebaseInternalState).toEqual({ originalBranchTip, baseBranchTip, targetBranch: 'this-is-a-feature', }) }) it('has conflicted files in working directory', async () => { expect( status.workingDirectory.files.filter( f => f.status.kind === AppFileStatusKind.Conflicted ) ).toHaveLength(2) }) it('is a detached HEAD state', async () => { expect(status.currentBranch).toBeUndefined() }) }) describe('abort after conflicts found', () => { let status: IStatusResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) const baseBranch = await getBranchOrError(repository, baseBranchName) await rebase(repository, baseBranch, featureBranch) await abortRebase(repository) status = await getStatusOrThrow(repository) }) it('REBASE_HEAD is no longer found', async () => { expect(status.rebaseInternalState).toBeNull() }) it('no longer has working directory changes', async () => { expect(status.workingDirectory.files).toHaveLength(0) }) it('returns to the feature branch', async () => { expect(status.currentBranch).toBe(featureBranchName) }) }) describe('attempt to continue without resolving conflicts', () => { let result: RebaseResult let originalBranchTip: string let baseBranchTip: string let status: IStatusResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) originalBranchTip = featureBranch.tip.sha const baseBranch = await getBranchOrError(repository, baseBranchName) baseBranchTip = baseBranch.tip.sha await rebase(repository, baseBranch, featureBranch) // the second parameter here represents files that the UI indicates have // no conflict markers, so can be safely staged before continuing the // rebase result = await continueRebase(repository, [], []) status = await getStatusOrThrow(repository) }) it('indicates that the rebase was not complete', async () => { expect(result).toBe(RebaseResult.OutstandingFilesNotStaged) }) it('REBASE_HEAD is still found', async () => { expect(status.rebaseInternalState).toEqual({ originalBranchTip, baseBranchTip, targetBranch: 'this-is-a-feature', }) }) it('still has conflicted files in working directory', async () => { expect( status!.workingDirectory.files.filter( f => f.status.kind === AppFileStatusKind.Conflicted ) ).toHaveLength(2) }) }) describe('continue after resolving conflicts', () => { let beforeRebaseTip: IBranchTip let result: RebaseResult let status: IStatusResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) beforeRebaseTip = featureBranch.tip const baseBranch = await getBranchOrError(repository, baseBranchName) await rebase(repository, baseBranch, featureBranch) const afterRebase = await getStatusOrThrow(repository) const { files } = afterRebase.workingDirectory const diffCheckBefore = await GitProcess.exec( ['diff', '--check'], repository.path ) expect(diffCheckBefore.exitCode).toBeGreaterThan(0) // resolve conflicts by writing files to disk await FSE.writeFile( Path.join(repository.path, 'THING.md'), '# HELLO WORLD! \nTHINGS GO HERE\nFEATURE BRANCH UNDERWAY\n' ) await FSE.writeFile( Path.join(repository.path, 'OTHER.md'), '# HELLO WORLD! \nTHINGS GO HERE\nALSO FEATURE BRANCH UNDERWAY\n' ) const diffCheckAfter = await GitProcess.exec( ['diff', '--check'], repository.path ) expect(diffCheckAfter.exitCode).toEqual(0) result = await continueRebase(repository, files, []) status = await getStatusOrThrow(repository) }) it('returns success', () => { expect(result).toBe(RebaseResult.CompletedWithoutError) }) it('REBASE_HEAD is no longer found', () => { expect(status.rebaseInternalState).toBeNull() }) it('no longer has working directory changes', () => { expect(status.workingDirectory.files).toHaveLength(0) }) it('returns to the feature branch', () => { expect(status.currentBranch).toBe(featureBranchName) }) it('branch is now a different ref', () => { expect(status.currentTip).not.toBe(beforeRebaseTip.sha) }) }) describe('continue with additional changes unrelated to conflicted files', () => { let beforeRebaseTip: IBranchTip let filesInRebasedCommit: ReadonlyArray<CommittedFileChange> let result: RebaseResult let status: IStatusResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) beforeRebaseTip = featureBranch.tip const baseBranch = await getBranchOrError(repository, baseBranchName) await rebase(repository, baseBranch, featureBranch) // resolve conflicts by writing files to disk await FSE.writeFile( Path.join(repository.path, 'THING.md'), '# HELLO WORLD! \nTHINGS GO HERE\nFEATURE BRANCH UNDERWAY\n' ) await FSE.writeFile( Path.join(repository.path, 'OTHER.md'), '# HELLO WORLD! \nTHINGS GO HERE\nALSO FEATURE BRANCH UNDERWAY\n' ) // change unrelated tracked while rebasing changes await FSE.writeFile( Path.join(repository.path, 'THIRD.md'), 'this change should be included in the latest commit' ) // add untracked file before continuing rebase await FSE.writeFile( Path.join(repository.path, 'UNTRACKED-FILE.md'), 'this file should remain in the working directory' ) const afterRebase = await getStatusOrThrow(repository) const { files } = afterRebase.workingDirectory result = await continueRebase(repository, files, []) status = await getStatusOrThrow(repository) filesInRebasedCommit = await getChangedFiles( repository, [], status.currentTip! ) }) it('returns success', () => { expect(result).toBe(RebaseResult.CompletedWithoutError) }) it('keeps untracked working directory file out of rebase', () => { expect(status.workingDirectory.files).toHaveLength(1) }) it('has modified but unconflicted file in commit contents', () => { expect( filesInRebasedCommit.find(f => f.path === 'THIRD.md') ).not.toBeUndefined() }) it('returns to the feature branch', () => { expect(status.currentBranch).toBe(featureBranchName) }) it('branch is now a different ref', () => { expect(status.currentTip).not.toBe(beforeRebaseTip.sha) }) }) describe('continue with tracked change omitted from list', () => { let result: RebaseResult beforeEach(async () => { const repository = await createRepository( baseBranchName, featureBranchName ) const featureBranch = await getBranchOrError( repository, featureBranchName ) const baseBranch = await getBranchOrError(repository, baseBranchName) await rebase(repository, baseBranch, featureBranch) // resolve conflicts by writing files to disk await FSE.writeFile( Path.join(repository.path, 'THING.md'), '# HELLO WORLD! \nTHINGS GO HERE\nFEATURE BRANCH UNDERWAY\n' ) await FSE.writeFile( Path.join(repository.path, 'OTHER.md'), '# HELLO WORLD! \nTHINGS GO HERE\nALSO FEATURE BRANCH UNDERWAY\n' ) // change unrelated tracked while rebasing changes await FSE.writeFile( Path.join(repository.path, 'THIRD.md'), 'this change should be included in the latest commit' ) const afterRebase = await getStatusOrThrow(repository) const { files } = afterRebase.workingDirectory // omit the last change should cause Git to error because it requires // all tracked changes to be staged as a prerequisite for rebasing const onlyConflictedFiles = files.filter(f => f.path !== 'THIRD.md') result = await continueRebase(repository, onlyConflictedFiles, []) }) it('returns error code indicating that required files were missing', () => { expect(result).toBe(RebaseResult.OutstandingFilesNotStaged) }) }) })
the_stack
import * as R from "ramda"; import { Auth, Api, Client, Model } from "@core/types"; import { BaseArgs } from "../types"; import { sha256 } from "@core/lib/crypto/utils"; import { dispatch, refreshState } from "./core"; import { logAndExitIfActionFailed } from "./args"; import { exit } from "./process"; import chalk from "chalk"; import Table from "cli-table3"; import { spinner, stopSpinner } from "./spinner"; import { wait } from "@core/lib/utils/wait"; import util from "util"; import { getPrompt } from "./console_io"; import { detectApp } from "../app_detection"; export const authenticate = async < IncludePendingSelfHostedType extends boolean | undefined >( state: Client.State, argv: BaseArgs, forceChooseAccount?: true, maybeTargetObjectId?: string ): Promise<{ auth: Client.ClientUserAuth | Client.ClientCliAuth | undefined; accountIdOrCliKey: string | undefined; }> => { let auth: Client.ClientUserAuth | Client.ClientCliAuth | undefined, accountIdOrCliKey: string | undefined; const accounts = Object.values( state.orgUserAccounts ) as Client.ClientUserAuth[]; const signedInAccounts = accounts.filter((acct) => acct.token); argv["detectedApp"] = await detectApp(state, argv, process.cwd()); if (argv["cli-envkey"] ?? process.env.CLI_ENVKEY) { accountIdOrCliKey = (argv["cli-envkey"] ?? process.env.CLI_ENVKEY)!; const hash = sha256(accountIdOrCliKey), cliAuth = state.cliKeyAccounts[hash]; if (cliAuth) { auth = cliAuth; } else { const res = await dispatch({ type: Client.ActionType.AUTHENTICATE_CLI_KEY, payload: { cliKey: accountIdOrCliKey }, }); auth = res.state.cliKeyAccounts[hash]; } } else if (argv.account) { auth = await authFromEmail(state, argv.account, argv.org, accounts); } else if (maybeTargetObjectId && signedInAccounts.length > 1) { // if we are targeting a specific object in the graph for an action // look through signed in accounts to see if that object is in one // of their graphs, and if so then use that account for (let acct of signedInAccounts) { let accountState = await refreshState(acct.userId); if (!accountState.graphUpdatedAt) { const res = await dispatch({ type: Client.ActionType.GET_SESSION, }); if (res.success) { accountState = res.state; } } if (accountState.graph[maybeTargetObjectId]) { auth = acct; break; } } } else if (argv["detectedApp"] && !forceChooseAccount) { auth = state.orgUserAccounts[argv["detectedApp"].accountId]; } else if (state.defaultAccountId && !forceChooseAccount) { auth = state.orgUserAccounts[state.defaultAccountId]; } else if (signedInAccounts.length == 1 && !forceChooseAccount) { auth = signedInAccounts[0]; } else if (accounts.length == 1) { auth = accounts[0]; } else if (accounts.length > 1) { auth = await chooseAccount(state, false, false); } if (!auth) { return exit( 1, chalk.bold("Authentication required."), "Use", chalk.bold("`envkey sign-in`") + ", or", chalk.bold("`envkey accept-invite`") ); } if (auth.type == "clientUserAuth" && (!auth.token || !auth.privkey)) { auth = await signIn(auth); } return { auth, accountIdOrCliKey: accountIdOrCliKey ?? auth?.userId, }; }, chooseAccount = async <IncludePendingSelfHostedType extends boolean>( state: Client.State, signedInOnly: boolean, includePendingSelfHosted: IncludePendingSelfHostedType, chooseAccountFilter?: (auth: Client.ClientUserAuth) => boolean ) => { const prompt = getPrompt(); let choices = ( Object.values(state.orgUserAccounts) as Client.ClientUserAuth[] ) .filter( (auth) => (!signedInOnly || auth.token) && (!chooseAccountFilter || chooseAccountFilter(auth)) ) .map((acct) => ({ name: acct.userId, message: `${acct.orgName} - ${chalk.bold(acct.email)}`, })); if (includePendingSelfHosted) { choices = choices.concat( state.pendingSelfHostedDeployments.map((pending, i) => ({ name: i.toString(), message: `${pending.orgName} - ${chalk.bold(pending.email)}`, })) ); } if (choices.length === 0) { return undefined; } const { id } = await prompt<{ id: string }>({ type: "select", name: "id", message: "Select an account on this device:", initial: 0, choices, }); return ( includePendingSelfHosted ? state.orgUserAccounts[id] ?? state.pendingSelfHostedDeployments[parseInt(id)] : state.orgUserAccounts[id] ) as IncludePendingSelfHostedType extends true ? Client.ClientUserAuth | Client.PendingSelfHostedDeployment : Client.ClientUserAuth; }, chooseOrg = async ( state: Client.State, emailOrUserId: string, signedIn?: true ): Promise<Client.ClientUserAuth> => { const prompt = getPrompt(); const { id } = await prompt<{ id: string }>({ type: "select", name: "id", message: "Select an account on this device:", initial: 0, choices: (Object.values(state.orgUserAccounts) as Client.ClientUserAuth[]) .filter( (acct) => (acct.email == emailOrUserId || acct.userId === emailOrUserId) && (!signedIn || acct.token) ) .map((acct) => ({ name: "id", value: acct.userId, message: chalk.bold(acct.orgName), })), }); return state.orgUserAccounts[id]!; }, authFromEmail = async ( state: Client.State, emailOrUserId: string, org?: string, accountsArg?: Client.ClientUserAuth[] ) => { const accounts = accountsArg ?? (Object.values(state.orgUserAccounts) as Client.ClientUserAuth[]), candidates = accounts.filter( (acct) => acct!.email == emailOrUserId || acct.userId == emailOrUserId ); if (candidates.length == 1) { return candidates[0]; } else if (candidates.length > 1) { if (org) { return candidates.find(({ orgName }) => orgName.toLowerCase() == org); } else { return chooseOrg(state, emailOrUserId); } } return undefined; }; export async function signIn( auth: Client.ClientUserAuth ): Promise<Client.ClientUserAuth>; export async function signIn( auth: Client.ClientUserAuth, pendingSelfHostedDeploymentIndex: undefined, attemptCounter?: number ): Promise<Client.ClientUserAuth>; export async function signIn( auth: Client.PendingSelfHostedDeployment, pendingSelfHostedDeploymentIndex: number, attemptCounter?: number ): Promise<Client.ClientUserAuth>; // recusive calls of signIn() are recommended to pass the attempt counter export async function signIn( auth: Client.ClientUserAuth | Client.PendingSelfHostedDeployment, pendingSelfHostedDeploymentIndex?: number | undefined, attemptCounter = 0 ): Promise<Client.ClientUserAuth> { const prompt = getPrompt(); let emailVerificationToken: string | undefined; let externalAuthSessionId: string | undefined; if (attemptCounter > 4) { // Infinite loop due to a bug somewhere. None are known at this time, but this has happened and slammed the server. throw new Error("Too many retry attempts on sign-in"); } if (auth.type == "pendingSelfHostedDeployment") { console.log( `\nIf your installation of EnvKey Self-Hosted finished successfully, you should have received an email at ${ auth.email } including an ${chalk.bold("Init Token")}.\n\n${chalk.bold( "*Note:" )} you might also need to wait for DNS records to finish propagating for ${chalk.bold( auth.domain )}\n` ); let { initToken } = await prompt<{ initToken: string; }>({ type: "password", name: "initToken", message: `Paste your ${chalk.bold("Init Token")} here:`, }); const loginRes = await dispatch({ type: Client.ActionType.SIGN_IN_PENDING_SELF_HOSTED, payload: { initToken, index: pendingSelfHostedDeploymentIndex! }, }); await logAndExitIfActionFailed( loginRes, `Failed to sign in to Self-Hosted EnvKey installation. Please ensure that the installation has completed successfully and try again.\nYou can check installation status here:\n\n${chalk.bold( auth.codebuildLink )}\n\n${chalk.bold( "*Note:" )} you might also need to wait for DNS records to finish propagating on your domain: ${chalk.bold( auth.domain )}` ); return R.last( R.sortBy( R.prop("addedAt"), Object.values( loginRes.state.orgUserAccounts as Record< string, Client.ClientUserAuth > ) ) )!; } else { // not pending self-hosted. regular sign-in to account on device. const { email, userId } = auth; switch (auth.provider) { case "email": spinner(); const createVerifRes = await dispatch( { type: Api.ActionType.CREATE_EMAIL_VERIFICATION, payload: { email, authType: "sign_in" }, }, userId ); stopSpinner(); const { verifyEmailError } = createVerifRes.state; if (verifyEmailError?.type === "signInWrongProviderError") { // provider will have been switched in new state return signIn( createVerifRes.state.orgUserAccounts[userId]!, undefined, attemptCounter + 1 ); } // normal email sign-in await logAndExitIfActionFailed( createVerifRes, "Failed creating an email verification token." ); ({ emailVerificationToken } = await prompt<{ emailVerificationToken: string; }>({ type: "password", name: "emailVerificationToken", message: `${chalk.green.bold( "Sign In →" )} an email verification was just sent to ${chalk.green.bold( email )}. Paste it here:`, })); spinner(); let checkValidRes = await dispatch( { type: Api.ActionType.CHECK_EMAIL_TOKEN_VALID, payload: { email, token: emailVerificationToken }, }, userId ); stopSpinner(); // TODO: add link to issues support here while (!checkValidRes.success) { ({ emailVerificationToken } = await prompt<{ emailVerificationToken: string; }>({ type: "password", name: "emailVerificationToken", message: "Sign in token invalid. Please try again:", })); spinner(); checkValidRes = await dispatch( { type: Api.ActionType.CHECK_EMAIL_TOKEN_VALID, payload: { email, token: emailVerificationToken }, }, userId ); stopSpinner(); } console.log(chalk.bold("Email verified.\n")); break; case "saml": const createSessRes = await dispatch({ type: Client.ActionType.CREATE_EXTERNAL_AUTH_SESSION_FOR_LOGIN, payload: { waitBeforeOpenMillis: 1500, authMethod: "saml", provider: "saml", externalAuthProviderId: auth.externalAuthProviderId!, orgId: auth.orgId, userId, }, }); // handle special errors where provider is different if (createSessRes.state.startingExternalAuthSessionError) { if ( ["requiresEmailAuthError", "signInWrongProviderError"].includes( createSessRes.state.startingExternalAuthSessionError.type ) ) { // auth method has changed to email since last time they logged in, state was updated by producer return signIn( createSessRes.state.orgUserAccounts[userId]!, undefined, attemptCounter + 1 ); } } await logAndExitIfActionFailed( createSessRes, "Failed creating SAML pending session" ); console.log( chalk.blueBright("You will be prompted to authenticate externally") ); let state = createSessRes.state; while (!state.completedExternalAuth) { process.stderr.write("."); await wait(950); state = await refreshState(); if (state.authorizingExternallyErrorMessage) { await exit( 1, util.inspect(state.authorizingExternallyErrorMessage) ); } } externalAuthSessionId = state.completedExternalAuth.externalAuthSessionId; console.log("Successfully logged in with SAML."); break; default: throw new Error( `External provider ${auth.provider} is not yet supported` ); } spinner(); const loginRes = await dispatch< Client.Action.ClientActions["CreateSession"] >( { type: Client.ActionType.CREATE_SESSION, payload: { accountId: userId, emailVerificationToken, externalAuthSessionId, }, }, userId ); stopSpinner(); await logAndExitIfActionFailed(loginRes, "Signing in failed."); return loginRes.state.orgUserAccounts[userId]!; } } export const listAccounts = (state: Client.State) => { const orgUserAccounts = R.toPairs( state.orgUserAccounts as Record<string, Client.ClientUserAuth> ), pendingSelfHostedDeployments = state.pendingSelfHostedDeployments.map( (auth, i) => [`pendingSelfHostedDeployment-${i}`, auth] ), accounts = R.sortBy(([_, auth]) => auth.orgName, [ ...orgUserAccounts, ...pendingSelfHostedDeployments, ] as [ string, Client.ClientUserAuth | Client.PendingSelfHostedDeployment ][]), numAccounts = accounts.length; console.log( chalk.bold( "You have", numAccounts, `EnvKey account${numAccounts > 1 ? "s" : ""}`, "on this device:" ) ); for (let [accountId, account] of accounts) { if (accountId == state.defaultAccountId) { continue; } printAccount(accountId, account, false, state.graph); } if (state.defaultAccountId) { printAccount( state.defaultAccountId, state.orgUserAccounts[state.defaultAccountId]!, true, state.graph ); } }; export const printAccount = ( accountId: string, account: Client.ClientUserAuth | Client.PendingSelfHostedDeployment, isDefault: boolean, graph?: Client.Graph.UserGraph ) => { let authStatus: string; if (account.type == "pendingSelfHostedDeployment") { authStatus = "Pending"; } else if (account.token) { authStatus = "Signed in"; } else { authStatus = " Signed out"; } const signedIn = authStatus == "Signed in"; const table = new Table({ colWidths: [11, 36, 13, 13], style: { head: [], //disable colors in header cells border: signedIn ? [isDefault ? "cyan" : "green"] : [], }, }); let { provider } = account; const thisUser = graph?.[accountId] as Model.OrgUser | undefined; if (thisUser?.provider) { // read from the graph, if it's the current active user provider = thisUser.provider; } table.push( [ { content: chalk.bold("🔑"), hAlign: "center", }, { content: chalk.bold(account.orgName), colSpan: isDefault ? 1 : 2, }, isDefault && { content: chalk.bgCyan(chalk.whiteBright(chalk.bold(" Default "))), hAlign: "center", }, { content: signedIn ? chalk.bgGreen(chalk.whiteBright(chalk.bold(` ${authStatus} `))) : authStatus, hAlign: "center", }, ].filter(Boolean) as any, ["Host", { content: chalk.bold(account.hostUrl), colSpan: 3 }], ["Email", { content: chalk.bold(account.email), colSpan: 3 }], [ "Auth", { content: chalk.bold(Auth.AUTH_PROVIDERS[provider]), colSpan: 3, }, ], [ "Device", { content: chalk.bold(account.deviceName), colSpan: 3, }, ], [ "Security", { content: chalk.bold( account.requiresPassphrase && account.lockoutMs ? account.requiresLockout ? `passphrase and max ${ account.lockoutMs / 1000 / 60 } minute lockout required` : "passphrase required, no lockout required" : "no passphrase or lockout required" ), colSpan: 3, }, ] ); console.log(""); console.log(table.toString()); }, printNoAccountsHelp = () => { console.log(chalk.bold("No EnvKey accounts are stored on this device.\n")); console.log("Try", chalk.bold("`envkey accept-invite`"), "\n"); }, printDeviceSettings = (state: Client.State) => { const defaultAccount = state.defaultAccountId ? state.orgUserAccounts[state.defaultAccountId] : undefined, defaultAccountString = defaultAccount ? [defaultAccount.orgName, defaultAccount.email].join(" - ") : "none"; const table = new Table({ colWidths: [22, 53], colAligns: ["left", "center"], style: { head: [], //disable colors in header cells }, }); table.push( [{ colSpan: 2, content: chalk.bold(chalk.cyan("Device Settings")) }], ["Default Device Name", state.defaultDeviceName], ["Has Passphrase", state.requiresPassphrase ? "yes" : "no"], [ "Inactivity Lockout", state.lockoutMs ? (state.lockoutMs / 1000 / 60).toString() + " minutes" : "none", ], ["Default Account", defaultAccountString] ); console.log(""); console.log(table.toString()); };
the_stack
import React, { useCallback, useEffect, useMemo, useState } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronDown, faChevronUp, faAngleLeft, faAngleDoubleLeft, faAngleRight, faAngleDoubleRight, } from "@fortawesome/free-solid-svg-icons"; import { useTable, useSortBy, useRowSelect, useGlobalFilter, usePagination, } from "react-table"; import { useTranslation } from "react-i18next"; import { useWindowSize } from "../hooks"; interface Props { selection: "multiple" | "single" | "none"; initialSortByField?: string; initialSortAscending?: boolean; screenReaderField?: string; filterQuery?: string; className?: string; onSelection?: Function; rows: Array<object>; pageSize?: 5 | 10 | 20 | 25 | 50 | 100; disablePagination?: boolean; disableBorderless?: boolean; width?: string | number | undefined; columns: Array<{ accessor?: string | Function; Header: string; Cell?: Function; id?: string; minWidth?: string | number | undefined; }>; selectedHeaders?: Set<string>; hiddenColumns?: Set<string>; addNumbersColumn?: boolean; sortByColumn?: string; sortByDesc?: boolean; setSortByColumn?: Function; setSortByDesc?: Function; reset?: Function; mobileNavigation?: boolean; } function Table(props: Props) { const { t } = useTranslation(); const windowSize = useWindowSize(); const isMobile = props.mobileNavigation || windowSize.width <= 600; const borderlessClassName = !props.disableBorderless ? " usa-table--borderless" : ""; const className = props.className ? ` ${props.className}` : ""; const [currentPage, setCurrentPage] = useState<string>("1"); const { initialSortByField, initialSortAscending, sortByColumn, sortByDesc, setSortByColumn, setSortByDesc, reset, } = props; const initialSortBy = useMemo(() => { return initialSortByField ? [ { id: initialSortByField, desc: !initialSortAscending, }, ] : []; }, [initialSortByField, initialSortAscending]); const { getTableProps, getTableBodyProps, headerGroups, toggleSortBy, prepareRow, rows, page, canPreviousPage, canNextPage, pageOptions, pageCount, gotoPage, nextPage, previousPage, setPageSize, state: { pageIndex, pageSize }, selectedFlatRows, setGlobalFilter, toggleAllRowsSelected, } = useTable( { columns: props.columns, data: props.rows, disableSortRemove: true, initialState: props.disablePagination ? { selectedRowIds: {}, sortBy: initialSortBy, } : { selectedRowIds: {}, sortBy: initialSortBy, pageIndex: 0, pageSize: props.pageSize || 25, }, }, useGlobalFilter, useSortBy, usePagination, useRowSelect, (hooks) => { if (props.selection === "single") { hooks.visibleColumns.push((columns) => [ { id: "selection", Header: ({}) => <div></div>, Cell: ({ row }) => ( <div> <IndeterminateRadio onClick={() => { toggleAllRowsSelected(false); row.toggleRowSelected(); }} {...row.getToggleRowSelectedProps()} /> </div> ), }, ...columns, ]); } else if (props.selection === "multiple") { hooks.visibleColumns.push((columns) => [ { id: "selection", Header: ({ getToggleAllRowsSelectedProps }) => ( <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} /> ), Cell: ({ row }) => ( <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} title={ props.screenReaderField ? row.values[props.screenReaderField] : null } /> ), }, ...columns, ]); } else if (props.addNumbersColumn) { hooks.visibleColumns.push((columns) => [ { id: "numbersListing", Header: () => { return <div>1</div>; }, Cell: ({ row }) => { return <div>{row.index + 2}</div>; }, }, ...columns, ]); } } ); useEffect(() => { if (setSortByColumn && setSortByDesc && reset) { for (const headerGroup of headerGroups) { for (const header of headerGroup.headers) { if ( header.isSorted && (sortByColumn !== header.id || sortByDesc !== header.isSortedDesc) ) { reset({ sortData: header.id ? `${header.id}###${header.isSortedDesc ? "desc" : "asc"}` : "", }); setSortByColumn(header.id); setSortByDesc(header.isSortedDesc); break; } } } } }, [rows]); useEffect(() => { if (sortByColumn) { toggleSortBy(sortByColumn, sortByDesc); } }, [sortByColumn, sortByDesc]); const { onSelection, filterQuery } = props; useEffect(() => { setGlobalFilter(filterQuery); }, [filterQuery, setGlobalFilter]); useEffect(() => { if (onSelection) { const values = selectedFlatRows.map((flatRow) => flatRow.original); onSelection(values); } }, [selectedFlatRows, onSelection]); const currentRows = props.disablePagination ? rows : page; const getCellBackground = useCallback( (id: string, defaultColor: string) => { if (id.startsWith("checkbox")) { for (const selectedHeader of Array.from(props.selectedHeaders ?? [])) { if (id.includes(selectedHeader)) { return "#97d4ea"; } } return defaultColor; } else { return props.selectedHeaders?.has(id) ? "#97d4ea" : defaultColor; } }, [props.selectedHeaders] ); return ( <> <div className="overflow-x-hidden overflow-y-hidden"> <table className={`usa-table${borderlessClassName}${className}`} width={props.width} {...getTableProps()} > <thead> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((column, i) => ( <th scope="col" {...column.getHeaderProps()} style={ props.selection !== "none" ? { padding: "0.5rem 1rem", } : { minWidth: column.minWidth, backgroundColor: `${getCellBackground( column.id, "" )}`, } } > <span> { /** * The split is to remove the quotes from the * string, the filter to remove the resulted * empty ones, and the join to form it again. */ typeof column.render("Header") === "string" ? (column.render("Header") as string) .split('"') .filter(Boolean) .join() : column.render("Header") } </span> {(props.selection !== "none" && i === 0) || (column.id && column.id.startsWith("checkbox")) || (column.id && column.id.startsWith("numbersListing")) ? null : ( <button className="margin-left-1 usa-button usa-button--unstyled" {...column.getSortByToggleProps()} title={`${t("ToggleSortBy")} ${column.Header}`} type="button" > <FontAwesomeIcon className={`hover:text-base ${ column.isSorted ? "text-base-darkest" : "text-base-lighter" }`} icon={ column.isSorted && column.isSortedDesc ? faChevronDown : faChevronUp } /> </button> )} </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {currentRows.map((row) => { prepareRow(row); return ( <tr {...row.getRowProps()}> {row.cells.map((cell, j) => { return j === 0 && props.selection === "none" ? ( <th style={{ backgroundColor: `${getCellBackground( cell.column.id, props.addNumbersColumn ? "#f0f0f0" : "" )}`, }} scope="row" {...cell.getCellProps()} > {cell.render("Cell")} </th> ) : ( <td style={{ backgroundColor: `${getCellBackground( cell.column.id, props.hiddenColumns?.has(cell.column.id) ? "#adadad" : "" )}`, }} {...cell.getCellProps()} > {cell.render("Cell")} </td> ); })} </tr> ); })} </tbody> </table> </div> {!props.disablePagination && rows.length ? ( <div className={`${ isMobile ? "grid-col" : "grid-row margin-bottom-05" } font-sans-sm`} > <div className={`${ isMobile ? "grid-row margin-bottom-2 margin-left-05" : "grid-col-3 text-left" } text-base text-italic`} > {`${t("Showing")} ${pageIndex * pageSize + 1}-${Math.min( pageIndex * pageSize + pageSize, rows.length )} ${t("Of")} ${rows.length}`} </div> <div className={`${ isMobile ? "margin-left-05" : "grid-col-6 text-center" }`} > {!isMobile && ( <> <button type="button" className="margin-right-1" onClick={() => { setCurrentPage("1"); gotoPage(0); }} disabled={!canPreviousPage} > <FontAwesomeIcon icon={faAngleDoubleLeft} className="margin-top-2px" /> </button> <button type="button" className="margin-right-2" onClick={() => { setCurrentPage(`${pageIndex}`); previousPage(); }} disabled={!canPreviousPage} > <FontAwesomeIcon icon={faAngleLeft} className="margin-top-2px" /> </button> </> )} {isMobile ? <div className="margin-bottom-1" /> : ""} <span className="margin-right-2px">{`${t("Page")} `}</span> <span className="margin-right-1"> <input type="text" value={`${currentPage}`} className="margin-right-2px" onChange={(e) => { setCurrentPage(e.target.value); }} style={{ width: "33px" }} pattern="\d*" /> {` of ${pageOptions.length} `} </span> <button type="button" className={`${ isMobile ? "" : "usa-button " }usa-button--unstyled margin-right-2 text-base-darker hover:text-base-darkest active:text-base-darkest`} onClick={() => { if (currentPage) { const currentPageNumber = Number(currentPage); if ( !isNaN(currentPageNumber) && currentPageNumber >= 1 && currentPageNumber <= pageOptions.length ) { gotoPage(currentPageNumber - 1); } } }} > {t("Go")} </button> {isMobile ? <div className="margin-top-1" /> : ""} {isMobile && ( <> <button type="button" className="margin-right-1" onClick={() => { setCurrentPage("1"); gotoPage(0); }} disabled={!canPreviousPage} > <FontAwesomeIcon icon={faAngleDoubleLeft} className="margin-top-2px" /> </button> <button type="button" className="margin-right-2" onClick={() => { setCurrentPage(`${pageIndex}`); previousPage(); }} disabled={!canPreviousPage} > <FontAwesomeIcon icon={faAngleLeft} className="margin-top-2px" /> </button> </> )} <button type="button" className="margin-right-1" onClick={() => { setCurrentPage(`${pageIndex + 2}`); nextPage(); }} disabled={!canNextPage} > <FontAwesomeIcon icon={faAngleRight} className="margin-top-2px" /> </button> <button type="button" onClick={() => { setCurrentPage(`${pageCount}`); gotoPage(pageCount - 1); }} disabled={!canNextPage} > <FontAwesomeIcon icon={faAngleDoubleRight} className="margin-top-2px" /> </button> </div> <div className={`${ isMobile ? "grid-row margin-top-2 margin-left-05 margin-bottom-05" : "grid-col-3 text-right" }`} > <select value={pageSize} onChange={(e) => { setPageSize(Number(e.target.value)); }} className="margin-right-05" > {[5, 10, 20, 25, 50, 100].map((pageSize) => ( <option key={pageSize} value={pageSize}> {t("Show")} {pageSize} </option> ))} </select> </div> </div> ) : ( "" )} </> ); } // Taken from example: https://react-table.tanstack.com/docs/examples/row-selection const IndeterminateCheckbox = React.forwardRef< HTMLInputElement, { indeterminate?: boolean; title?: string } >(({ indeterminate, title, ...rest }, ref) => { const defaultRef = React.useRef(null); const resolvedRef = ref || defaultRef; React.useEffect(() => { (resolvedRef as any).current.indeterminate = indeterminate; }, [resolvedRef, indeterminate]); return <input type="checkbox" title={title} ref={resolvedRef} {...rest} />; }); const IndeterminateRadio = React.forwardRef< HTMLInputElement, { indeterminate?: boolean; title?: string; checked?: boolean; onClick?: Function; } >(({ indeterminate, ...rest }, ref) => { const defaultRef = React.useRef(); const resolvedRef = ref || defaultRef; React.useEffect(() => { (resolvedRef as any).current.indeterminate = indeterminate; }, [resolvedRef, indeterminate]); return ( <> <input type="radio" ref={resolvedRef as any} {...rest} /> </> ); }); export default Table;
the_stack
import {fromEvent, merge, Subject} from 'rxjs'; import {filter, take, takeUntil} from 'rxjs/operators'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, Directive, ElementRef, EventEmitter, forwardRef, Input, NgZone, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {TranslationWidth} from '@angular/common'; import {NgbCalendar} from './ngb-calendar'; import {NgbDate} from './ngb-date'; import {DatepickerServiceInputs, NgbDatepickerService} from './datepicker-service'; import {DatepickerViewModel, DayViewModel, MonthViewModel, NavigationEvent} from './datepicker-view-model'; import {DayTemplateContext} from './datepicker-day-template-context'; import {NgbDatepickerConfig} from './datepicker-config'; import {NgbDateAdapter} from './adapters/ngb-date-adapter'; import {NgbDateStruct} from './ngb-date-struct'; import {NgbDatepickerI18n} from './datepicker-i18n'; import {NgbDatepickerKeyboardService} from './datepicker-keyboard-service'; import {isChangedDate, isChangedMonth} from './datepicker-tools'; import {hasClassName} from '../util/util'; /** * An event emitted right before the navigation happens and the month displayed by the datepicker changes. */ export interface NgbDatepickerNavigateEvent { /** * The currently displayed month. */ current: {year: number, month: number} | null; /** * The month we're navigating to. */ next: {year: number, month: number}; /** * Calling this function will prevent navigation from happening. * * @since 4.1.0 */ preventDefault: () => void; } /** * An interface that represents the readonly public state of the datepicker. * * Accessible via the `datepicker.state` getter * * @since 5.2.0 */ export interface NgbDatepickerState { /** * The earliest date that can be displayed or selected */ readonly minDate: NgbDate | null; /** * The latest date that can be displayed or selected */ readonly maxDate: NgbDate | null; /** * The first visible date of currently displayed months */ readonly firstDate: NgbDate; /** * The last visible date of currently displayed months */ readonly lastDate: NgbDate; /** * The date currently focused by the datepicker */ readonly focusedDate: NgbDate; /** * First dates of months currently displayed by the datepicker * * @since 5.3.0 */ readonly months: NgbDate[]; } /** * A directive that marks the content template that customizes the way datepicker months are displayed * * @since 5.3.0 */ @Directive({selector: 'ng-template[ngbDatepickerContent]'}) export class NgbDatepickerContent { constructor(public templateRef: TemplateRef<any>) {} } /** * A highly configurable component that helps you with selecting calendar dates. * * `NgbDatepicker` is meant to be displayed inline on a page or put inside a popup. */ @Component({ exportAs: 'ngbDatepicker', selector: 'ngb-datepicker', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, styleUrls: ['./datepicker.scss'], template: ` <ng-template #defaultDayTemplate let-date="date" let-currentMonth="currentMonth" let-selected="selected" let-disabled="disabled" let-focused="focused"> <div ngbDatepickerDayView [date]="date" [currentMonth]="currentMonth" [selected]="selected" [disabled]="disabled" [focused]="focused"> </div> </ng-template> <ng-template #defaultContentTemplate> <div *ngFor="let month of model.months; let i = index;" class="ngb-dp-month"> <div *ngIf="navigation === 'none' || (displayMonths > 1 && navigation === 'select')" class="ngb-dp-month-name"> {{ i18n.getMonthLabel(month.firstDate) }} </div> <ngb-datepicker-month [month]="month.firstDate"></ngb-datepicker-month> </div> </ng-template> <div class="ngb-dp-header"> <ngb-datepicker-navigation *ngIf="navigation !== 'none'" [date]="model.firstDate!" [months]="model.months" [disabled]="model.disabled" [showSelect]="model.navigation === 'select'" [prevDisabled]="model.prevDisabled" [nextDisabled]="model.nextDisabled" [selectBoxes]="model.selectBoxes" (navigate)="onNavigateEvent($event)" (select)="onNavigateDateSelect($event)"> </ngb-datepicker-navigation> </div> <div class="ngb-dp-content" [class.ngb-dp-months]="!contentTemplate" #content> <ng-template [ngTemplateOutlet]="contentTemplate?.templateRef || defaultContentTemplate"></ng-template> </div> <ng-template [ngTemplateOutlet]="footerTemplate"></ng-template> `, providers: [{provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NgbDatepicker), multi: true}, NgbDatepickerService] }) export class NgbDatepicker implements OnDestroy, OnChanges, OnInit, ControlValueAccessor { static ngAcceptInputType_autoClose: boolean | string; static ngAcceptInputType_navigation: string; static ngAcceptInputType_outsideDays: string; static ngAcceptInputType_weekdays: boolean | number; model: DatepickerViewModel; @ViewChild('defaultDayTemplate', {static: true}) private _defaultDayTemplate: TemplateRef<DayTemplateContext>; @ViewChild('content', {static: true}) private _contentEl: ElementRef<HTMLElement>; @ContentChild(NgbDatepickerContent, {static: true}) contentTemplate: NgbDatepickerContent; private _controlValue: NgbDate | null = null; private _destroyed$ = new Subject<void>(); private _publicState: NgbDatepickerState = <any>{}; /** * The reference to a custom template for the day. * * Allows to completely override the way a day 'cell' in the calendar is displayed. * * See [`DayTemplateContext`](#/components/datepicker/api#DayTemplateContext) for the data you get inside. */ @Input() dayTemplate: TemplateRef<DayTemplateContext>; /** * The callback to pass any arbitrary data to the template cell via the * [`DayTemplateContext`](#/components/datepicker/api#DayTemplateContext)'s `data` parameter. * * `current` is the month that is currently displayed by the datepicker. * * @since 3.3.0 */ @Input() dayTemplateData: (date: NgbDate, current?: {year: number, month: number}) => any; /** * The number of months to display. */ @Input() displayMonths: number; /** * The first day of the week. * * With default calendar we use ISO 8601: 'weekday' is 1=Mon ... 7=Sun. */ @Input() firstDayOfWeek: number; /** * The reference to the custom template for the datepicker footer. * * @since 3.3.0 */ @Input() footerTemplate: TemplateRef<any>; /** * The callback to mark some dates as disabled. * * It is called for each new date when navigating to a different month. * * `current` is the month that is currently displayed by the datepicker. */ @Input() markDisabled: (date: NgbDate, current?: {year: number, month: number}) => boolean; /** * The latest date that can be displayed or selected. * * If not provided, 'year' select box will display 10 years after the current month. */ @Input() maxDate: NgbDateStruct; /** * The earliest date that can be displayed or selected. * * If not provided, 'year' select box will display 10 years before the current month. */ @Input() minDate: NgbDateStruct; /** * Navigation type. * * * `"select"` - select boxes for month and navigation arrows * * `"arrows"` - only navigation arrows * * `"none"` - no navigation visible at all */ @Input() navigation: 'select' | 'arrows' | 'none'; /** * The way of displaying days that don't belong to the current month. * * * `"visible"` - days are visible * * `"hidden"` - days are hidden, white space preserved * * `"collapsed"` - days are collapsed, so the datepicker height might change between months * * For the 2+ months view, days in between months are never shown. */ @Input() outsideDays: 'visible' | 'collapsed' | 'hidden'; /** * If `true`, week numbers will be displayed. */ @Input() showWeekNumbers: boolean; /** * The date to open calendar with. * * With the default calendar we use ISO 8601: 'month' is 1=Jan ... 12=Dec. * If nothing or invalid date is provided, calendar will open with current month. * * You could use `navigateTo(date)` method as an alternative. */ @Input() startDate: {year: number, month: number, day?: number}; /** * The way weekdays should be displayed. * * * `true` - weekdays are displayed using default width * * `false` - weekdays are not displayed * * `TranslationWidth` - weekdays are displayed using specified width * * @since 9.1.0 */ @Input() weekdays: TranslationWidth | boolean; /** * An event emitted right before the navigation happens and displayed month changes. * * See [`NgbDatepickerNavigateEvent`](#/components/datepicker/api#NgbDatepickerNavigateEvent) for the payload info. */ @Output() navigate = new EventEmitter<NgbDatepickerNavigateEvent>(); /** * An event emitted when user selects a date using keyboard or mouse. * * The payload of the event is currently selected `NgbDate`. * * @since 5.2.0 */ @Output() dateSelect = new EventEmitter<NgbDate>(); onChange = (_: any) => {}; onTouched = () => {}; constructor( private _service: NgbDatepickerService, private _calendar: NgbCalendar, public i18n: NgbDatepickerI18n, config: NgbDatepickerConfig, cd: ChangeDetectorRef, private _elementRef: ElementRef<HTMLElement>, private _ngbDateAdapter: NgbDateAdapter<any>, private _ngZone: NgZone) { ['dayTemplate', 'dayTemplateData', 'displayMonths', 'firstDayOfWeek', 'footerTemplate', 'markDisabled', 'minDate', 'maxDate', 'navigation', 'outsideDays', 'showWeekNumbers', 'startDate', 'weekdays'] .forEach(input => this[input] = config[input]); _service.dateSelect$.pipe(takeUntil(this._destroyed$)).subscribe(date => { this.dateSelect.emit(date); }); _service.model$.pipe(takeUntil(this._destroyed$)).subscribe(model => { const newDate = model.firstDate !; const oldDate = this.model ? this.model.firstDate : null; // update public state this._publicState = { maxDate: model.maxDate, minDate: model.minDate, firstDate: model.firstDate !, lastDate: model.lastDate !, focusedDate: model.focusDate !, months: model.months.map(viewModel => viewModel.firstDate) }; let navigationPrevented = false; // emitting navigation event if the first month changes if (!newDate.equals(oldDate)) { this.navigate.emit({ current: oldDate ? {year: oldDate.year, month: oldDate.month} : null, next: {year: newDate.year, month: newDate.month}, preventDefault: () => navigationPrevented = true }); // can't prevent the very first navigation if (navigationPrevented && oldDate !== null) { this._service.open(oldDate); return; } } const newSelectedDate = model.selectedDate; const newFocusedDate = model.focusDate; const oldFocusedDate = this.model ? this.model.focusDate : null; this.model = model; // handling selection change if (isChangedDate(newSelectedDate, this._controlValue)) { this._controlValue = newSelectedDate; this.onTouched(); this.onChange(this._ngbDateAdapter.toModel(newSelectedDate)); } // handling focus change if (isChangedDate(newFocusedDate, oldFocusedDate) && oldFocusedDate && model.focusVisible) { this.focus(); } cd.markForCheck(); }); } /** * Returns the readonly public state of the datepicker * * @since 5.2.0 */ get state(): NgbDatepickerState { return this._publicState; } /** * Returns the calendar service used in the specific datepicker instance. * * @since 5.3.0 */ get calendar(): NgbCalendar { return this._calendar; } /** * Focuses on given date. */ focusDate(date?: NgbDateStruct | null): void { this._service.focus(NgbDate.from(date)); } /** * Selects focused date. */ focusSelect(): void { this._service.focusSelect(); } focus() { this._ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => { const elementToFocus = this._elementRef.nativeElement.querySelector<HTMLDivElement>('div.ngb-dp-day[tabindex="0"]'); if (elementToFocus) { elementToFocus.focus(); } }); } /** * Navigates to the provided date. * * With the default calendar we use ISO 8601: 'month' is 1=Jan ... 12=Dec. * If nothing or invalid date provided calendar will open current month. * * Use the `[startDate]` input as an alternative. */ navigateTo(date?: {year: number, month: number, day?: number}) { this._service.open(NgbDate.from(date ? date.day ? date as NgbDateStruct : {...date, day: 1} : null)); } ngAfterViewInit() { this._ngZone.runOutsideAngular(() => { const focusIns$ = fromEvent<FocusEvent>(this._contentEl.nativeElement, 'focusin'); const focusOuts$ = fromEvent<FocusEvent>(this._contentEl.nativeElement, 'focusout'); const {nativeElement} = this._elementRef; // we're changing 'focusVisible' only when entering or leaving months view // and ignoring all focus events where both 'target' and 'related' target are day cells merge(focusIns$, focusOuts$) .pipe( filter( ({target, relatedTarget}) => !(hasClassName(target, 'ngb-dp-day') && hasClassName(relatedTarget, 'ngb-dp-day') && nativeElement.contains(target as Node) && nativeElement.contains(relatedTarget as Node))), takeUntil(this._destroyed$)) .subscribe(({type}) => this._ngZone.run(() => this._service.set({focusVisible: type === 'focusin'}))); }); } ngOnDestroy() { this._destroyed$.next(); } ngOnInit() { if (this.model === undefined) { const inputs: DatepickerServiceInputs = {}; ['dayTemplateData', 'displayMonths', 'markDisabled', 'firstDayOfWeek', 'navigation', 'minDate', 'maxDate', 'outsideDays', 'weekdays'] .forEach(name => inputs[name] = this[name]); this._service.set(inputs); this.navigateTo(this.startDate); } if (!this.dayTemplate) { this.dayTemplate = this._defaultDayTemplate; } } ngOnChanges(changes: SimpleChanges) { const inputs: DatepickerServiceInputs = {}; ['dayTemplateData', 'displayMonths', 'markDisabled', 'firstDayOfWeek', 'navigation', 'minDate', 'maxDate', 'outsideDays', 'weekdays'] .filter(name => name in changes) .forEach(name => inputs[name] = this[name]); this._service.set(inputs); if ('startDate' in changes) { const {currentValue, previousValue} = changes.startDate; if (isChangedMonth(previousValue, currentValue)) { this.navigateTo(this.startDate); } } } onDateSelect(date: NgbDate) { this._service.focus(date); this._service.select(date, {emitEvent: true}); } onNavigateDateSelect(date: NgbDate) { this._service.open(date); } onNavigateEvent(event: NavigationEvent) { switch (event) { case NavigationEvent.PREV: this._service.open(this._calendar.getPrev(this.model.firstDate !, 'm', 1)); break; case NavigationEvent.NEXT: this._service.open(this._calendar.getNext(this.model.firstDate !, 'm', 1)); break; } } registerOnChange(fn: (value: any) => any): void { this.onChange = fn; } registerOnTouched(fn: () => any): void { this.onTouched = fn; } setDisabledState(disabled: boolean) { this._service.set({disabled}); } writeValue(value) { this._controlValue = NgbDate.from(this._ngbDateAdapter.fromModel(value)); this._service.select(this._controlValue); } } /** * A component that renders one month including all the days, weekdays and week numbers. Can be used inside * the `<ng-template ngbDatepickerMonths></ng-template>` when you want to customize months layout. * * For a usage example, see [custom month layout demo](#/components/datepicker/examples#custommonth) * * @since 5.3.0 */ @Component({ selector: 'ngb-datepicker-month', host: {'role': 'grid', '(keydown)': 'onKeyDown($event)'}, encapsulation: ViewEncapsulation.None, styleUrls: ['./datepicker-month.scss'], template: ` <div *ngIf="viewModel.weekdays.length > 0" class="ngb-dp-week ngb-dp-weekdays" role="row"> <div *ngIf="datepicker.showWeekNumbers" class="ngb-dp-weekday ngb-dp-showweek small">{{ i18n.getWeekLabel() }}</div> <div *ngFor="let weekday of viewModel.weekdays" class="ngb-dp-weekday small" role="columnheader">{{ weekday }}</div> </div> <ng-template ngFor let-week [ngForOf]="viewModel.weeks"> <div *ngIf="!week.collapsed" class="ngb-dp-week" role="row"> <div *ngIf="datepicker.showWeekNumbers" class="ngb-dp-week-number small text-muted">{{ i18n.getWeekNumerals(week.number) }}</div> <div *ngFor="let day of week.days" (click)="doSelect(day); $event.preventDefault()" class="ngb-dp-day" role="gridcell" [class.disabled]="day.context.disabled" [tabindex]="day.tabindex" [class.hidden]="day.hidden" [class.ngb-dp-today]="day.context.today" [attr.aria-label]="day.ariaLabel"> <ng-template [ngIf]="!day.hidden"> <ng-template [ngTemplateOutlet]="datepicker.dayTemplate" [ngTemplateOutletContext]="day.context"></ng-template> </ng-template> </div> </div> </ng-template> ` }) export class NgbDatepickerMonth { /** * The first date of month to be rendered. * * This month must one of the months present in the * [datepicker state](#/components/datepicker/api#NgbDatepickerState). */ @Input() set month(month: NgbDateStruct) { this.viewModel = this._service.getMonth(month); } viewModel: MonthViewModel; constructor( public i18n: NgbDatepickerI18n, public datepicker: NgbDatepicker, private _keyboardService: NgbDatepickerKeyboardService, private _service: NgbDatepickerService) {} onKeyDown(event: KeyboardEvent) { this._keyboardService.processKey(event, this.datepicker); } doSelect(day: DayViewModel) { if (!day.context.disabled && !day.hidden) { this.datepicker.onDateSelect(day.date); } } }
the_stack
import * as WebSocket from 'faye-websocket' import * as EJSON from 'ejson' import { EventEmitter } from 'events' import got from 'got' export interface TLSOpts { // Described in https://nodejs.org/api/tls.html#tls_tls_connect_options_callback /* Necessary only if the server uses a self-signed certificate.*/ ca?: Buffer[] // example: [ fs.readFileSync('server-cert.pem') ] /* Necessary only if the server requires client certificate authentication.*/ key?: Buffer // example: fs.readFileSync('client-key.pem'), cert?: Buffer // example: fs.readFileSync('client-cert.pem'), /* Necessary only if the server's cert isn't for "localhost". */ checkServerIdentity?: (hostname: string, cert: object) => Error | undefined // () => { }, // Returns <Error> object, populating it with reason, host, and cert on failure. On success, returns <undefined>. } /** * Options set when creating a new DDP client connection. */ export interface DDPConnectorOptions { host: string port: number path?: string ssl?: boolean debug?: boolean autoReconnect?: boolean // default: true autoReconnectTimer?: number tlsOpts?: TLSOpts useSockJs?: boolean url?: string maintainCollections?: boolean ddpVersion?: '1' | 'pre2' | 'pre1' } /** * Observer watching for changes to a collection. */ export interface Observer { /** Name of the collection being observed */ readonly name: string /** Identifier of this observer */ readonly id: string /** * Callback when a document is added to a collection. * @callback * @param id Identifier of the document added * @param fields The added document */ added: (id: string, fields?: { [attr: string]: unknown }) => void /** Callback when a document is changed in a collection. */ changed: (id: string, oldFields: { [attr: string]: unknown }, clearedFields: Array<string>, newFields: { [attr: string]: unknown }) => void /** Callback when a document is removed from a collection. */ removed: (id: string, oldValue: { [attr: string]: unknown }) => void /** Request to stop observing the collection */ stop: () => void } /** DDP message type for client requests to servers */ export type ClientServer = 'connect' | 'ping' | 'pong' | 'method' | 'sub' | 'unsub' /** DDP message type for server requests to clients */ export type ServerClient = 'failed' | 'connected' | 'result' | 'updated' | 'nosub' | 'added' | 'removed' | 'changed' | 'ready' | 'ping' | 'pong' | 'error' /** All types of DDP messages */ export type MessageType = ClientServer | ServerClient /** * Represents any DDP message sent from as a request or response from a server to a client. */ export interface Message { /** Kind of meteor message */ msg: MessageType } /** * DDP-specified error. * Note. Different fields to a Javascript error. */ export interface DDPError { error: string | number reason?: string message?: string errorType: 'Meteor.Error' } /** * Request message to initiate a connection from a client to a server. */ interface Connect extends Message { msg: 'connect' /** If trying to reconnect to an existing DDP session */ session?: string /** The proposed protocol version */ version: string /** Protocol versions supported by the client, in order of preference */ support: Array<string> } /** * Response message sent when a client's connection request was successful. */ interface Connected extends Message { msg: 'connected' /** An identifier for the DDP session */ session: string } /** * Response message when a client's connection request was unsuccessful. */ interface Failed extends Message { msg: 'failed' /** A suggested protocol version to connect with */ version: string } /** * Heartbeat request message. Can be sent from server to client or client to server. */ interface Ping extends Message { msg: 'ping' /** Identifier used to correlate with response */ id?: string } /** * Heartbeat response message. */ interface Pong extends Message { msg: 'pong' /** Same as received in the `ping` message */ id?: string } /** * Message from the client specifying the sets of information it is interested in. * The server should then send `added`, `changed` and `removed` messages matching * the subscribed types. */ interface Sub extends Message { msg: 'sub' /** An arbitrary client-determined identifier for this subscription */ id: string /** Name of the subscription */ name: string /** Parameters to the subscription. Most be serializable to EJSON. */ params?: Array<unknown> } /** * Request to unsubscribe from messages related to an existing subscription. */ interface UnSub extends Message { msg: 'unsub' /** The `id` passed to `sub` */ id: string } /** * Message sent when a subscription is unsubscribed. Contains an optional error if a * problem occurred. */ interface NoSub extends Message { msg: 'nosub' /** The client `id` passed to `sub` for this subscription. */ id: string /** An error raised by the subscription as it concludes, or sub-not-found */ error?: DDPError } /** * Notification that a document has been added to a collection. */ interface Added extends Message { msg: 'added' /** Collection name */ collection: string /** Document identifier */ id: string /** Document values - serializable with EJSON */ fields?: { [ attr: string]: unknown } } /** * Notification that a document has changed within a collection. */ interface Changed extends Message { msg: 'changed' /** Collection name */ collection: string /** Document identifier */ id: string /** Document values - serializable with EJSON */ fields?: { [ attr: string]: unknown } /** Field names to delete */ cleared?: Array<string> } /** * Notification that a document has been removed from a collection. */ interface Removed extends Message { msg: 'removed' /** Collection name */ collection: string /** Document identifier */ id: string } /** * Message sent to client after an initial salvo of updates have sent a * complete set of initial data. */ interface Ready extends Message { msg: 'ready' /** Identifiers passed to `sub` which have sent their initial batch of data */ subs: Array<string> } /** * Remote procedure call request request. */ interface Method extends Message { msg: 'method' /** Method name */ method: string /** Parameters to the method */ params?: Array<unknown> /** An arbitrary client-determined identifier for this method call */ id: string /** An arbitrary client-determined seed for pseudo-random generators */ randomSeed?: string } /** * Remote procedure call response message, either an error or a return value _result_. */ interface Result extends Message { msg: 'result' /** Method name */ id: string /** An error thrown by the method, or method nor found */ error?: DDPError /** Return value of the method */ result?: unknown } /** * Message sent to indicate that all side-effect changes to subscribed data caused by * a method have completed. */ interface Updated extends Message { msg: 'updated' /** Identifiers passed to `method`, all of whose writes have been reflected in data messages */ methods: Array<string> } /** * Erroneous messages sent from the client to the server can result in receiving a top-level * `error` message in response. */ interface ErrorMessage extends Message { msg: 'error' /** Description of the error */ reason: string /** If the original message parsed properly, it is included here */ offendingMessage?: Message } export type AnyMessage = Connect | Connected | Failed | Ping | Pong | Sub | UnSub | NoSub | Added | Changed | Removed | Ready | Method | Result | Updated | ErrorMessage /** * Class reprsenting a DDP client and its connection. */ export class DDPClient extends EventEmitter { public collections: { [collectionName: string]: { [id: string]: { _id: string, [attr: string]: unknown } } } public socket: WebSocket.Client public session: string private hostInt: string public get host (): string { return this.hostInt } private portInt: number public get port (): number { return this.portInt } private pathInt?: string public get path (): string | undefined { return this.pathInt } private sslInt: boolean public get ssl (): boolean { return this.sslInt } private useSockJSInt: boolean public get useSockJS (): boolean { return this.useSockJSInt } private autoReconnectInt: boolean public get autoReconnect () { return this.autoReconnectInt } private autoReconnectTimerInt: number public get autoReconnectTimer (): number { return this.autoReconnectTimerInt } private ddpVersionInt: '1' | 'pre2' | 'pre1' public get ddpVersion () { return this.ddpVersionInt } private urlInt?: string public get url (): string | undefined { return this.urlInt } private maintainCollectionsInt: boolean public get maintainCollections (): boolean { return this.maintainCollectionsInt } public static readonly ERRORS: { [ name: string]: DDPError } = { DISCONNECTED: { error: 'DISCONNECTED', message: 'DDPClient: Disconnected from DDP server', errorType: 'Meteor.Error' } } public static readonly supportedDdpVersions = [ '1', 'pre2', 'pre1'] private tlsOpts: TLSOpts private isConnecting: boolean = false private isReconnecting: boolean = false private isClosing: boolean = false private connectionFailed: boolean = false private nextId: number = 0 private callbacks: { [id: string]: (error?: DDPError, result?: unknown) => void } = {} private updatedCallbacks: { [name: string]: Function } = {} private pendingMethods: { [id: string]: boolean } = {} private observers: { [name: string]: { [_id: string]: Observer } } = {} private reconnectTimeout: NodeJS.Timeout | null = null constructor (opts?: DDPConnectorOptions) { super() opts || (opts = { host: '127.0.0.1', port: 3000, tlsOpts: {} }) this.resetOptions(opts) this.ddpVersionInt = opts.ddpVersion || '1' // very very simple collections (name -> [{id -> document}]) if (this.maintainCollections) { this.collections = {} } } resetOptions (opts: DDPConnectorOptions) { // console.log(opts) this.hostInt = opts.host || '127.0.0.1' this.portInt = opts.port || 3000 this.pathInt = opts.path this.sslInt = opts.ssl || this.port === 443 this.tlsOpts = opts.tlsOpts || {} this.useSockJSInt = opts.useSockJs || false this.autoReconnectInt = opts.autoReconnect === false ? false : true this.autoReconnectTimerInt = opts.autoReconnectTimer || 500 this.maintainCollectionsInt = opts.maintainCollections || true this.urlInt = opts.url this.ddpVersionInt = opts.ddpVersion || '1' } private prepareHandlers (): void { this.socket.on('open', () => { // just go ahead and open the connection on connect this.send({ msg : 'connect', version : this.ddpVersion, support : DDPClient.supportedDdpVersions }) }) this.socket.on('error', (error: Error) => { // error received before connection was established if (this.isConnecting) { this.emit('failed', error.message) } this.emit('socket-error', error) }) this.socket.on('close', (event) => { this.emit('socket-close', event.code, event.reason) this.endPendingMethodCalls() this.recoverNetworkError() }) this.socket.on('message', (event) => { this.message(event.data) this.emit('message', event.data) }) } private clearReconnectTimeout (): void { if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout) this.reconnectTimeout = null } } private recoverNetworkError (err?: any): void { // console.log('autoReconnect', this.autoReconnect, 'connectionFailed', this.connectionFailed, 'isClosing', this.isClosing) if (this.autoReconnect && !this.connectionFailed && !this.isClosing) { this.clearReconnectTimeout() this.reconnectTimeout = setTimeout(() => { this.connect() }, this.autoReconnectTimer) this.isReconnecting = true } else { if (err) { throw err } } } /////////////////////////////////////////////////////////////////////////// // RAW, low level functions private send (data: AnyMessage): void { if (data.msg !== 'connect' && this.isConnecting) { this.endPendingMethodCalls() } else { this.socket.send( EJSON.stringify(data) ) } } private failed (data: Failed): void { if (DDPClient.supportedDdpVersions.indexOf(data.version) !== -1) { this.ddpVersionInt = (data.version as '1' | 'pre2' | 'pre1') this.connect() } else { this.autoReconnectInt = false this.emit('failed', 'Cannot negotiate DDP version') } } private connected (data: Connected): void { this.session = data.session this.isConnecting = false this.isReconnecting = false this.emit('connected') } private result (data: Result): void { // console.log('Received result', data, this.callbacks, this.callbacks[data.id]) const cb = this.callbacks[data.id] || undefined if (cb) { cb(data.error, data.result) data.id && (delete this.callbacks[data.id]) } } private updated (data: Updated): void { if (data.methods) { data.methods.forEach(method => { const cb = this.updatedCallbacks[method] if (cb) { cb() delete this.updatedCallbacks[method] } }) } } private nosub (data: NoSub): void { const cb = data.id && this.callbacks[data.id] || undefined if (cb) { cb(data.error) data.id && (delete this.callbacks[data.id]) } } private added (data: Added): void { // console.log('Received added', data, this.maintainCollections) if (this.maintainCollections) { const name = data.collection const id = data.id || 'unknown' if (!this.collections[name]) { this.collections[name] = {} } if (!this.collections[name][id]) { this.collections[name][id] = { _id: id } } if (data.fields) { Object.entries(data.fields).forEach(([key, value]) => { this.collections[name][id][key] = value }) } if (this.observers[name]) { Object.values(this.observers[name]).forEach(ob => ob.added(id, data.fields)) } } } private removed (data: Removed): void { if (this.maintainCollections) { const name = data.collection const id = data.id || 'unknown' if (!this.collections[name][id]) { return } let oldValue = this.collections[name][id] delete this.collections[name][id] if (this.observers[name]) { Object.values(this.observers[name]).forEach(ob => ob.removed(id, oldValue)) } } } private changed (data: Changed): void { if (this.maintainCollections) { const name = data.collection const id = data.id || 'unknown' if (!this.collections[name]) { return } if (!this.collections[name][id]) { return } let oldFields: { [attr: string]: unknown } = {} const clearedFields = data.cleared || [] let newFields: { [attr: string]: unknown } = {} if (data.fields) { Object.entries(data.fields).forEach(([key, value]) => { oldFields[key] = this.collections[name][id][key] newFields[key] = value this.collections[name][id][key] = value }) } if (data.cleared) { data.cleared.forEach(value => { delete this.collections[name][id][value] }) } if (this.observers[name]) { Object.values(this.observers[name]).forEach(ob => ob.changed(id, oldFields, clearedFields, newFields)) } } } private ready (data: Ready): void { // console.log('Received ready', data, this.callbacks) data.subs.forEach(id => { const cb = this.callbacks[id] if (cb) { cb() delete this.callbacks[id] } }) } private ping (data: Ping): void { this.send( data.id && { msg : 'pong', id : data.id } as Pong || { msg : 'pong' } as Pong ) } private messageWork: { [name in ServerClient]: (data: Message) => void } = { failed: this.failed.bind(this), connected: this.connected.bind(this), result: this.result.bind(this), updated: this.updated.bind(this), nosub: this.nosub.bind(this), added: this.added.bind(this), removed: this.removed.bind(this), changed: this.changed.bind(this), ready: this.ready.bind(this), ping: this.ping.bind(this), pong: () => { /* Do nothing */ }, error: () => { /* Do nothing */} // TODO - really do nothing!?! } // handle a message from the server private message (rawData: string): void { // console.log('Received message', rawData) const data: Message = EJSON.parse(rawData) if (this.messageWork[data.msg as ServerClient]) { this.messageWork[data.msg as ServerClient](data) } } private getNextId (): string { return (this.nextId += 1).toString() } private addObserver (observer: Observer): void { if (!this.observers[observer.name]) { this.observers[observer.name] = {} } this.observers[observer.name][observer.id] = observer } private removeObserver (observer: Observer): void { if (!this.observers[observer.name]) { return } delete this.observers[observer.name][observer.id] } ////////////////////////////////////////////////////////////////////////// // USER functions -- use these to control the client /* open the connection to the server * * connected(): Called when the 'connected' message is received * If autoReconnect is true (default), the callback will be * called each time the connection is opened. */ connect (connected?: (error?: Error, wasReconnect?: boolean) => void): void { this.isConnecting = true this.connectionFailed = false this.isClosing = false if (connected) { this.addListener('connected', () => { this.clearReconnectTimeout() this.isConnecting = false this.isReconnecting = false connected(undefined, this.isReconnecting) }) this.addListener('failed', error => { this.isConnecting = false this.connectionFailed = true connected(error, this.isReconnecting) }) } if (this.useSockJS) { this.makeSockJSConnection().catch(e => { this.emit('failed', e) }) } else { const url = this.buildWsUrl() this.makeWebSocketConnection(url) } } private endPendingMethodCalls (): void { const ids = Object.keys(this.pendingMethods) this.pendingMethods = {} ids.forEach(id => { if (this.callbacks[id]) { this.callbacks[id](DDPClient.ERRORS.DISCONNECTED) delete this.callbacks[id] } if (this.updatedCallbacks[id]) { this.updatedCallbacks[id]() delete this.updatedCallbacks[id] } }) } private async makeSockJSConnection (): Promise<void> { const protocol = this.ssl ? 'https://' : 'http://' if (this.path && !this.path?.endsWith('/')) { this.pathInt = this.path + '/' } const url = `${protocol}${this.host}:${this.port}/${this.path || ''}sockjs/info` try { let response = await got(url, { https: { certificateAuthority: this.tlsOpts.ca, key: this.tlsOpts.key, certificate: this.tlsOpts.cert, checkServerIdentity: this.tlsOpts.checkServerIdentity }, responseType: 'json' }) // Info object defined here(?): https://github.com/sockjs/sockjs-node/blob/master/lib/info.js const info = response.body as { base_url: string } if (!info || !info.base_url) { const url = this.buildWsUrl() this.makeWebSocketConnection(url) } else if (info.base_url.indexOf('http') === 0) { const url = info.base_url + '/websocket' url.replace(/^http/, 'ws') this.makeWebSocketConnection(url) } else { const path = info.base_url + '/websocket' const url = this.buildWsUrl(path) this.makeWebSocketConnection(url) } } catch (err) { this.recoverNetworkError(err) } } private buildWsUrl (path?: string): string { let url: string path = path || this.path || 'websocket' const protocol = this.ssl ? 'wss://' : 'ws://' if (this.url && !this.useSockJS) { url = this.url } else { url = `${protocol}${this.host}:${this.port}${(path.indexOf('/') === 0) ? path : '/' + path}` } return url } private makeWebSocketConnection (url: string): void { // console.log('About to create WebSocket client') this.socket = new WebSocket.Client(url, null, { tls: this.tlsOpts }) this.prepareHandlers() } close (): void { this.isClosing = true this.socket && this.socket.close() // with mockJS connection, might not get created this.removeAllListeners('connected') this.removeAllListeners('failed') } call ( methodName: string, data: Array<unknown>, callback: (err: Error, result: unknown) => void, updatedCallback?: (err: Error, result: unknown) => void ): void { // console.log('Call', methodName, 'with this.isConnecting = ', this.isConnecting) const id = this.getNextId() this.callbacks[id] = (error?: DDPError, result?: unknown) => { delete this.pendingMethods[id] if (callback) { callback.apply(this, [error, result]) } } const self = this this.updatedCallbacks[id] = function () { delete self.pendingMethods[id] if (updatedCallback) { updatedCallback.apply(this, arguments) } } this.pendingMethods[id] = true this.send({ msg : 'method', id : id, method : methodName, params : data }) } callWithRandomSeed ( methodName: string, data: Array<unknown>, randomSeed: string, callback: (err?: DDPError, result?: unknown) => void, updatedCallback?: (err?: Error, result?: unknown) => void ): void { const id = this.getNextId() if (callback) { this.callbacks[id] = callback } if (updatedCallback) { this.updatedCallbacks[id] = updatedCallback } this.send({ msg : 'method', id : id, method : methodName, randomSeed : randomSeed, params : data }) } // open a subscription on the server, callback should handle on ready and nosub subscribe (subscriptionName: string, data: Array<unknown>, callback: () => void): string { const id = this.getNextId() if (callback) { this.callbacks[id] = callback } this.send({ msg : 'sub', id : id, name : subscriptionName, params : data }) return id } unsubscribe (subscriptionId: string): void { this.send({ msg : 'unsub', id : subscriptionId }) } /** * Adds an observer to a collection and returns the observer. * Observation can be stopped by calling the stop() method on the observer. * Functions for added, changed and removed can be added to the observer * afterward. */ observe ( collectionName: string, added?: () => {}, changed?: () => {}, removed?: () => {} ): Observer { const observer: Observer = { id: this.getNextId(), name: collectionName, added: added || (() => { /* Do nothing */ }), changed: changed || (() => { /* Do nothing */ }), removed: removed || (() => { /* Do nothing */ }), stop: () => { this.removeObserver(observer) } } this.addObserver(observer) return observer } }
the_stack
import { BaseInfo32, limbSize32, limbInv32, limbsPerDigit32 } from './BaseInfo32'; import { BigFloatBase } from './BigFloatBase'; import { trimNumber } from './util'; export class BigFloat32 implements BigFloatBase<BigFloat32> { constructor(value?: BigFloat32 | number | string, base?: number) { value ? this.setValue(value, base) : this.setZero(); } clone() { return(new BigFloat32().setBig(this)); } setZero() { this.sign = 1; this.fractionLen = 0; this.len = 0; return(this); } setValue(other: BigFloat32 | number | string, base?: number) { if(typeof(other) == 'number') { return(this.setNumber(other)); } if(other instanceof BigFloat32) { return(this.setBig(other)); } return(this.setString(other.toString(), base || 10)); } private setBig(other: BigFloat32) { const len = other.len; this.sign = other.sign; this.fractionLen = other.fractionLen; this.len = len; for(let pos = 0; pos < len; ++pos) { this.limbList[pos] = other.limbList[pos]; } return(this); } /** Set value from a floating point number (probably IEEE 754 double). */ private setNumber(value: number) { if(value < 0) { value = -value; this.sign = -1; } else { this.sign = 1; } let iPart = Math.floor(value); let fPart = value - iPart; let fractionLen = 0; const limbList = this.limbList; let limb: number; let len = 0; // Handle fractional part. while(fPart) { // Extract limbs starting from the most significant. fPart *= limbSize32; limb = fPart >>> 0; fPart -= limb; // Append limb to value (limbs are reversed later). limbList[len++] = limb; ++fractionLen; } // Reverse array from 0 to len. let pos = 0; while(--len > pos) { limb = limbList[pos]; limbList[pos++] = limbList[len]; limbList[len] = limb; } len += pos + 1; // Handle integer part. while(iPart) { // Extract limbs starting from the least significant. limb = iPart % limbSize32; // Could also be iPart >>> 0 iPart = (iPart - limb) / limbSize32; // Append limb to value. limbList[len++] = limb; } this.limbList = limbList; this.fractionLen = fractionLen; this.len = len; return(this); } private parseFraction(value: string, base: number, start: number, offset: number, limbBase: number, limbDigits: number) { const limbList = this.limbList; let pos = value.length; // Set limbs to zero, because divInt uses them as input. let limbNum = offset - 1; while(limbNum) { limbList[--limbNum] = 0; } // Read initial digits so their count becomes divisible by limbDigits. let posNext = pos - ((pos - start + limbDigits - 1) % limbDigits + 1); limbList[offset - 1] = parseInt(value.substr(posNext, pos - posNext), base); this.divInt(Math.pow(base, pos - posNext), offset); pos = posNext; // Read rest of the digits in limbDigits sized chunks. while(pos > start) { pos -= limbDigits; limbList[offset - 1] = parseInt(value.substr(pos, limbDigits), base); // Divide by maximum power of base that fits in a limb. this.divInt(limbBase, offset); } } private setString(value: string, base: number) { const { limbBase, limbDigits, limbDigitsExact } = BaseInfo32.init(base); const limbList = this.limbList; let pos = -1; let c: string; this.sign = 1; // Handle leading signs and zeroes. while(1) { c = value.charAt(++pos); switch(c) { case '-': this.sign = -1; case '+': case '0': continue; } break; } const posDot = (value.indexOf('.', pos) + 1 || value.length + 1) - 1; // Handle fractional part. if(posDot < value.length - 1) { // Reserve enough limbs to contain digits in fractional part. const len = ~~((value.length - posDot - 1) / limbDigitsExact) + 1; this.parseFraction(value, base, posDot + 1, len + 1, limbBase, limbDigits); this.fractionLen = len; this.len = len; // Remove trailing zeroes. this.trimLeast(); } else { this.fractionLen = 0; this.len = 0; } const offset = this.fractionLen; // Handle integer part. if(posDot > pos) { // Read initial digits so their count becomes divisible by limbDigits. let posNext = pos + (posDot - pos + limbDigits - 1) % limbDigits + 1; ++this.len; limbList[offset] = parseInt(value.substr(pos, posNext - pos), base); pos = posNext; // Read rest of the digits in limbDigits sized chunks. while(pos < posDot) { // Multiply by maximum power of base that fits in a limb. if(this.mulInt(limbBase, limbList, offset, offset, 0)) ++this.len; // Add latest limb. limbList[offset] += parseInt(value.substr(pos, limbDigits), base); pos += limbDigits; } } return(this); } /** Trim zero limbs from most significant end. */ private trimMost() { const limbList = this.limbList; const fractionLen = this.fractionLen; let len = this.len; while(len > fractionLen && !limbList[len - 1]) --len; this.len = len; } /** Trim zero limbs from least significant end. */ private trimLeast() { const limbList = this.limbList; let len = this.fractionLen; let pos = 0; while(pos < len && !limbList[pos]) ++pos; if(pos) this.truncate(len - pos); } /** Multiply by an integer and write output limbs to another list. */ private mulInt(factor: number, dstLimbList: number[], srcPos: number, dstPos: number, overwriteMask: number) { if(!factor) return(0); const limbList = this.limbList; const limbCount = this.len; let limb: number; let lo: number; let carry = 0; // limbList is an array of 32-bit ints but split here into 16-bit low // and high words for multiplying by a 32-bit term, so the intermediate // 48-bit multiplication results fit into 53 bits of IEEE 754 mantissa. while(srcPos < limbCount) { limb = limbList[srcPos++]; // Multiply lower half of limb with factor, making carry temporarily take 48 bits. carry += factor * (limb & 0xffff); // Get lowest 16 bits of full product. lo = carry & 0xffff; // Right shift by dividing because >> and >>> truncate to 32 bits before shifting. carry = (carry - lo) / 65536; // Multiply higher half of limb and combine with lowest 16 bits of full product. carry += factor * (limb >>> 16); lo |= carry << 16; // Lowest 32 bits of full product are added to output limb. limb = ((dstLimbList[dstPos] & overwriteMask) + lo) >>> 0; dstLimbList[dstPos++] = limb; // Highest 32 bits of full product stay in carry, also increment by 1 if previous sum overflowed. carry = (carry / 65536) >>> 0; // Bit twiddle equivalent to: if(limb < (lo >>> 0)) ++carry; carry += (lo ^ (((limb - lo) ^ lo) & ~(limb ^ lo))) >>> 31; } // Extend result by one more limb if it overflows. if(carry) dstLimbList[dstPos] = carry; return(carry); } private mulBig(multiplier: BigFloat32, product: BigFloat32) { if(this.isZero() || multiplier.isZero()) return(product.setZero()); const multiplierLimbs = multiplier.limbList; const lenMultiplier = multiplier.len; const productLimbs = product.limbList; let posProduct = this.len + lenMultiplier; product.len = posProduct; // TODO: Only clear from len to len + lenMultiplier while(posProduct--) { productLimbs[posProduct] = 0; } this.mulInt(multiplierLimbs[0], productLimbs, 0, 0, 0); for(let posMultiplier = 1; posMultiplier < lenMultiplier; ++posMultiplier) { this.mulInt(multiplierLimbs[posMultiplier], productLimbs, 0, posMultiplier, 0xffffffff); } product.sign = this.sign * multiplier.sign as (-1 | 1); product.fractionLen = this.fractionLen + multiplier.fractionLen; product.trimMost(); product.trimLeast(); return(product); } /** Multiply and return product in a new BigFloat32. */ mul(multiplier: number | BigFloat32, product?: BigFloat32) { product = product || new BigFloat32(); if(typeof(multiplier) == 'number') { multiplier = temp32.setNumber(multiplier); } if(product == this) throw(new Error('Multiplication in place is unsupported')); return(this.mulBig(multiplier, product)); } absDeltaFrom(other: number | BigFloat32) { if(typeof(other) == 'number') { other = temp32.setNumber(other); } const limbList = this.limbList; const otherList = other.limbList; let limbCount = this.len; let otherCount = other.len; // Compare lengths. // Note: leading zeroes in integer part must be trimmed for this to work! let d = (limbCount - this.fractionLen) - (otherCount - other.fractionLen); // If lengths are equal, compare each limb from most to least significant. while(!d && limbCount && otherCount) d = limbList[--limbCount] - otherList[--otherCount]; if(d) return(d); if(limbCount) { do d = limbList[--limbCount]; while(!d && limbCount); } else if(otherCount) { do d = -otherList[--otherCount]; while(!d && otherCount); } return(d); } cmp: (other: number | BigFloat32) => number; isZero() { return(this.len == 0); } getSign() { return(this.len && this.sign); } /** Return an arbitrary number with sign matching the result of this - other. */ deltaFrom(other: number | BigFloat32) { if(typeof(other) == 'number') { other = temp32.setNumber(other); } return( // Make positive and negative zero equal. this.len + other.len && ( // Compare signs. this.sign - other.sign || // Finally compare full values. this.absDeltaFrom(other) * this.sign ) ); } private addBig(addend: BigFloat32, sum: BigFloat32) { let augend: BigFloat32 = this; let fractionLen = augend.fractionLen; let len = fractionLen - addend.fractionLen; if(len < 0) { len = -len; fractionLen += len; augend = addend; addend = this; } sum.sign = this.sign; sum.fractionLen = fractionLen; let sumLimbs = sum.limbList; let augendLimbs = augend.limbList; let addendLimbs = addend.limbList; let posAugend = 0; let posAddend = 0; let carry = 0; let limbSum: number; // If one input has more fractional limbs, just copy the leftovers to output. while(posAugend < len) { sumLimbs[posAugend] = augendLimbs[posAugend]; ++posAugend; } let lenAddend = addend.len; len = augend.len - posAugend; if(len > lenAddend) len = lenAddend; // Calculate sum where input numbers overlap. while(posAddend < len) { carry += augendLimbs[posAugend] + addendLimbs[posAddend++]; limbSum = carry >>> 0; carry = carry - limbSum && 1; sumLimbs[posAugend++] = limbSum; } let posSum = posAugend; if(len < lenAddend) { len = lenAddend; augend = addend; posAugend = posAddend; augendLimbs = addendLimbs; } else len = augend.len; // Copy leftover most significant limbs to output, propagating carry. while(posAugend < len) { carry += augendLimbs[posAugend++]; limbSum = carry >>> 0; carry = carry - limbSum && 1; sumLimbs[posSum++] = limbSum; } if(carry) sumLimbs[posSum++] = carry; sum.len = posSum; sum.trimLeast(); return(sum); } private subBig(subtrahend: BigFloat32, difference: BigFloat32) { let minuend: BigFloat32 = this; difference.sign = this.sign; // Make sure the subtrahend is the smaller number. if(minuend.absDeltaFrom(subtrahend) < 0) { minuend = subtrahend; subtrahend = this; difference.sign = -this.sign as (-1 | 1); } let fractionLen = minuend.fractionLen; let len = fractionLen - subtrahend.fractionLen; let differenceLimbs = difference.limbList; let minuendLimbs = minuend.limbList; let subtrahendLimbs = subtrahend.limbList; let lenMinuend = minuend.len; let lenSubtrahend = subtrahend.len; let lenFinal = lenMinuend; let posMinuend = 0; let posSubtrahend = 0; let posDifference = 0; let carry = 0; let limbDiff: number; if(len >= 0) { while(posMinuend < len) { differenceLimbs[posMinuend] = minuendLimbs[posMinuend]; ++posMinuend; } len += lenSubtrahend; if(len > lenMinuend) len = lenMinuend; posDifference = posMinuend; } else { len = -len; fractionLen += len; lenFinal += len; while(posSubtrahend < len) { carry -= subtrahendLimbs[posSubtrahend]; limbDiff = carry >>> 0; carry = -(carry < 0); differenceLimbs[posSubtrahend++] = limbDiff; } len += lenMinuend; if(len > lenSubtrahend) len = lenSubtrahend; posDifference = posSubtrahend; } difference.fractionLen = fractionLen; // Calculate difference where input numbers overlap. while(posDifference < len) { carry += minuendLimbs[posMinuend++] - subtrahendLimbs[posSubtrahend++]; limbDiff = carry >>> 0; carry = -(carry < 0); differenceLimbs[posDifference++] = limbDiff; } // Copy leftover most significant limbs to output, propagating carry. while(posDifference < lenFinal) { carry += minuendLimbs[posMinuend++]; limbDiff = carry >>> 0; carry = -(carry < 0); differenceLimbs[posDifference++] = limbDiff; } difference.len = posDifference; difference.trimMost(); difference.trimLeast(); return(difference); } private addSub(addend: number | BigFloat32, sign: -1 | 1, result?: BigFloat32) { result = result || new BigFloat32(); if(result == this) throw(new Error('Addition and subtraction in place is unsupported')); if(typeof(addend) == 'number') { addend = temp32.setNumber(addend); } if(this.sign * addend.sign * sign < 0) { return(this.subBig(addend, result)); } else { return(this.addBig(addend, result)); } } /** Add and return sum in a new BigFloat32. */ add(addend: number | BigFloat32, sum?: BigFloat32) { return(this.addSub(addend, 1, sum)); } /** Subtract and return difference in a new BigFloat32. */ sub(subtrahend: number | BigFloat32, difference?: BigFloat32) { return(this.addSub(subtrahend, -1, difference)); } /** Round towards zero, to given number of base 2^32 fractional digits. */ truncate(fractionLimbCount: number) { const diff = this.fractionLen - fractionLimbCount; if(diff > 0) { this.fractionLen = fractionLimbCount; this.len -= diff; const len = this.len; const limbList = this.limbList; for(let pos = 0; pos < len; ++pos) { limbList[pos] = limbList[pos + diff]; } } return(this); } round(decimalCount: number) { return(this.truncate(1 + ~~(decimalCount * limbsPerDigit32))); } /** Divide by integer, replacing current value by quotient. Return integer remainder. */ private divInt(divisor: number, pos: number) { let limbList = this.limbList; let limb: number; let hi: number, lo: number; let carry = 0; // If most significant limb is zero after dividing, decrement number of limbs remaining. if(limbList[pos - 1] < divisor) { carry = limbList[--pos]; this.len = pos; } while(pos--) { limb = limbList[pos]; carry = carry * 0x10000 + (limb >>> 16); hi = (carry / divisor) >>> 0; carry = carry - hi * divisor; carry = carry * 0x10000 + (limb & 0xffff); lo = (carry / divisor) >>> 0; carry = carry - lo * divisor; limbList[pos] = ((hi << 16) | lo) >>> 0; } return(carry); } private fractionToString(base: number, digitList: string[]) { const { pad, limbBase } = BaseInfo32.init(base); let limbList = this.limbList; let limbCount = this.fractionLen; let limbNum = 0; let limbStr: string; if(base & 1) { throw(new Error('Conversion of floating point values to odd bases is unsupported')); } // Skip least significant limbs that equal zero. while(limbNum < limbCount && !limbList[limbNum]) ++limbNum; if(limbNum >= limbCount) return; digitList.push('.'); const fPart = temp32; fPart.limbList = limbList.slice(limbNum, limbCount); fPart.len = limbCount - limbNum; limbNum = 0; while(limbNum < fPart.len) { if(fPart.limbList[limbNum]) { let carry = fPart.mulInt(limbBase, fPart.limbList, limbNum, limbNum, 0); limbStr = carry.toString(base); digitList.push(pad.substr(limbStr.length) + limbStr); } else ++limbNum; } } getExpansion(output: number[]) { const limbList = this.limbList; const len = this.len; let exp = this.sign; let pos = this.fractionLen; while(pos--) { exp *= limbInv32; } while(++pos < len) { output[pos] = limbList[pos] * exp; exp *= limbSize32; } return(len); } valueOf() { const limbList = this.limbList; let result = 0; let exp = limbInv32 * this.sign; let len = this.fractionLen; let pos = 0; while(pos < len) { result = result * limbInv32 + limbList[pos++]; } len = this.len; while(pos < len) { result = result * limbInv32 + limbList[pos++]; exp *= limbSize32; } return(result * exp); } /** Convert to string in any even base supported by Number.toString. * @return String in lower case. */ toString(base: number = 10) { const { pad, limbBase } = BaseInfo32.init(base); let digitList: string[] = []; let limbList = this.limbList; let limb: number; let limbStr: string; if(limbBase != limbSize32) { let iPart = temp32; iPart.limbList = limbList.slice(this.fractionLen, this.len); iPart.len = this.len - this.fractionLen; // Loop while 2 or more limbs remain, requiring arbitrary precision division to extract digits. while(iPart.len > 1) { limbStr = iPart.divInt(limbBase, iPart.len).toString(base); // Prepend digits into final result, padded with zeroes to 9 digits. // Since more limbs still remain, whole result will not have extra padding. digitList.push(pad.substr(limbStr.length) + limbStr); } // Prepend last remaining limb and sign to result. digitList.push('' + (iPart.limbList[0] || 0)); if(this.sign < 0) digitList.push('-'); digitList.reverse(); // Handle fractional part. this.fractionToString(base, digitList); } else { let limbNum = this.len; const fractionPos = this.fractionLen; if(this.sign < 0) digitList.push('-'); if(limbNum == fractionPos) digitList.push('0'); while(limbNum--) { limbStr = limbList[limbNum].toString(base); if(limbNum == fractionPos - 1) digitList.push('.'); digitList.push(pad.substr(limbStr.length) + limbStr); } } // Remove leading and trailing zeroes. return(trimNumber(digitList.join(''))); } private sign: -1 | 1; /** List of digits in base 2^32, least significant first. */ private limbList: number[] = []; /** Number of limbs belonging to fractional part. */ private fractionLen: number; private len: number; } BigFloat32.prototype.cmp = BigFloat32.prototype.deltaFrom; const temp32 = new BigFloat32();
the_stack
import TimePixelConversion from './TimePixelConversion' describe('TimePixelConversion', () => { describe('#frameToPixel', () => { // formula: // framePerPixel = pixelPerSec / framerate // pixel = inputFrame * framePerPixel * scale it('Should returns correct value: 0', () => { const actual1 = TimePixelConversion.framesToPixel({ durationFrames: 0, framerate: 30, pxPerSec: 30, scale: 1, }) const actual2 = TimePixelConversion.framesToPixel({ durationFrames: 0, framerate: 60, pxPerSec: 30, scale: 1, }) const actual3 = TimePixelConversion.framesToPixel({ durationFrames: 0, framerate: 30, pxPerSec: 30, scale: 2, }) expect(actual1).toBe(0) expect(actual2).toBe(0) expect(actual3).toBe(0) }) it('Should returns correc value with `durationFrames', () => { const actual1 = TimePixelConversion.framesToPixel({ durationFrames: 20, framerate: 30, pxPerSec: 30, scale: 1, }) const actual2 = TimePixelConversion.framesToPixel({ durationFrames: -20, framerate: 60, pxPerSec: 30, scale: 1, }) // frame * (pixelPerSec / framerate) * scale expect(actual1).toBe(20 * (30 / 30) * 1) expect(actual2).toBe(-(20 * (30 / 60) * 1)) }) it('Should returns correc value with `framerate`', () => { const actual = TimePixelConversion.framesToPixel({ durationFrames: 1, framerate: 60, pxPerSec: 30, scale: 1, }) // frame * (pixelPerSec / framerate) * scale expect(actual).toBe(1 * (30 / 60) * 1) }) it('Should returns correc value with `pxPerSec`', () => { const actual = TimePixelConversion.framesToPixel({ durationFrames: 1, framerate: 30, pxPerSec: 40, scale: 1, }) // frame * (pixelPerSec / framerate) * scale expect(actual).toBe(1 * (40 / 30) * 1) }) it('Should returns correc value with `scale`', () => { const actual = TimePixelConversion.framesToPixel({ durationFrames: 1, framerate: 30, pxPerSec: 30, scale: 2, }) // frame * (pixelPerSec / framerate) * scale expect(actual).toBe(1 * (30 / 30) * 2) }) it('Should returns correc value with complex params', () => { const actual = TimePixelConversion.framesToPixel({ durationFrames: 45, framerate: 60, pxPerSec: 42, scale: 2.4, }) // frame * (pixelPerSec / framerate) * scale expect(actual).toBe(45 * (42 / 60) * 2.4) }) }) describe('#pixelToFrames', () => { // formula: // framePerPixel = pixelPerSec / framerate // frame = (inputPixel / scale) * framePerPixel it('Should returns correct value: 0', () => { const actual1 = TimePixelConversion.pixelToFrames({ pixel: 0, framerate: 30, pxPerSec: 30, scale: 1, }) const actual2 = TimePixelConversion.pixelToFrames({ pixel: 0, framerate: 60, pxPerSec: 30, scale: 1, }) const actual3 = TimePixelConversion.pixelToFrames({ pixel: 0, framerate: 30, pxPerSec: 30, scale: 2, }) expect(actual1).toBe(0) expect(actual2).toBe(0) expect(actual3).toBe(0) }) it('Should returns correct value with `pixels', () => { const actual = TimePixelConversion.pixelToFrames({ pixel: 20, framerate: 30, pxPerSec: 30, scale: 1, }) // (pixel / scale) * (pixelPerSec / framerate) expect(actual).toBe(Math.round((20 / 1) * (30 / 30))) }) it('Should returns correct value with `framerate`', () => { const actual = TimePixelConversion.pixelToFrames({ pixel: 1, framerate: 60, pxPerSec: 30, scale: 1, }) // (pixel / scale) * (pixelPerSec / framerate) expect(actual).toBe(Math.round((1 / 1) * (30 / 60))) }) it('Should returns correct value with `pxPerSec`', () => { const actual = TimePixelConversion.pixelToFrames({ pixel: 1, framerate: 30, pxPerSec: 45, scale: 1, }) // (pixel / scale) * (pixelPerSec / framerate) expect(actual).toBe(Math.round((1 / 1) * (45 / 30))) }) it('Should returns correct value with `scale`', () => { const actual = TimePixelConversion.pixelToFrames({ pixel: 1, framerate: 30, pxPerSec: 35, scale: 2, }) // (pixel / scale) * (pixelPerSec / framerate) expect(actual).toBe(Math.round((1 / 2) * (35 / 30))) }) it('Should returns correct value with complex params', () => { const actual = TimePixelConversion.pixelToFrames({ pixel: 13, framerate: 60, pxPerSec: 45, scale: 2.2, }) // (pixel / scale) * (pixelPerSec / framerate) expect(actual).toBe(Math.round((13 / 2.2) * (45 / 60))) }) it('Should returns integer (not float)', () => { // There is no concept of decimal in the number of frames const actual = TimePixelConversion.pixelToFrames({ pixel: 13, framerate: 60, pxPerSec: 45, scale: 2.2, }) expect(actual).toBe(actual | 0) }) }) describe('#secondsToPx', () => { // formula: // secondsPerPixel = pixelPerSecond / framePerSecond // pixel = secondPerPixel * inputSeconds * scale it('Should returns correct value: 0', () => { const actual1 = TimePixelConversion.secondsToPx({ seconds: 0, framerate: 30, pxPerSec: 30, scale: 1, }) const actual2 = TimePixelConversion.secondsToPx({ seconds: 0, framerate: 60, pxPerSec: 30, scale: 1, }) const actual3 = TimePixelConversion.secondsToPx({ seconds: 0, framerate: 30, pxPerSec: 60, scale: 1, }) const actual4 = TimePixelConversion.secondsToPx({ seconds: 0, framerate: 30, pxPerSec: 30, scale: 2, }) expect(actual1).toBe(0) expect(actual2).toBe(0) expect(actual3).toBe(0) expect(actual4).toBe(0) }) it('Should returns correct value with `seconds`', () => { const actual = TimePixelConversion.secondsToPx({ seconds: 20, framerate: 30, pxPerSec: 30, scale: 1, }) // (pps / framerate) * inputSeconds * scale expect(actual).toBe((30 / 30) * 20 * 1) }) it('Should returns correct value with `framerate`', () => { const actual = TimePixelConversion.secondsToPx({ seconds: 1, framerate: 60, pxPerSec: 30, scale: 1, }) // (pps / framerate) * inputSeconds * scale expect(actual).toBe((30 / 60) * 1 * 1) }) it('Should returns correct value with `pxPerSec`', () => { const actual = TimePixelConversion.secondsToPx({ seconds: 1, framerate: 30, pxPerSec: 60, scale: 1, }) // (pps / framerate) * inputSeconds * scale expect(actual).toBe((60 / 30) * 1 * 1) }) it('Should returns correct value with `scale`', () => { const actual = TimePixelConversion.secondsToPx({ seconds: 1, framerate: 30, pxPerSec: 30, scale: 2, }) // (pps / framerate) * inputSeconds * scale expect(actual).toBe((30 / 30) * 1 * 2) }) it('Should returns correct value with complex param', () => { const actual = TimePixelConversion.secondsToPx({ seconds: 45.3, framerate: 60, pxPerSec: 45, scale: 2.3, }) // (pps / framerate) * inputSeconds * scale expect(actual).toBe((45 / 60) * 45.3 * 2.3) }) }) describe('#pxToSeconds', () => { // formula: // pixelPerFrame = framePerSecond / pixelPerSecond // seconds = pixel * pixelPerFrame * scale it('Should returns correct value: 0', () => { const actual1 = TimePixelConversion.pxToSeconds({ pixel: 0, framerate: 30, pxPerSec: 30, scale: 1, }) const actual2 = TimePixelConversion.pxToSeconds({ pixel: 0, framerate: 60, pxPerSec: 30, scale: 1, }) const actual3 = TimePixelConversion.pxToSeconds({ pixel: 0, framerate: 30, pxPerSec: 60, scale: 1, }) const actual4 = TimePixelConversion.pxToSeconds({ pixel: 0, framerate: 30, pxPerSec: 30, scale: 2, }) expect(actual1).toBe(0) expect(actual2).toBe(0) expect(actual3).toBe(0) expect(actual4).toBe(0) }) it('Should returns correct value with `pixel`', () => { const actual = TimePixelConversion.pxToSeconds({ pixel: 14, framerate: 30, pxPerSec: 30, scale: 1, }) // px * (framerate / pps) * scale expect(actual).toBe(14 * (30 / 30) * 1) }) it('Should returns correct value with `framerate`', () => { const actual = TimePixelConversion.pxToSeconds({ pixel: 1, framerate: 60, pxPerSec: 30, scale: 1, }) // px * (framerate / pps) * scale expect(actual).toBe(1 * (60 / 30) * 1) }) it('Should returns correct value with `pxPerSec`', () => { const actual = TimePixelConversion.pxToSeconds({ pixel: 1, framerate: 30, pxPerSec: 60, scale: 1, }) // px * (framerate / pps) * scale expect(actual).toBe(1 * (30 / 60) * 1) }) it('Should returns correct value with `scale`', () => { const actual = TimePixelConversion.pxToSeconds({ pixel: 1, framerate: 30, pxPerSec: 30, scale: 2, }) // px * (framerate / pps) * scale expect(actual).toBe(1 * (30 / 30) * 2) }) it('Should returns correct value with complex param', () => { const actual = TimePixelConversion.pxToSeconds({ pixel: 132, framerate: 60, pxPerSec: 45, scale: 3.5, }) // px * (framerate / pps) * scale expect(actual).toBe(132 * (60 / 45) * 3.5) }) }) describe('#buildMeasures', () => { it('Should works without any Error', () => { TimePixelConversion.buildMeasures({ durationFrames: 1000, framerate: 60, maxMeasures: 100, placeIntervalWidth: 30, pxPerSec: 30, scale: 1, }) }) }) })
the_stack
import '@tamagui/polyfill-dev' import { useDismiss, useFloating, useFocus, useInteractions, useRole, } from '@floating-ui/react-dom-interactions' import { AnimatePresence } from '@tamagui/animate-presence' import { useComposedRefs } from '@tamagui/compose-refs' import { Theme, composeEventHandlers, useId, useThemeName, withStaticProperties, } from '@tamagui/core' import type { Scope } from '@tamagui/create-context' import { createContextScope } from '@tamagui/create-context' // import { DismissableLayer } from '@tamagui/react-dismissable-layer' // import { useFocusGuards } from '@tamagui/react-focus-guards' // import { FocusScope } from '@tamagui/react-focus-scope' import { FloatingOverrideContext, Popper, PopperAnchor, PopperArrow, PopperContent, PopperContentProps, PopperProps, UseFloatingFn, createPopperScope, } from '@tamagui/popper' import { Portal } from '@tamagui/portal' import { YStack, YStackProps } from '@tamagui/stacks' import { useControllableState } from '@tamagui/use-controllable-state' // import { hideOthers } from 'aria-hidden' import * as React from 'react' import { GestureResponderEvent, View } from 'react-native' // import { RemoveScroll } from 'react-remove-scroll' const POPOVER_NAME = 'Popover' type ScopedProps<P> = P & { __scopePopover?: Scope } const [createPopoverContext, createPopoverScopeInternal] = createContextScope(POPOVER_NAME, [ createPopperScope, ]) export const usePopoverScope = createPopperScope() export const createPopoverScope = createPopoverScopeInternal type PopoverContextValue = { triggerRef: React.RefObject<HTMLButtonElement> contentId?: string open: boolean onOpenChange(open: boolean): void onOpenToggle(): void hasCustomAnchor: boolean onCustomAnchorAdd(): void onCustomAnchorRemove(): void modal: boolean } const [PopoverProviderInternal, usePopoverInternalContext] = createPopoverContext<PopoverContextValue>(POPOVER_NAME) export const __PopoverProviderInternal = PopoverProviderInternal /* ------------------------------------------------------------------------------------------------- * PopoverAnchor * -----------------------------------------------------------------------------------------------*/ const ANCHOR_NAME = 'PopoverAnchor' type PopoverAnchorElement = HTMLElement | View export type PopoverAnchorProps = YStackProps export const PopoverAnchor = React.forwardRef<PopoverAnchorElement, PopoverAnchorProps>( (props: ScopedProps<PopoverAnchorProps>, forwardedRef) => { const { __scopePopover, ...anchorProps } = props const context = usePopoverInternalContext(ANCHOR_NAME, __scopePopover) const popperScope = usePopoverScope(__scopePopover) const { onCustomAnchorAdd, onCustomAnchorRemove } = context React.useEffect(() => { onCustomAnchorAdd() return () => onCustomAnchorRemove() }, [onCustomAnchorAdd, onCustomAnchorRemove]) return <PopperAnchor {...popperScope} {...anchorProps} ref={forwardedRef} /> } ) PopoverAnchor.displayName = ANCHOR_NAME /* ------------------------------------------------------------------------------------------------- * PopoverTrigger * -----------------------------------------------------------------------------------------------*/ const TRIGGER_NAME = 'PopoverTrigger' type PopoverTriggerElement = HTMLElement | View export type PopoverTriggerProps = YStackProps export const PopoverTrigger = React.forwardRef<PopoverTriggerElement, PopoverTriggerProps>( (props: ScopedProps<PopoverTriggerProps>, forwardedRef) => { const { __scopePopover, ...triggerProps } = props const context = usePopoverInternalContext(TRIGGER_NAME, __scopePopover) const popperScope = usePopoverScope(__scopePopover) const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef) const trigger = ( <YStack aria-haspopup="dialog" aria-expanded={context.open} aria-controls={context.contentId} data-state={getState(context.open)} {...triggerProps} ref={composedTriggerRef} onPress={composeEventHandlers(props.onPress, context.onOpenToggle)} /> ) return context.hasCustomAnchor ? ( trigger ) : ( <PopperAnchor asChild {...popperScope}> {trigger} </PopperAnchor> ) } ) PopoverTrigger.displayName = TRIGGER_NAME /* ------------------------------------------------------------------------------------------------- * PopoverContent * -----------------------------------------------------------------------------------------------*/ const CONTENT_NAME = 'PopoverContent' export interface PopoverContentTypeProps extends Omit<PopoverContentImplProps, 'trapFocus' | 'disableOutsidePointerEvents'> { /** * @see https://github.com/theKashey/react-remove-scroll#usage */ allowPinchZoom?: RemoveScrollProps['allowPinchZoom'] } export type PopoverContentProps = PopoverContentTypeProps export const PopoverContent = React.forwardRef<PopoverContentTypeElement, PopoverContentProps>( (props: ScopedProps<PopoverContentProps>, forwardedRef) => { const context = usePopoverInternalContext(CONTENT_NAME, props.__scopePopover) return context.modal ? ( <PopoverContentModal {...props} ref={forwardedRef} /> ) : ( <PopoverContentNonModal {...props} ref={forwardedRef} /> ) } ) PopoverContent.displayName = CONTENT_NAME /* -----------------------------------------------------------------------------------------------*/ type RemoveScrollProps = any //React.ComponentProps<typeof RemoveScroll> type PopoverContentTypeElement = PopoverContentImplElement const PopoverContentModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>( (props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => { const { allowPinchZoom, ...contentModalProps } = props const context = usePopoverInternalContext(CONTENT_NAME, props.__scopePopover) const contentRef = React.useRef<HTMLDivElement>(null) const composedRefs = useComposedRefs(forwardedRef, contentRef) const isRightClickOutsideRef = React.useRef(false) const themeName = useThemeName() // aria-hide everything except the content (better supported equivalent to setting aria-modal) // React.useEffect(() => { // const content = contentRef.current // if (content) return hideOthers(content) // }, []) const PortalWrapper = context.modal ? Portal : React.Fragment return ( <PortalWrapper> <Theme name={themeName}> {/* <RemoveScroll allowPinchZoom={allowPinchZoom}> */} <PopoverContentImpl {...contentModalProps} ref={composedRefs} // we make sure we're not trapping once it's been closed // (closed !== unmounted when animating out) trapFocus={context.open} disableOutsidePointerEvents onCloseAutoFocus={composeEventHandlers(props.onCloseAutoFocus, (event) => { event.preventDefault() if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus() })} onPointerDownOutside={composeEventHandlers( props.onPointerDownOutside, (event) => { // @ts-expect-error const originalEvent = event.detail.originalEvent const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true const isRightClick = originalEvent.button === 2 || ctrlLeftClick isRightClickOutsideRef.current = isRightClick }, { checkDefaultPrevented: false } )} // When focus is trapped, a `focusout` event may still happen. // We make sure we don't trigger our `onDismiss` in such case. onFocusOutside={composeEventHandlers( props.onFocusOutside, (event) => event.preventDefault(), { checkDefaultPrevented: false } )} /> </Theme> {/* </RemoveScroll> */} </PortalWrapper> ) } ) const PopoverContentNonModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>( (props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => { const { ...contentNonModalProps } = props const context = usePopoverInternalContext(CONTENT_NAME, props.__scopePopover) const hasInteractedOutsideRef = React.useRef(false) const PortalWrapper = context.modal ? Portal : React.Fragment return ( <PortalWrapper> <PopoverContentImpl {...contentNonModalProps} ref={forwardedRef} trapFocus={false} disableOutsidePointerEvents={false} onCloseAutoFocus={(event) => { props.onCloseAutoFocus?.(event) if (!event.defaultPrevented) { if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus() // Always prevent auto focus because we either focus manually or want user agent focus event.preventDefault() } hasInteractedOutsideRef.current = false }} onInteractOutside={(event) => { props.onInteractOutside?.(event) if (!event.defaultPrevented) hasInteractedOutsideRef.current = true // Prevent dismissing when clicking the trigger. // As the trigger is already setup to close, without doing so would // cause it to close and immediately open. // // We use `onInteractOutside` as some browsers also // focus on pointer down, creating the same issue. // @ts-ignore const target = event.target as HTMLElement const targetIsTrigger = context.triggerRef.current?.contains(target) if (targetIsTrigger) event.preventDefault() }} /> </PortalWrapper> ) } ) /* -----------------------------------------------------------------------------------------------*/ type PopoverContentImplElement = React.ElementRef<typeof PopperContent> // TODO type FocusScopeProps = { /** * Whether focus should be trapped within the FocusScope * (default: false) */ trapped?: boolean /** * Event handler called when auto-focusing on mount. * Can be prevented. */ onMountAutoFocus?: (event: GestureResponderEvent) => void /** * Event handler called when auto-focusing on unmount. * Can be prevented. */ onUnmountAutoFocus?: (event: GestureResponderEvent) => void } type DismissableLayerProps = { /** * When `true`, hover/focus/click interactions will be disabled on elements outside the `DismissableLayer`. * Users will need to click twice on outside elements to interact with them: * Once to close the `DismissableLayer`, and again to trigger the element. */ disableOutsidePointerEvents?: boolean /** * Event handler called when the escape key is down. * Can be prevented. */ onEscapeKeyDown?: (event: KeyboardEvent) => void /** * Event handler called when the a pointer event happens outside of the `DismissableLayer`. * Can be prevented. */ onPointerDownOutside?: (event: GestureResponderEvent) => void // onPointerDownOutside?: (event: MouseEvent | TouchEvent) => void /** * Event handler called when the focus moves outside of the `DismissableLayer`. * Can be prevented. */ onFocusOutside?: (event: React.FocusEvent) => void /** * Event handler called when an interaction happens outside the `DismissableLayer`. * Specifically, when a pointer event happens outside of the `DismissableLayer` or focus moves outside of it. * Can be prevented. */ onInteractOutside?: (event: GestureResponderEvent) => void // onInteractOutside?: (event: MouseEvent | TouchEvent | React.FocusEvent) => void /** Callback called when the `DismissableLayer` should be dismissed */ onDismiss?: () => void } export interface PopoverContentImplProps extends PopperContentProps, Omit<DismissableLayerProps, 'onDismiss'> { /** * Whether focus should be trapped within the `Popover` * (default: false) */ trapFocus?: FocusScopeProps['trapped'] /** * Event handler called when auto-focusing on open. * Can be prevented. */ onOpenAutoFocus?: FocusScopeProps['onMountAutoFocus'] /** * Event handler called when auto-focusing on close. * Can be prevented. */ onCloseAutoFocus?: FocusScopeProps['onUnmountAutoFocus'] } const PopoverContentImpl = React.forwardRef<PopoverContentImplElement, PopoverContentImplProps>( (props: ScopedProps<PopoverContentImplProps>, forwardedRef) => { const { __scopePopover, trapFocus, onOpenAutoFocus, onCloseAutoFocus, disableOutsidePointerEvents, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, ...contentProps } = props const context = usePopoverInternalContext(CONTENT_NAME, __scopePopover) const popperScope = usePopoverScope(__scopePopover) // Make sure the whole tree has focus guards as our `Popover` may be // the last element in the DOM (beacuse of the `Portal`) // useFocusGuards() // <FocusScope // asChild // loop // trapped={trapFocus} // onMountAutoFocus={onOpenAutoFocus} // onUnmountAutoFocus={onCloseAutoFocus} // > // <DismissableLayer // asChild // disableOutsidePointerEvents={disableOutsidePointerEvents} // onInteractOutside={onInteractOutside} // onEscapeKeyDown={onEscapeKeyDown} // onPointerDownOutside={onPointerDownOutside} // onFocusOutside={onFocusOutside} // onDismiss={() => context.onOpenChange(false)} // > return ( <AnimatePresence> {!!context.open && ( <PopperContent data-state={getState(context.open)} // role="dialog" id={context.contentId} pointerEvents="auto" {...popperScope} {...contentProps} ref={forwardedRef} /> )} </AnimatePresence> ) // </DismissableLayer> // </FocusScope> } ) /* ------------------------------------------------------------------------------------------------- * PopoverClose * -----------------------------------------------------------------------------------------------*/ const CLOSE_NAME = 'PopoverClose' type PopoverCloseElement = HTMLElement | View export type PopoverCloseProps = YStackProps export const PopoverClose = React.forwardRef<PopoverCloseElement, PopoverCloseProps>( (props: ScopedProps<PopoverCloseProps>, forwardedRef) => { const { __scopePopover, ...closeProps } = props const context = usePopoverInternalContext(CLOSE_NAME, __scopePopover) return ( <YStack {...closeProps} ref={forwardedRef} onPress={composeEventHandlers(props.onPress, () => context.onOpenChange(false))} /> ) } ) PopoverClose.displayName = CLOSE_NAME /* ------------------------------------------------------------------------------------------------- * PopoverArrow * -----------------------------------------------------------------------------------------------*/ const ARROW_NAME = 'PopoverArrow' type PopoverArrowElement = HTMLElement | View export type PopoverArrowProps = YStackProps export const PopoverArrow = React.forwardRef<PopoverArrowElement, PopoverArrowProps>( (props: ScopedProps<PopoverArrowProps>, forwardedRef) => { const { __scopePopover, ...arrowProps } = props const popperScope = usePopoverScope(__scopePopover) return <PopperArrow {...popperScope} {...arrowProps} ref={forwardedRef} /> } ) PopoverArrow.displayName = ARROW_NAME /* ------------------------------------------------------------------------------------------------- * Popover * -----------------------------------------------------------------------------------------------*/ export type PopoverProps = PopperProps & { open?: boolean defaultOpen?: boolean onOpenChange?: (open: boolean) => void modal?: boolean } export const Popover = withStaticProperties( ((props: ScopedProps<PopoverProps>) => { const { __scopePopover, children, open: openProp, defaultOpen, onOpenChange, modal = true, ...restProps } = props const popperScope = usePopoverScope(__scopePopover) const triggerRef = React.useRef<HTMLButtonElement>(null) const [hasCustomAnchor, setHasCustomAnchor] = React.useState(false) const [open, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen || false, onChange: onOpenChange, }) const useFloatingFn: UseFloatingFn = (props) => { const floating = useFloating({ ...props, open, onOpenChange: setOpen, }) const { getReferenceProps, getFloatingProps } = useInteractions([ useFocus(floating.context), useRole(floating.context, { role: 'dialog' }), useDismiss(floating.context), ]) return { ...floating, getReferenceProps, getFloatingProps, } as any } const useFloatingContext = React.useCallback(useFloatingFn, [open]) return ( <FloatingOverrideContext.Provider value={useFloatingContext}> <Popper {...popperScope} {...restProps}> <PopoverProviderInternal scope={__scopePopover} contentId={useId()} triggerRef={triggerRef} open={open} onOpenChange={setOpen} onOpenToggle={React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen])} hasCustomAnchor={hasCustomAnchor} onCustomAnchorAdd={React.useCallback(() => setHasCustomAnchor(true), [])} onCustomAnchorRemove={React.useCallback(() => setHasCustomAnchor(false), [])} modal={modal} > {children} </PopoverProviderInternal> </Popper> </FloatingOverrideContext.Provider> ) }) as React.FC<PopoverProps>, { Anchor: PopoverAnchor, Arrow: PopoverArrow, Trigger: PopoverTrigger, Content: PopoverContent, Close: PopoverClose, } ) Popover.displayName = POPOVER_NAME /* -----------------------------------------------------------------------------------------------*/ function getState(open: boolean) { return open ? 'open' : 'closed' }
the_stack
import { ResponseMessage } from "../server/ws_api"; import { BroadcasterDatabase } from "./broadcaster_database"; import { BrowserAPI } from "./browser"; import { Content } from "./content"; import { EventDispatcher, EventQueue } from "./event_queue"; import { BML } from "./interface/DOM"; import { Interpreter } from "./interpreter/interpreter"; import { JSInterpreter } from "./interpreter/js_interpreter"; import { NVRAM } from "./nvram"; import { Resources } from "./resource"; // @ts-ignore import defaultCSS from "../public/default.css"; export interface AudioNodeProvider { getAudioDestinationNode(): AudioNode; } class DefaultAudioNodeProvider implements AudioNodeProvider { getAudioDestinationNode(): AudioNode { return new AudioContext().destination; } } export interface Indicator { // arib-dc://<..>/以降 setUrl(name: string, loading: boolean): void; // テレビの下の方に出てくるデータ受信中...の表示 setReceivingStatus(receiving: boolean): void; setNetworkingGetStatus(get: boolean): void; setNetworkingPostStatus(post: boolean): void; // 番組名 setEventName(eventName: string | null): void; } export interface EPG { // 指定されたサービスを選局する // true: 成功, false: 失敗, never: ページ遷移などで帰らない tune?(originalNetworkId: number, transportStreamId: number, serviceId: number): boolean | never; // 指定されたサービスを選局して指定されたコンポーネントを表示する tuneToComponent?(originalNetworkId: number, transportStreamId: number, serviceId: number, component: string): boolean | never; } export interface IP { isIPConnected?(): number; getConnectionType?(): number; transmitTextDataOverIP?(uri: string, body: Uint8Array): Promise<{ resultCode: number, statusCode: string, response: Uint8Array }>; get?(uri: string): Promise<{ response?: Uint8Array, headers?: Headers, statusCode?: number }>; confirmIPNetwork?(destination: string, isICMP: boolean, timeoutMillis: number): Promise<{ success: boolean, ipAddress: string | null, responseTimeMillis: number | null } | null>; } export type InputCharacterType = "all" | "number" | "alphabet" | "hankaku" | "zenkaku" | "katakana" | "hiragana"; const hankakuNumber = "0123456789"; const hankakuAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const hankakuSymbol = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; const zenkakuHiragana = "ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわをん"; const zenkakuKatakana = "ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヲン"; const zenkakuNumber = "0123456789"; const zenkakuAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const zenkakuSymbol = " 、。・ー―「」"; export const inputCharacters: Map<InputCharacterType, string> = new Map([ ["number", hankakuNumber], ["alphabet", hankakuAlphabet + hankakuSymbol], ["hankaku", hankakuAlphabet + hankakuNumber + hankakuSymbol], ["zenkaku", zenkakuHiragana + zenkakuKatakana + zenkakuAlphabet + zenkakuNumber + zenkakuSymbol], ["katakana", zenkakuKatakana + zenkakuSymbol], ["hiragana", zenkakuHiragana + zenkakuSymbol], ]); export type InputCancelReason = "other" | "unload" | "readonly" | "blur" | "invisible"; export type InputApplicationLaunchOptions = { // 入力できる文字種 characterType: InputCharacterType, // 入力できる文字 undefinedならば制限はない(ただしデータ放送で扱える範囲の文字のみで半角カタカナなど扱えない文字もある) allowedCharacters?: string, // 最大文字数 maxLength: number, // 以前入力されていた文字 value: string, inputMode: "text" | "password", // 文字入力が完了した際に呼ぶコールバック callback: (value: string) => void, }; /** * TR-B14 第二分冊 1.6 文字入力機能 */ export interface InputApplication { /** * 文字入力アプリケーションを起動 */ launch(options: InputApplicationLaunchOptions): void; /** * 文字入力アプリケーションを終了 * 起動中に文書の遷移、フォーカス移動、readonly属性の設定、invisible属性が有効になった場合など */ cancel(reason: InputCancelReason): void; } export interface Reg { getReg(index: number): string | undefined; setReg(index: number, value: string): void; } interface BMLBrowserEventMap { // 読み込まれたとき "load": CustomEvent<{ resolution: { width: number, height: number }, displayAspectRatio: { numerator: number, denominator: number } }>; // invisibleが設定されているときtrue "invisible": CustomEvent<boolean>; /** * 動画の位置や大きさが変わった際に呼ばれるイベント * invisibleがtrueである場合渡される矩形に関わらず全面に表示する必要がある */ "videochanged": CustomEvent<{ clientRect: { left: number, top: number, right: number, bottom: number }, boundingRect: DOMRect }>; "usedkeylistchanged": CustomEvent<{ usedKeyList: Set<"basic" | "data-button" | "numeric-tuning"> }>; } interface CustomEventTarget<M> { addEventListener<K extends keyof M>(type: K, callback: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void; dispatchEvent<K extends keyof M>(event: M[K]): boolean; removeEventListener<K extends keyof M>(type: K, callback: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void; } export type BMLBrowserEventTarget = CustomEventTarget<BMLBrowserEventMap>; /* STD-B24 第二分冊(2/2) 第二編 付属2 4.4.8 */ export type BMLBrowserFontFace = { source: string | BinaryData, descriptors?: FontFaceDescriptors | undefined }; export type BMLBrowserFonts = { roundGothic?: BMLBrowserFontFace; boldRoundGothic?: BMLBrowserFontFace; squareGothic?: BMLBrowserFontFace; }; export const bmlBrowserFontNames = Object.freeze({ roundGothic: "丸ゴシック", boldRoundGothic: "太丸ゴシック", squareGothic: "角ゴシック", }); export type BMLBrowserOptions = { // 親要素 containerElement: HTMLElement; // 動画の要素 mediaElement: HTMLElement; // 番組名などを表示 indicator?: Indicator; fonts?: BMLBrowserFonts; // localStorageのprefix (default: "") storagePrefix?: string; // nvramのprefix (default: "nvram_") nvramPrefix?: string; // 放送者ID DBのprefix (default: "") broadcasterDatabasePrefix?: string; // フォーカスを受け付けキー入力を受け取る tabIndex?: number; epg?: EPG; /** * 動画像プレーンモードを有効化 * 動画像が配置されている部分が切り抜かれるためvideochangedイベントに合わせて動画を配置する */ videoPlaneModeEnabled?: boolean; audioNodeProvider?: AudioNodeProvider; ip?: IP, inputApplication?: InputApplication; ureg?: Reg; greg?: Reg; }; export class BMLBrowser { private containerElement: HTMLElement; private shadowRoot: ShadowRoot; private documentElement: HTMLElement; private interpreter: Interpreter; public readonly nvram: NVRAM; public readonly browserAPI: BrowserAPI; private mediaElement: HTMLElement; private resources: Resources; private eventQueue: EventQueue; private eventDispatcher: EventDispatcher; public readonly broadcasterDatabase: BroadcasterDatabase; public readonly content: Content; private bmlDomDocument: BML.BMLDocument; private indicator?: Indicator; private eventTarget = new EventTarget() as BMLBrowserEventTarget; private fonts: FontFace[] = []; private readonly epg: EPG; public constructor(options: BMLBrowserOptions) { this.containerElement = options.containerElement; this.mediaElement = options.mediaElement; this.indicator = options.indicator; this.shadowRoot = options.containerElement.attachShadow({ mode: "closed" }); const uaStyle = document.createElement("style"); uaStyle.textContent = defaultCSS; this.shadowRoot.appendChild(uaStyle); this.documentElement = document.createElement("html"); if (options.tabIndex != null) { this.documentElement.tabIndex = options.tabIndex; } this.shadowRoot.appendChild(this.documentElement); this.resources = new Resources(this.indicator, options.ip ?? {}); this.broadcasterDatabase = new BroadcasterDatabase(this.resources); this.broadcasterDatabase.openDatabase(); this.nvram = new NVRAM(this.resources, this.broadcasterDatabase, options.nvramPrefix); this.epg = options.epg ?? {}; this.interpreter = new JSInterpreter(); this.eventQueue = new EventQueue(this.interpreter); const audioContextProvider = options.audioNodeProvider ?? new DefaultAudioNodeProvider(); this.bmlDomDocument = new BML.BMLDocument(this.documentElement, this.interpreter, this.eventQueue, this.resources, this.eventTarget, audioContextProvider, options.inputApplication); this.eventDispatcher = new EventDispatcher(this.eventQueue, this.bmlDomDocument, this.resources); this.content = new Content(this.bmlDomDocument, this.documentElement, this.resources, this.eventQueue, this.eventDispatcher, this.interpreter, this.mediaElement, this.eventTarget, this.indicator, options.videoPlaneModeEnabled ?? false, options.inputApplication); this.browserAPI = new BrowserAPI(this.resources, this.eventQueue, this.eventDispatcher, this.content, this.nvram, this.interpreter, audioContextProvider, options.ip ?? {}, this.indicator, options.ureg, options.greg); this.eventQueue.dispatchBlur = this.eventDispatcher.dispatchBlur.bind(this.eventDispatcher); this.eventQueue.dispatchClick = this.eventDispatcher.dispatchClick.bind(this.eventDispatcher); this.eventQueue.dispatchFocus = this.eventDispatcher.dispatchFocus.bind(this.eventDispatcher); this.eventQueue.dispatchChange = this.eventDispatcher.dispatchChange.bind(this.eventDispatcher); this.interpreter.setupEnvironment(this.browserAPI, this.resources, this.content, this.epg); if (options.fonts?.roundGothic) { this.fonts.push(new FontFace(bmlBrowserFontNames.roundGothic, options.fonts?.roundGothic.source, options.fonts?.roundGothic.descriptors)); } if (options.fonts?.boldRoundGothic) { this.fonts.push(new FontFace(bmlBrowserFontNames.boldRoundGothic, options.fonts?.boldRoundGothic.source, options.fonts?.boldRoundGothic.descriptors)); } if (options.fonts?.squareGothic) { this.fonts.push(new FontFace(bmlBrowserFontNames.squareGothic, options.fonts?.squareGothic.source, options.fonts?.squareGothic.descriptors)); } for (const font of this.fonts) { document.fonts.add(font); } } public emitMessage(msg: ResponseMessage) { if (msg.type === "programInfo") { this.indicator?.setEventName(msg.eventName); } this.resources.onMessage(msg); this.broadcasterDatabase.onMessage(msg); this.browserAPI.onMessage(msg); this.content.onMessage(msg); } public addEventListener<K extends keyof BMLBrowserEventMap>(type: K, callback: (this: undefined, evt: BMLBrowserEventMap[K]) => void, options?: AddEventListenerOptions | boolean) { this.eventTarget.addEventListener(type, callback as EventListener, options); } public removeEventListener<K extends keyof BMLBrowserEventMap>(type: K, callback: (this: undefined, evt: BMLBrowserEventMap[K]) => void, options?: AddEventListenerOptions | boolean) { this.eventTarget.removeEventListener(type, callback as EventListener, options); } public getVideoElement(): HTMLElement | null { return this.documentElement.querySelector("object[arib-type=\"video/X-arib-mpeg2\"]"); } public destroy() { for (const font of this.fonts) { document.fonts.delete(font); } this.fonts.length = 0; this.content.unloadAllDRCS(); } }
the_stack
import * as leaflet from "leaflet"; // Experiment inspired by: // http://bl.ocks.org/Sumbera/c6fed35c377a46ff74c3 // CanvasOverlad from here: // https://github.com/Sumbera/gLayers.Leaflet/blob/master/L.CanvasLayer.js /* Generic Canvas Layer for leaflet 0.7 and 1.0-rc, 1.2, 1.3 copyright Stanislav Sumbera, 2016-2018, sumbera.com , license MIT originally created and motivated by leaflet.CanvasOverlay available here: https://gist.github.com/Sumbera/11114288 also thanks to contributors: heyyeyheman,andern,nikiv3, anyoneelse ? enjoy ! */ // -- L.DomUtil.setTransform from leaflet 1.0.0 to work on 0.0.7 //------------------------------------------------------------------------------ leaflet.DomUtil.setTransform = leaflet.DomUtil.setTransform || function (el, offset, scale) { var pos = offset || new leaflet.Point(0, 0); el.style[leaflet.DomUtil.TRANSFORM as any] = (leaflet.Browser.ie3d ? 'translate(' + pos.x + 'px,' + pos.y + 'px)' : 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') + (scale ? ' scale(' + scale + ')' : ''); }; // -- support for both 0.0.7 and 1.0.0 rc2 leaflet const CanvasLayer = (leaflet.Layer ? leaflet.Layer : leaflet.Class).extend({ // -- initialized is called on prototype initialize: function (options: any) { this._map = null; this._canvas = null; this._frame = null; this._delegate = null; (leaflet as any).setOptions(this, options); }, delegate :function(del: any){ this._delegate = del; return this; }, needRedraw: function () { if (!this._frame) { this._frame = leaflet.Util.requestAnimFrame(this.drawLayer, this); } return this; }, //------------------------------------------------------------- _onLayerDidResize: function (resizeEvent: any) { this._canvas.width = resizeEvent.newSize.x; this._canvas.height = resizeEvent.newSize.y; }, //------------------------------------------------------------- _onLayerDidMove: function () { var topLeft = this._map.containerPointToLayerPoint([0, 0]); leaflet.DomUtil.setPosition(this._canvas, topLeft); this.drawLayer(); }, //------------------------------------------------------------- getEvents: function () { var events = { resize: this._onLayerDidResize, moveend: this._onLayerDidMove, zoom: this._onLayerDidMove }; if (this._map.options.zoomAnimation && leaflet.Browser.any3d) { (events as any).zoomanim = this._animateZoom; } return events; }, //------------------------------------------------------------- onAdd: function (map: any) { this._map = map; this._canvas = leaflet.DomUtil.create('canvas', 'leaflet-layer'); this.tiles = {}; var size = this._map.getSize(); this._canvas.width = size.x; this._canvas.height = size.y; var animated = this._map.options.zoomAnimation && leaflet.Browser.any3d; leaflet.DomUtil.addClass(this._canvas, 'leaflet-zoom-' + (animated ? 'animated' : 'hide')); map._panes.overlayPane.appendChild(this._canvas); map.on(this.getEvents(),this); var del = this._delegate || this; del.onLayerDidMount && del.onLayerDidMount(); // -- callback this.needRedraw(); }, //------------------------------------------------------------- onRemove: function (map: any) { var del = this._delegate || this; del.onLayerWillUnmount && del.onLayerWillUnmount(); // -- callback if (this._frame) { leaflet.Util.cancelAnimFrame(this._frame); } map.getPanes().overlayPane.removeChild(this._canvas); map.off(this.getEvents(),this); this._canvas = null; }, //------------------------------------------------------------ addTo: function (map: any) { map.addLayer(this); return this; }, // -------------------------------------------------------------------------------- LatLonToMercator: function (latlon: any) { return { x: latlon.lng * 6378137 * Math.PI / 180, y: Math.log(Math.tan((90 + latlon.lat) * Math.PI / 360)) * 6378137 }; }, //------------------------------------------------------------------------------ drawLayer: function () { // -- todo make the viewInfo properties flat objects. var size = this._map.getSize(); var bounds = this._map.getBounds(); var zoom = this._map.getZoom(); var center = this.LatLonToMercator(this._map.getCenter()); var corner = this.LatLonToMercator(this._map.containerPointToLatLng(this._map.getSize())); var del = this._delegate || this; del.onDrawLayer && del.onDrawLayer( { layer : this, canvas: this._canvas, bounds: bounds, size: size, zoom: zoom, center : center, corner : corner }); this._frame = null; }, // -- leaflet.DomUtil.setTransform from leaflet 1.0.0 to work on 0.0.7 //------------------------------------------------------------------------------ _setTransform: function (el: any, offset: any, scale: any) { var pos = offset || new leaflet.Point(0, 0); el.style[leaflet.DomUtil.TRANSFORM] = (leaflet.Browser.ie3d ? 'translate(' + pos.x + 'px,' + pos.y + 'px)' : 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') + (scale ? ' scale(' + scale + ')' : ''); }, //------------------------------------------------------------------------------ _animateZoom: function (e: any) { var scale = this._map.getZoomScale(e.zoom); // -- different calc of animation zoom in leaflet 1.0.3 thanks @peterkarabinovic, @jduggan1 var offset = leaflet.Layer ? this._map._latLngBoundsToNewLayerBounds(this._map.getBounds(), e.zoom, e.center).min : this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos()); leaflet.DomUtil.setTransform(this._canvas, offset, scale); } }); const canvasLayer = function () { return new CanvasLayer(); }; // The above seems to be the successor of the original gist: // https://gist.github.com/Sumbera/11114288 // https://gist.github.com/danwild/1ce9fb8891bf187450f882261730b4a8 // But since the API has changed (for the worse), let's stick with the original: const CanvasOverlay = leaflet.Layer.extend({ initialize: function (userDrawFunc: () => void, options: any) { this._userDrawFunc = userDrawFunc; //leaflet.setOptions(this, options); }, drawing: function (userDrawFunc: () => void) { this._userDrawFunc = userDrawFunc; return this; }, params: function(options: any){ //L.setOptions(this, options); return this; }, canvas: function () { return this._canvas; }, redraw: function () { if (!this._frame) { this._frame = leaflet.Util.requestAnimFrame(this._redraw, this); } return this; }, onAdd: function (map: leaflet.Map) { this._map = map; this._canvas = leaflet.DomUtil.create('canvas', 'leaflet-heatmap-layer'); var size = this._map.getSize(); this._canvas.width = size.x; this._canvas.height = size.y; var animated = this._map.options.zoomAnimation && leaflet.Browser.any3d; leaflet.DomUtil.addClass(this._canvas, 'leaflet-zoom-' + (animated ? 'animated' : 'hide')); (map as any)._panes.overlayPane.appendChild(this._canvas); map.on('moveend', this._reset, this); map.on('resize', this._resize, this); if (map.options.zoomAnimation && leaflet.Browser.any3d) { map.on('zoomanim', this._animateZoom, this); } this._reset(); }, onRemove: function (map: leaflet.Map) { map.getPanes().overlayPane.removeChild(this._canvas); map.off('moveend', this._reset, this); map.off('resize', this._resize, this); if (map.options.zoomAnimation) { map.off('zoomanim', this._animateZoom, this); } this._canvas = null; }, addTo: function (map: leaflet.Map) { map.addLayer(this); return this; }, _resize: function (resizeEvent: leaflet.ResizeEvent) { this._canvas.width = resizeEvent.newSize.x; this._canvas.height = resizeEvent.newSize.y; }, _reset: function () { var topLeft = this._map.containerPointToLayerPoint([0, 0]); leaflet.DomUtil.setPosition(this._canvas, topLeft); this._redraw(); }, _redraw: function () { var size = this._map.getSize(); var bounds = this._map.getBounds(); var zoomScale = (size.x * 180) / (20037508.34 * (bounds.getEast() - bounds.getWest())); // resolution = 1/zoomScale var zoom = this._map.getZoom(); // console.time('process'); if (this._userDrawFunc) { this._userDrawFunc(this, { canvas :this._canvas, bounds : bounds, size : size, zoomScale: zoomScale, zoom : zoom, options: this.options }); } // console.timeEnd('process'); this._frame = null; }, /* _animateZoom: function (e: any) { var scale = this._map.getZoomScale(e.zoom), offset = this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos()); this._canvas.style[leaflet.DomUtil.TRANSFORM] = leaflet.DomUtil.getTranslateString(offset) + ' scale(' + scale + ')'; } */ // animateZoom was relying on leaflet.DomUtil.getTranslateString which no longer exists. // replacing by the updated version from the new "CanvasLayer" repo... _animateZoom: function (e: any) { var scale = this._map.getZoomScale(e.zoom); // -- different calc of animation zoom in leaflet 1.0.3 thanks @peterkarabinovic, @jduggan1 var offset = leaflet.Layer ? this._map._latLngBoundsToNewLayerBounds(this._map.getBounds(), e.zoom, e.center).min : this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos()); leaflet.DomUtil.setTransform(this._canvas, offset, scale); } }); const canvasOverlay = function (userDrawFunc?: () => void, options?: any) { return new (CanvasOverlay as any)(userDrawFunc, options); }; let vshader = ` uniform mat4 u_matrix; attribute vec4 a_vertex; attribute float a_pointSize; attribute vec4 a_color; varying vec4 v_color; void main() { // Set the size of the point gl_PointSize = a_pointSize; // multiply each vertex by a matrix. gl_Position = u_matrix * a_vertex; // pass the color to the fragment shader v_color = a_color; }` let fshader = ` precision mediump float; varying vec4 v_color; void main() { float border = 0.05; float radius = 0.5; vec4 color0 = vec4(0.0, 0.0, 0.0, 0.0); vec4 color1 = vec4(v_color[0], v_color[1], v_color[2], 0.2); vec2 m = gl_PointCoord.xy - vec2(0.5, 0.5); float dist = radius - sqrt(m.x * m.x + m.y * m.y); float t = 0.0; if (dist > border) t = 1.0; else if (dist > 0.0) t = dist / border; // float centerDist = length(gl_PointCoord - 0.5); // works for overlapping circles if blending is enabled gl_FragColor = mix(color0, color1, t); }` export function addLayerGL(leafletMap: leaflet.Map, data: number[][]) { var glLayer = canvasOverlay() .drawing(drawingOnCanvas) .addTo(leafletMap); console.log("Adding map layer of size", data.length) console.time("setup_gl") window.performance.mark("setup_gl_mark"); var canvas = glLayer.canvas(); glLayer.canvas.width = canvas.clientWidth; glLayer.canvas.height = canvas.clientHeight; //var gl = canvas.getContext('experimental-webgl', { antialias: true }); var gl = canvas.getContext('webgl', { antialias: true }); var pixelsToWebGLMatrix = new Float32Array(16); var mapMatrix = new Float32Array(16); // -- WebGl setup var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vshader); gl.compileShader(vertexShader); var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fshader); gl.compileShader(fragmentShader); // link shaders to create our program var program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.useProgram(program); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.enable(gl.BLEND); // gl.disable(gl.DEPTH_TEST); // ---------------------------- // look up the locations for the inputs to our shaders. var u_matLoc = gl.getUniformLocation(program, "u_matrix"); var colorLoc = gl.getAttribLocation(program, "a_color"); var vertLoc = gl.getAttribLocation(program, "a_vertex"); gl.aPointSize = gl.getAttribLocation(program, "a_pointSize"); // Set the matrix to some that makes 1 unit 1 pixel. pixelsToWebGLMatrix.set([2 / canvas.width, 0, 0, 0, 0, -2 / canvas.height, 0, 0, 0, 0, 0, 0, -1, 1, 0, 1]); gl.viewport(0, 0, canvas.width, canvas.height); gl.uniformMatrix4fv(u_matLoc, false, pixelsToWebGLMatrix); // -- data var verts = [] as number[]; data.map(function (d, i) { let pixel = LatLongToPixelXY(d[0], d[1]); //-- 2 coord, 3 rgb colors interleaved buffer verts.push(pixel.x, pixel.y, Math.random(), Math.random(), Math.random()); }); var numPoints = data.length ; var vertBuffer = gl.createBuffer(); var vertArray = new Float32Array(verts); var fsize = vertArray.BYTES_PER_ELEMENT; gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertArray, gl.STATIC_DRAW); gl.vertexAttribPointer(vertLoc, 2, gl.FLOAT, false,fsize*5,0); gl.enableVertexAttribArray(vertLoc); // -- offset for color buffer gl.vertexAttribPointer(colorLoc, 3, gl.FLOAT, false, fsize*5, fsize*2); gl.enableVertexAttribArray(colorLoc); glLayer.redraw(); console.timeEnd("setup_gl") window.performance.measure("setup_gl", "setup_gl_mark"); function drawingOnCanvas(canvasOverlay: any, params: any) { if (gl == null) return; gl.clear(gl.COLOR_BUFFER_BIT); pixelsToWebGLMatrix.set([2 / canvas.width, 0, 0, 0, 0, -2 / canvas.height, 0, 0, 0, 0, 0, 0, -1, 1, 0, 1]); gl.viewport(0, 0, canvas.width, canvas.height); var pointSize = Math.max(leafletMap.getZoom() - 4.0, 1.0); gl.vertexAttrib1f(gl.aPointSize, pointSize); // -- set base matrix to translate canvas pixel coordinates -> webgl coordinates mapMatrix.set(pixelsToWebGLMatrix); var bounds = leafletMap.getBounds(); var topLeft = new leaflet.LatLng(bounds.getNorth(), bounds.getWest()); var offset = LatLongToPixelXY(topLeft.lat, topLeft.lng); // -- Scale to current zoom var scale = Math.pow(2, leafletMap.getZoom()); scaleMatrix(mapMatrix, scale, scale); translateMatrix(mapMatrix, -offset.x, -offset.y); // -- attach matrix value to 'mapMatrix' uniform in shader gl.uniformMatrix4fv(u_matLoc, false, mapMatrix); gl.drawArrays(gl.POINTS, 0, numPoints); } // Returns a random integer from 0 to range - 1. function randomInt(range: any) { return Math.floor(Math.random() * range); } /* function latlonToPixels(lat, lon) { initialResolution = 2 * Math.PI * 6378137 / 256, // at zoomlevel 0 originShift = 2 * Math.PI * 6378137 / 2; // -- to meters var mx = lon * originShift / 180; var my = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180); my = my * originShift / 180; // -- to pixels at zoom level 0 var res = initialResolution; x = (mx + originShift) / res, y = (my + originShift) / res; return { x: x, y: 256- y }; } */ // -- converts latlon to pixels at zoom level 0 (for 256x256 tile size) , inverts y coord ) // -- source : http://build-failed.blogspot.cz/2013/02/displaying-webgl-data-on-google-maps.html function LatLongToPixelXY(latitude: number, longitude: number) { var pi_180 = Math.PI / 180.0; var pi_4 = Math.PI * 4; var sinLatitude = Math.sin(latitude * pi_180); var pixelY = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (pi_4)) * 256; var pixelX = ((longitude + 180) / 360) * 256; var pixel = { x: pixelX, y: pixelY }; return pixel; } function translateMatrix(matrix: Float32Array, tx: number, ty: number) { // translation is in last column of matrix matrix[12] += matrix[0] * tx + matrix[4] * ty; matrix[13] += matrix[1] * tx + matrix[5] * ty; matrix[14] += matrix[2] * tx + matrix[6] * ty; matrix[15] += matrix[3] * tx + matrix[7] * ty; } function scaleMatrix(matrix: Float32Array, scaleX: number, scaleY: number) { // scaling x and y, which is just scaling first two columns of matrix matrix[0] *= scaleX; matrix[1] *= scaleX; matrix[2] *= scaleX; matrix[3] *= scaleX; matrix[4] *= scaleY; matrix[5] *= scaleY; matrix[6] *= scaleY; matrix[7] *= scaleY; } }
the_stack
import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { getSupportedInputTypes } from '@angular/cdk/platform'; import { AfterContentInit, Directive, DoCheck, ElementRef, EventEmitter, Inject, Input, OnChanges, OnDestroy, Optional, Self } from '@angular/core'; import { FormControlName, FormGroupDirective, NG_VALIDATORS, NgControl, NgForm, NgModel, Validator } from '@angular/forms'; import { CanUpdateErrorState, CanUpdateErrorStateCtor, ErrorStateMatcher, MC_VALIDATION, McValidationOptions, mixinErrorState, setMosaicValidation } from '@ptsecurity/mosaic/core'; import { McFormFieldControl } from '@ptsecurity/mosaic/form-field'; import { Subject } from 'rxjs'; import { getMcInputUnsupportedTypeError } from './input-errors'; import { McNumberInput } from './input-number'; import { MC_INPUT_VALUE_ACCESSOR } from './input-value-accessor'; const MC_INPUT_INVALID_TYPES = [ 'button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit' ]; let nextUniqueId = 0; export class McInputBase { constructor( public defaultErrorStateMatcher: ErrorStateMatcher, public parentForm: NgForm, public parentFormGroup: FormGroupDirective, public ngControl: NgControl ) {} } // tslint:disable-next-line:naming-convention export const McInputMixinBase: CanUpdateErrorStateCtor & typeof McInputBase = mixinErrorState(McInputBase); @Directive({ selector: `input[mcInput]`, exportAs: 'mcInput', host: { class: 'mc-input', // Native input properties that are overwritten by Angular inputs need to be synced with // the native input element. Otherwise property bindings for those don't work. '[attr.id]': 'id', '[attr.placeholder]': 'placeholder', '[attr.disabled]': 'disabled || null', '[required]': 'required', '(blur)': 'onBlur()', '(focus)': 'focusChanged(true)', '(input)': 'onInput()' }, providers: [{ provide: McFormFieldControl, useExisting: McInput }] }) export class McInput extends McInputMixinBase implements McFormFieldControl<any>, OnChanges, OnDestroy, DoCheck, CanUpdateErrorState, AfterContentInit, OnChanges { /** An object used to control when error messages are shown. */ @Input() errorStateMatcher: ErrorStateMatcher; /** * Implemented as part of McFormFieldControl. * @docs-private */ focused: boolean = false; /** * Implemented as part of McFormFieldControl. * @docs-private */ readonly stateChanges: Subject<void> = new Subject<void>(); /** * Implemented as part of McFormFieldControl. * @docs-private */ controlType: string = 'input'; /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() placeholder: string; protected uid = `mc-input-${nextUniqueId++}`; protected previousNativeValue: any; protected neverEmptyInputTypes = [ 'date', 'datetime', 'datetime-local', 'month', 'time', 'week' ].filter((t) => getSupportedInputTypes().has(t)); /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get disabled(): boolean { if (this.ngControl && this.ngControl.disabled !== null) { return this.ngControl.disabled; } return this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); // Browsers may not fire the blur event if the input is disabled too quickly. // Reset from here to ensure that the element doesn't become stuck. if (this.focused) { this.focused = false; this.stateChanges.next(); } } private _disabled = false; /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get id(): string { return this._id; } set id(value: string) { this._id = value || this.uid; } private _id: string; /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get required(): boolean { return this._required; } set required(value: boolean) { this._required = coerceBooleanProperty(value); } private _required = false; // tslint:disable no-reserved-keywords /** Input type of the element. */ @Input() get type(): string { return this._type; } set type(value: string) { this._type = value || 'text'; this.validateType(); // When using Angular inputs, developers are no longer able to set the properties on the native // input element. To ensure that bindings for `type` work, we need to sync the setter // with the native property. Textarea elements don't support the type property or attribute. if (getSupportedInputTypes().has(this._type)) { this.elementRef.nativeElement.type = this._type; } } // tslint:enable no-reserved-keywords private _type = 'text'; /** * Implemented as part of McFormFieldControl. * @docs-private */ @Input() get value(): string { return this._inputValueAccessor.value; } set value(value: string) { if (value !== this.value) { this._inputValueAccessor.value = value; this.stateChanges.next(); } } // tslint:disable-next-line: orthodox-getter-and-setter private _inputValueAccessor: { value: any }; // tslint:disable-next-line: naming-convention constructor( protected elementRef: ElementRef, @Optional() @Self() @Inject(NG_VALIDATORS) public rawValidators: Validator[], @Optional() @Inject(MC_VALIDATION) private mcValidation: McValidationOptions, @Optional() @Self() ngControl: NgControl, @Optional() @Self() public numberInput: McNumberInput, @Optional() @Self() public ngModel: NgModel, @Optional() @Self() public formControlName: FormControlName, @Optional() parentForm: NgForm, @Optional() parentFormGroup: FormGroupDirective, defaultErrorStateMatcher: ErrorStateMatcher, @Optional() @Self() @Inject(MC_INPUT_VALUE_ACCESSOR) inputValueAccessor: any ) { super(defaultErrorStateMatcher, parentForm, parentFormGroup, ngControl); // If no input value accessor was explicitly specified, use the element as the input value // accessor. this._inputValueAccessor = inputValueAccessor || this.elementRef.nativeElement; this.previousNativeValue = this.value; // Force setter to be called in case id was not specified. this.id = this.id; } ngAfterContentInit(): void { if (!this.ngControl) { return; } if (this.mcValidation.useValidation) { setMosaicValidation(this); } } ngOnChanges() { this.stateChanges.next(); } ngOnDestroy() { this.stateChanges.complete(); } ngDoCheck() { if (this.ngControl) { // We need to re-evaluate this on every change detection cycle, because there are some // error triggers that we can't subscribe to (e.g. parent form submissions). This means // that whatever logic is in here has to be super lean or we risk destroying the performance. this.updateErrorState(); } // We need to dirty-check the native element's value, because there are some cases where // we won't be notified when it changes (e.g. the consumer isn't using forms or they're // updating the value using `emitEvent: false`). this.dirtyCheckNativeValue(); } /** Focuses the input. */ focus(): void { this.elementRef.nativeElement.focus(); } onBlur(): void { this.focusChanged(false); if (this.ngControl && this.ngControl.control) { const control = this.ngControl.control; control.updateValueAndValidity({ emitEvent: false }); (control.statusChanges as EventEmitter<string>).emit(control.status); } } /** Callback for the cases where the focused state of the input changes. */ focusChanged(isFocused: boolean) { if (isFocused !== this.focused) { this.focused = isFocused; this.stateChanges.next(); } } onInput() { // This is a noop function and is used to let Angular know whenever the value changes. // Angular will run a new change detection each time the `input` event has been dispatched. // It's necessary that Angular recognizes the value change, because when floatingLabel // is set to false and Angular forms aren't used, the placeholder won't recognize the // value changes and will not disappear. // Listening to the input event wouldn't be necessary when the input is using the // FormsModule or ReactiveFormsModule, because Angular forms also listens to input events. } /** * Implemented as part of McFormFieldControl. * @docs-private */ get empty(): boolean { return !this.isNeverEmpty() && !this.elementRef.nativeElement.value && !this.isBadInput(); } /** * Implemented as part of McFormFieldControl. * @docs-private */ onContainerClick() { this.focus(); } /** Does some manual dirty checking on the native input `value` property. */ protected dirtyCheckNativeValue() { const newValue = this.value; if (this.previousNativeValue !== newValue) { this.previousNativeValue = newValue; this.stateChanges.next(); } } /** Make sure the input is a supported type. */ protected validateType() { if (MC_INPUT_INVALID_TYPES.indexOf(this._type) > -1) { throw getMcInputUnsupportedTypeError(this._type); } } /** Checks whether the input type is one of the types that are never empty. */ protected isNeverEmpty() { return this.neverEmptyInputTypes.indexOf(this._type) > -1; } /** Checks whether the input is invalid based on the native validation. */ protected isBadInput() { // The `validity` property won't be present on platform-server. const validity = (this.elementRef.nativeElement as HTMLInputElement).validity; return validity && validity.badInput; } } @Directive({ selector: 'input[mcInputMonospace]', exportAs: 'McInputMonospace', host: { class: 'mc-input_monospace' } }) export class McInputMono {}
the_stack
/** * * @module Kiwi * @submodule Geom */ module Kiwi.Geom { /** * Represents a 2d transformation matrix. This can be used to map points * between different coordinate spaces. Matrices are used by Transform * objects to represent translation, scale and rotation transformations, * and to determine where objects are in world space or camera space. * Objects such as entities and groups may be nested, and their associated * transforms may represent how they are scaled, translated and rotated * relative to a parent transform. By concatenating an object's * transformation matrix with its ancestors matrices, it is possible to * determine the absolute position of the object in world space. * See * http://en.wikipedia.org/wiki/Transformation_matrix#Examples_in_2D_graphics * for an in depth discussion of 2d tranformation matrices. * * @class Matrix * @namespace Kiwi.Geom * @constructor * @param [a=1] {Number} position 0,0 of the matrix, * affects scaling and rotation. * @param [b=0] {Number} position 0,1 of the matrix, * affects scaling and rotation. * @param [c=0] {Number} position 1,0 of the matrix, * affects scaling and rotation. * @param [d=1] {Number} position 1,1 of the matrix, * affects scaling and rotation. * @param [tx=0] {Number} position 2,0 of the matrix, * affects translation on x axis. * @param [ty=0] {Number} position 2,1 of the matrix, * affects translation on y axis. * @return (Object) This object. * */ export class Matrix { constructor(a: number = 1, b: number = 0, c: number = 0, d: number = 1, tx: number = 0, ty: number = 0) { this.setTo(a, b, c, d, tx, ty); } /** * The type of object this is. * @method objType * @return {String} "Matrix" * @public */ public objType() { return "Matrix"; } /** * Position 0,0 of the matrix, affects scaling and rotation * @property a * @type Number * @default 1 * @public */ public a: number = 1; /** * Position 0,1 of the matrix, affects scaling and rotation. * @property b * @type Number * @default 0 * @public */ public b: number = 0; /** * Position 1,0 of the matrix, affects scaling and rotation. * @property c * @type Number * @default 0 * @public */ public c: number = 0; /** * Position 1,1 of the matrix, affects scaling and rotation. * @property d * @type Number * @default 1 * @public */ public d: number = 1; /** * Position 2,0 of the matrix, affects translation on x axis. * @property tx * @type Number * @default 0 * @public */ public tx: number = 0; /** * Position 2,1 of the matrix, affects translation on y axis. * @property ty * @type Number * @default 0 * @public */ public ty: number = 0; /** * Set all matrix values * @method setTo * @param [a=1] {Number} position 0,0 of the matrix, affects scaling and rotation. * @param [b=0] {Number} position 0,1 of the matrix, affects scaling and rotation. * @param [c=0] {Number} position 1,0 of the matrix, affects scaling and rotation. * @param [d=1] {Number} position 1,1 of the matrix, affects scaling and rotation. * @param [tx=0] {Number} position 2,0 of the matrix, affects translation on x axis. * @param [ty=0] {Number} position 2,1 of the matrix, affects translation on y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public setTo(a: number = 1, b: number = 0, c: number = 0, d: number = 1, tx: number = 0, ty: number = 0): Matrix { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; return this; } /** * Set matrix values from transform values * @method setFromTransform * @param tx {Number} Translation on x axis. * @param ty {Number} Translation on y axis. * @param scaleX {Number} scaleX. Scale on x axis. * @param scaleY {Number} scaleY. Scale on y axis. * @param rotation {Number} rotation. * @return {Kiwi.Geom.Matrix} This object. * @public */ public setFromTransform(tx: number, ty: number, scaleX: number, scaleY: number, rotation: number) { this.identity(); var cos = Math.cos(rotation); var sin = Math.sin(rotation); this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, tx, ty); return this; } /** * Set matrix values from transform values, with rotation point data included * @method setFromOffsetTransform * @param tx {Number} tx. Translation on x axis. * @param ty {Number} ty. Translation on y axis. * @param scaleX {Number} scaleX. Scale on x axis. * @param scaleY {Number} scaleY. Scale on y axis. * @param rotation {Number} rotation. * @param rotPointX {Number} Rotation point offset on x axis. * @param rotPointY {Number} Rotation point offset on y axis. * @return {Kiwi.Geom.Matrix} This object. * @public * @since 1.0.1 */ public setFromOffsetTransform(tx: number, ty: number, scaleX: number, scaleY: number, rotation: number, rotPointX: number, rotPointY: number) { this.identity(); var cos = Math.cos(rotation); var sin = Math.sin(rotation); this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, tx + rotPointX, ty + rotPointY); return this; } /** * Prepend values to this matrix, paramters supplied individually. * @method prepend * @param [a=1]{Number} position 0,0 of the matrix, affects scaling and rotation. * @param [b=0]{Number} position 0,1 of the matrix, affects scaling and rotation. * @param [c=0]{Number} position 1,0 of the matrix, affects scaling and rotation. * @param [d=0]{Number} position 1,1 of the matrix, affects scaling and rotation. * @param [tx=0]{Number} position 2,0 of the matrix, affects translation on x axis. * @param [ty=0]{Number} position 2,1 of the matrix, affects translation on y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public prepend(a: number = 1, b: number = 0, c: number = 0, d: number = 1, tx: number = 0, ty: number = 0): Matrix { var tx1 = this.tx; var a1 = this.a; var c1 = this.c; this.a = a1 * a + this.b * c; this.b = a1 * b + this.b * d; this.c = c1 * a + this.d * c; this.d = c1 * b + this.d * d; this.tx = tx1 * a + this.ty * c + tx; this.ty = tx1 * b + this.ty * d + ty; return this; } /** * Prepend a matrix to this matrix. * @method prependMatrix * @param m {Kiwi.Geom.Matrix} The matrix to prepend. * @return {Kiwi.Geom.Matrix} This object. * @public */ public prependMatrix(m: Matrix): Matrix { var tx1 = this.tx; var a1 = this.a; var c1 = this.c; this.a = a1 * m.a + this.b * m.c; this.b = a1 * m.b + this.b * m.d; this.c = c1 * m.a + this.d * m.c; this.d = c1 * m.b + this.d * m.d; this.tx = tx1 * m.a + this.ty * m.c + m.tx; this.ty = tx1 * m.b + this.ty * m.d + m.ty; return this; } /** * Append values to this matrix, parameters supplied individually. * @method append * @param [a=1]{Number} position 0,0 of the matrix, affects scaling and rotation. * @param [b=0]{Number} position 0,1 of the matrix, affects scaling and rotation. * @param [c=0]{Number} position 1,0 of the matrix, affects scaling and rotation. * @param [d=1]{Number} position 1,1 of the matrix, affects scaling and rotation. * @param [tx=0]{Number} position 2,0 of the matrix, affects translation on x axis. * @param [ty=0]{Number} position 2,1 of the matrix, affects translation on y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public append(a: number = 1, b: number = 0, c: number = 0, d: number = 1, tx: number = 0, ty: number = 0): Matrix { var a1 = this.a; var b1 = this.b; var c1 = this.c; var d1 = this.d; this.a = a * a1 + b * c1; this.b = a * b1 + b * d1; this.c = c * a1 + d * c1; this.d = c * b1 + d * d1; this.tx = tx * a1 + ty * c1 + this.tx; this.ty = tx * b1 + ty * d1 + this.ty; return this; } /** * Append a matrix to this matrix. * @method appendMatrix * @param m {Kiwi.Geom.Matrix} The matrix to append. * @return {Kiwi.Geom.Matrix} This object. * @public */ public appendMatrix(m: Matrix): Matrix { var a1 = this.a; var b1 = this.b; var c1 = this.c; var d1 = this.d; this.a = m.a * a1 + m.b * c1; this.b = m.a * b1 + m.b * d1; this.c = m.c * a1 + m.d * c1; this.d = m.c * b1 + m.d * d1; this.tx = m.tx * a1 + m.ty * c1 + this.tx; this.ty = m.tx * b1 + m.ty * d1 + this.ty; return this; } /** * Set the tx and ty elements of the matrix. * @method setPosition * @param x {Number} Translation on x axis. * @param y {Number} Translation on y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public setPosition(x: number, y: number): Matrix { this.tx = x; this.ty = y; return this; } /** * Set the tx and ty elements of the matrix from an object with x and y properties. * @method setPositionPoint * @param p {Number} The object from which to copy the x and y properties from. * @return {Kiwi.Geom.Matrix} This object. * @public */ public setPositionPoint(p: any): Matrix { this.tx = p.x; this.ty = p.y; return this } /** * Get the x and y position of the matrix as an object with x and y properties * @method getPosition * @return {Kiwi.Geom.Point} An object constructed from a literal with x and y properties. * @public */ public getPosition(output: Kiwi.Geom.Point = new Kiwi.Geom.Point): Kiwi.Geom.Point { return output.setTo(this.tx, this.ty); } /** * Set the matrix to the identity matrix - when appending or prepending this matrix to another there will be no change in the resulting matrix * @method identity * @return {Kiwi.Geom.Matrix} This object. * @public */ public identity(): Matrix { this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.tx = 0; this.ty = 0; return this; } /** * Rotate the matrix by "radians" degrees * @method rotate * @param radians {Number} The angle (in radians) to rotate this matrix by. * @return {Kiwi.Geom.Matrix} This object. * @public */ public rotate(radians: number): Matrix { var cos = Math.cos(radians); var sin = Math.sin(radians); var a1 = this.a; var c1 = this.c; var tx1 = this.tx; this.a = a1 * cos - this.b * sin; this.b = a1 * sin + this.b * cos; this.c = c1 * cos - this.d * sin; this.d = c1 * sin + this.d * cos; this.tx = tx1 * cos - this.ty * sin; this.ty = tx1 * sin + this.ty * cos; return this; } /** * Translate the matrix by the amount passed. * * @method translate * @param tx {Number} The amount to translate on the x axis. * @param ty {Number} The amount to translate on the y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public translate(tx: number, ty: number): Matrix { this.tx += tx; this.ty += ty; return this; } /** * Scales the matrix by the amount passed. * * @method scale * @param scaleX {Number} The amount to scale on the x axis. * @param scaleY {Number} The amount to scale on the y axis. * @return {Kiwi.Geom.Matrix} This object. * @public */ public scale(scaleX: number, scaleY: number): Matrix { this.a *= scaleX; this.d *= scaleY; return this; } /** * Apply this matrix to a an object with x and y properties representing a point and return the transformed point. * @method transformPoint * @param pt {Object} The point to be translated. * @return {Kiwi.Geom.Matrix} This object. * @public */ public transformPoint(pt: any) { var x = pt.x; var y = pt.y pt.x = this.a * x + this.c * y + this.tx; pt.y = this.b * x + this.d * y + this.ty; return pt; } /** * Invert this matrix so that it represents the opposite of its orginal tranformaation. * @method invert * @return {Kiwi.Geom.Matrix} This object. * @public */ public invert(): Matrix { var a1 = this.a; var b1 = this.b; var c1 = this.c; var d1 = this.d; var tx1 = this.tx; var n = a1 * d1 - b1 * c1; this.a = d1 / n; this.b = -b1 / n; this.c = -c1 / n; this.d = a1 / n; this.tx = (c1 * this.ty - d1 * tx1) / n; this.ty = -(a1 * this.ty - b1 * tx1) / n; return this; } /** * Copy another matrix to this matrix. * @method copyFrom * @param m {Kiwi.Geom.Matrix} The matrixto be copied from. * @return {Kiwi.Geom.Matrix} This object. * @public */ public copyFrom(m: Matrix): Matrix { this.a = m.a; this.b = m.b; this.c = m.c; this.d = m.d; this.tx = m.tx; this.ty = m.ty; return this; } /** * Copy this matrix to another matrix. * @method copyTo * @param m {Kiwi.Geom.Matrix} The matrix to copy to. * @return {Kiwi.Geom.Matrix} This object. * @public */ public copyTo(m: Matrix): Matrix { m.a = this.a; m.b = this.b; m.c = this.c; m.d = this.d; m.tx = this.tx; m.ty = this.ty; return this; } /** * Clone this matrix and returns a new Matrix object. * @method clone * @return {Kiwi.Geom.Matrix} * @public */ public clone(): Matrix { return new Kiwi.Geom.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); } /** * Returns a string representation of this object. * @method toString * @return {string} A string representation of the instance. * @public */ public get toString(): string { return "[{Matrix (a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + ")}]"; } /** * Check whether this matrix equals another matrix. * * @method equals * @param matrix {Kiwi.Geom.Matrix} * @return boolean * @public */ public equals( matrix: Matrix ): boolean { return ( this.a === matrix.a && this.b === matrix.b && this.c === matrix.c && this.d === matrix.d && this.tx === matrix.tx && this.ty === matrix.ty ); } } }
the_stack
* Copyright © 2020 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ import { GenericObject, CompiledSchema, CompiledSchemasArray } from './types'; import { writeSInt32, writeSInt64, writeUInt32, writeUInt64, readUInt32, readSInt32, readSInt64, readUInt64, } from './varint'; import { writeString, readString } from './string'; import { writeBytes, readBytes } from './bytes'; import { writeBoolean, readBoolean } from './boolean'; import { readKey } from './keys'; import { getDefaultValue } from './utils/default_value'; const _readers: { // eslint-disable-next-line @typescript-eslint/no-explicit-any readonly [key: string]: (value: Buffer, offset: number) => any; } = { uint32: readUInt32, sint32: readSInt32, uint64: readUInt64, sint64: readSInt64, string: readString, bytes: readBytes, boolean: readBoolean, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const _writers: { readonly [key: string]: (value: any) => Buffer } = { uint32: writeUInt32, sint32: writeSInt32, uint64: writeUInt64, sint64: writeSInt64, string: writeString, bytes: writeBytes, boolean: writeBoolean, }; export const writeObject = ( compiledSchema: CompiledSchemasArray, message: GenericObject, chunks: Buffer[], ): [Buffer[], number] => { let simpleObjectSize = 0; for (let i = 0; i < compiledSchema.length; i += 1) { const property = compiledSchema[i]; if (Array.isArray(property)) { const headerProp = property[0]; if (headerProp.schemaProp.type === 'array') { // eslint-disable-next-line no-use-before-define const [, size] = writeArray( property, message[headerProp.propertyName] as Array<unknown>, chunks, ); simpleObjectSize += size; continue; } // Write the key for container object chunks.push(headerProp.binaryKey); const [encodedValues, totalWrittenSize] = writeObject( property, message[headerProp.propertyName] as GenericObject, [], ); // Add nested object size to total size const objectSize = _writers.uint32(totalWrittenSize); simpleObjectSize += objectSize.length + headerProp.binaryKey.length; chunks.push(objectSize); for (let e = 0; e < encodedValues.length; e += 1) { simpleObjectSize += encodedValues[e].length; chunks.push(encodedValues[e]); } } else { // This is the header object so it does not need to be written if (property.schemaProp.type === 'object') { continue; } const value = message[property.propertyName]; // Missing properties are not encoded as per LIP-0027 if (value === undefined) { continue; } const { schemaProp: { dataType }, binaryKey, } = property; if (dataType === undefined) { throw new Error('Compiled Schema is corrupted as "dataType" can not be undefined.'); } const binaryValue = _writers[dataType](value); chunks.push(binaryKey); chunks.push(binaryValue); simpleObjectSize += binaryKey.length + binaryValue.length; } } return [chunks, simpleObjectSize]; }; export const readObject = ( message: Buffer, offset: number, compiledSchema: CompiledSchemasArray, terminateIndex: number, ): [GenericObject, number] => { let index = offset; const result: GenericObject = {}; for (let i = 0; i < compiledSchema.length; i += 1) { const typeSchema = compiledSchema[i]; if (Array.isArray(typeSchema)) { // Takeout the root wireType and field number if (typeSchema[0].schemaProp.type === 'array') { if (index >= terminateIndex) { result[typeSchema[0].propertyName] = []; continue; } // eslint-disable-next-line no-use-before-define const [arr, nextOffset] = readArray(message, index, typeSchema, terminateIndex); result[typeSchema[0].propertyName] = arr; index = nextOffset; } else if (typeSchema[0].schemaProp.type === 'object') { // It should be wire type 2 as it's object const [, keySize] = readUInt32(message, index); index += keySize; // Takeout the length const [objectSize, objectSizeLength] = readUInt32(message, index); index += objectSizeLength; const [obj, nextOffset] = readObject(message, index, typeSchema, objectSize + index); result[typeSchema[0].propertyName] = obj; index = nextOffset; } else { throw new Error('Invalid container type'); } continue; } if (typeSchema.schemaProp.type === 'object' || typeSchema.schemaProp.type === 'array') { // typeSchema is header, and we ignore this continue; } if (message.length <= index) { // assign default value result[typeSchema.propertyName] = getDefaultValue(typeSchema.schemaProp.dataType as string); continue; } // Takeout the root wireType and field number const [key, keySize] = readUInt32(message, index); const [fieldNumber] = readKey(key); if (fieldNumber !== typeSchema.schemaProp.fieldNumber) { // assign default value result[typeSchema.propertyName] = getDefaultValue(typeSchema.schemaProp.dataType as string); continue; } // Index is only incremented when the key is actually used index += keySize; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const [scalarValue, scalarSize] = _readers[typeSchema.schemaProp.dataType as string]( message, index, ); index += scalarSize; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment result[typeSchema.propertyName] = scalarValue; } return [result, index]; }; export const readArray = ( message: Buffer, offset: number, compiledSchema: CompiledSchemasArray, terminateIndex: number, // eslint-disable-next-line @typescript-eslint/no-explicit-any ): [Array<any>, number] => { // Takeout the root wireType and field number let index = offset; if (index >= message.length) { return [[], index]; } const startingByte = message[index]; const [rootSchema, typeSchema] = compiledSchema; // Peek the current key, and if not the same fieldnumber, skip const [key] = readUInt32(message, index); const [fieldNumber] = readKey(key); if (fieldNumber !== (rootSchema as CompiledSchema).schemaProp.fieldNumber) { return [[], index]; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const result: Array<any> = []; // Case of object if (Array.isArray(typeSchema)) { // handle as object const [nestedTypeSchema] = typeSchema; if (nestedTypeSchema.schemaProp.type === 'object') { // If still the next bytes is the same key, it is still element of array // Also, in case of object, inside of array, it checks the size of the object while (message[index] === startingByte && index !== terminateIndex) { const [, wire2KeySize] = readUInt32(message, index); index += wire2KeySize; // Takeout the length const [objectSize, objectSizeLength] = readUInt32(message, index); // for object, length is not used index += objectSizeLength; if (objectSize === 0) { continue; } // If array of object, it also gives the terminating index of the particular object const terminatingObjectSize = index + objectSize; // readObject returns Next offset, not index used const [res, nextOffset] = readObject(message, index, typeSchema, terminatingObjectSize); result.push(res); index = nextOffset; } return [result, index]; } throw new Error('Invalid container type'); } // Case for string and bytes if (typeSchema.schemaProp.dataType === 'string' || typeSchema.schemaProp.dataType === 'bytes') { // If still the next bytes is the same key, it is still element of array // Also, in case of object inside of array, it checks the size of the object while (message[index] === startingByte && index !== terminateIndex) { const [, wire2KeySize] = readUInt32(message, index); index += wire2KeySize; // wireType2LengthSize is used while decoding string or bytes, therefore it's not subtracted unless it's zero const [wireType2Length, wireType2LengthSize] = readUInt32(message, index); if (wireType2Length === 0) { if (typeSchema.schemaProp.dataType === 'string') { result.push(''); } else { result.push(Buffer.alloc(0)); } index += wireType2LengthSize; // Add default value continue; } // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const [res, wire2Size] = _readers[typeSchema.schemaProp.dataType as string](message, index); result.push(res); index += wire2Size; } return [result, index]; } const [, keySize] = readUInt32(message, index); index += keySize; // Takeout the length const [arrayLength, wireType2Size] = readUInt32(message, index); index += wireType2Size; // Case for varint and boolean const end = index + arrayLength; while (index < end) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const [res, size] = _readers[typeSchema.schemaProp.dataType as string](message, index); result.push(res); index += size; } return [result, index]; }; export const writeArray = ( compiledSchema: CompiledSchema[], message: Array<unknown>, chunks: Buffer[], ): [Buffer[], number] => { if (message.length === 0) { return [chunks, 0]; } let totalSize = 0; const [rootSchema, typeSchema] = compiledSchema; // Array of object if (Array.isArray(typeSchema)) { for (let i = 0; i < message.length; i += 1) { const [res, objectSize] = writeObject(typeSchema, message[i] as GenericObject, []); chunks.push(rootSchema.binaryKey); const size = _writers.uint32(objectSize); chunks.push(size); for (let j = 0; j < res.length; j += 1) { chunks.push(res[j]); } totalSize += objectSize + size.length + rootSchema.binaryKey.length; } return [chunks, totalSize]; } // Array of string or bytes if (typeSchema.schemaProp.dataType === 'string' || typeSchema.schemaProp.dataType === 'bytes') { for (let i = 0; i < message.length; i += 1) { const res = _writers[typeSchema.schemaProp.dataType as string](message[i]); chunks.push(rootSchema.binaryKey); chunks.push(res); totalSize += res.length + rootSchema.binaryKey.length; } return [chunks, totalSize]; } // Array of number or boolean chunks.push(rootSchema.binaryKey); // Insert size const contents = []; let contentSize = 0; for (let i = 0; i < message.length; i += 1) { const res = _writers[typeSchema.schemaProp.dataType as string](message[i]); contents.push(res); contentSize += res.length; } const arrayLength = _writers.uint32(contentSize); chunks.push(arrayLength); for (let i = 0; i < contents.length; i += 1) { chunks.push(contents[i]); } totalSize += rootSchema.binaryKey.length + contentSize + arrayLength.length; return [chunks, totalSize]; };
the_stack
import { Params } from '@angular/router'; import { CoreRoutedItemsManagerSource } from '@classes/items-management/routed-items-manager-source'; import { AddonModGlossary, AddonModGlossaryEntry, AddonModGlossaryGetEntriesOptions, AddonModGlossaryGetEntriesWSResponse, AddonModGlossaryGlossary, AddonModGlossaryProvider, } from '../services/glossary'; import { AddonModGlossaryOffline, AddonModGlossaryOfflineEntry } from '../services/glossary-offline'; /** * Provides a collection of glossary entries. */ export class AddonModGlossaryEntriesSource extends CoreRoutedItemsManagerSource<AddonModGlossaryEntryItem> { static readonly NEW_ENTRY: AddonModGlossaryNewEntryForm = { newEntry: true }; readonly COURSE_ID: number; readonly CM_ID: number; readonly GLOSSARY_PATH_PREFIX: string; isSearch = false; hasSearched = false; fetchMode?: AddonModGlossaryFetchMode; viewMode?: string; glossary?: AddonModGlossaryGlossary; onlineEntries: AddonModGlossaryEntry[] = []; offlineEntries: AddonModGlossaryOfflineEntry[] = []; protected fetchFunction?: (options?: AddonModGlossaryGetEntriesOptions) => AddonModGlossaryGetEntriesWSResponse; protected fetchInvalidate?: () => Promise<void>; constructor(courseId: number, cmId: number, glossaryPathPrefix: string) { super(); this.COURSE_ID = courseId; this.CM_ID = cmId; this.GLOSSARY_PATH_PREFIX = glossaryPathPrefix; } /** * Type guard to infer NewEntryForm objects. * * @param entry Item to check. * @return Whether the item is a new entry form. */ isNewEntryForm(entry: AddonModGlossaryEntryItem): entry is AddonModGlossaryNewEntryForm { return 'newEntry' in entry; } /** * Type guard to infer entry objects. * * @param entry Item to check. * @return Whether the item is an offline entry. */ isOnlineEntry(entry: AddonModGlossaryEntryItem): entry is AddonModGlossaryEntry { return 'id' in entry; } /** * Type guard to infer entry objects. * * @param entry Item to check. * @return Whether the item is an offline entry. */ isOfflineEntry(entry: AddonModGlossaryEntryItem): entry is AddonModGlossaryOfflineEntry { return !this.isNewEntryForm(entry) && !this.isOnlineEntry(entry); } /** * @inheritdoc */ getItemPath(entry: AddonModGlossaryEntryItem): string { if (this.isOnlineEntry(entry)) { return `${this.GLOSSARY_PATH_PREFIX}entry/${entry.id}`; } if (this.isOfflineEntry(entry)) { return `${this.GLOSSARY_PATH_PREFIX}edit/${entry.timecreated}`; } return `${this.GLOSSARY_PATH_PREFIX}edit/0`; } /** * @inheritdoc */ getItemQueryParams(entry: AddonModGlossaryEntryItem): Params { const params: Params = { cmId: this.CM_ID, courseId: this.COURSE_ID, }; if (this.isOfflineEntry(entry)) { params.concept = entry.concept; } return params; } /** * @inheritdoc */ getPagesLoaded(): number { if (this.items === null) { return 0; } return Math.ceil(this.onlineEntries.length / this.getPageLength()); } /** * Start searching. */ startSearch(): void { this.isSearch = true; this.setDirty(true); } /** * Stop searching and restore unfiltered collection. * * @param cachedOnlineEntries Cached online entries. * @param hasMoreOnlineEntries Whether there were more online entries. */ stopSearch(cachedOnlineEntries: AddonModGlossaryEntry[], hasMoreOnlineEntries: boolean): void { if (!this.fetchMode) { return; } this.isSearch = false; this.hasSearched = false; this.onlineEntries = cachedOnlineEntries; this.hasMoreItems = hasMoreOnlineEntries; this.setDirty(true); } /** * Set search query. * * @param query Search query. */ search(query: string): void { if (!this.glossary) { return; } this.fetchFunction = AddonModGlossary.getEntriesBySearch.bind( AddonModGlossary.instance, this.glossary.id, query, true, 'CONCEPT', 'ASC', ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesBySearch.bind( AddonModGlossary.instance, this.glossary.id, query, true, 'CONCEPT', 'ASC', ); this.hasSearched = true; this.setDirty(true); } /** * Load glossary. */ async loadGlossary(): Promise<void> { this.glossary = await AddonModGlossary.getGlossary(this.COURSE_ID, this.CM_ID); } /** * Invalidate glossary cache. */ async invalidateCache(): Promise<void> { await Promise.all([ AddonModGlossary.invalidateCourseGlossaries(this.COURSE_ID), this.fetchInvalidate && this.fetchInvalidate(), this.glossary && AddonModGlossary.invalidateCategories(this.glossary.id), ]); } /** * Change fetch mode. * * @param mode New mode. */ switchMode(mode: AddonModGlossaryFetchMode): void { if (!this.glossary) { throw new Error('Can\'t switch entries mode without a glossary!'); } this.fetchMode = mode; this.isSearch = false; this.setDirty(true); switch (mode) { case 'author_all': // Browse by author. this.viewMode = 'author'; this.fetchFunction = AddonModGlossary.getEntriesByAuthor.bind( AddonModGlossary.instance, this.glossary.id, 'ALL', 'LASTNAME', 'ASC', ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesByAuthor.bind( AddonModGlossary.instance, this.glossary.id, 'ALL', 'LASTNAME', 'ASC', ); break; case 'cat_all': // Browse by category. this.viewMode = 'cat'; this.fetchFunction = AddonModGlossary.getEntriesByCategory.bind( AddonModGlossary.instance, this.glossary.id, AddonModGlossaryProvider.SHOW_ALL_CATEGORIES, ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesByCategory.bind( AddonModGlossary.instance, this.glossary.id, AddonModGlossaryProvider.SHOW_ALL_CATEGORIES, ); break; case 'newest_first': // Newest first. this.viewMode = 'date'; this.fetchFunction = AddonModGlossary.getEntriesByDate.bind( AddonModGlossary.instance, this.glossary.id, 'CREATION', 'DESC', ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesByDate.bind( AddonModGlossary.instance, this.glossary.id, 'CREATION', 'DESC', ); break; case 'recently_updated': // Recently updated. this.viewMode = 'date'; this.fetchFunction = AddonModGlossary.getEntriesByDate.bind( AddonModGlossary.instance, this.glossary.id, 'UPDATE', 'DESC', ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesByDate.bind( AddonModGlossary.instance, this.glossary.id, 'UPDATE', 'DESC', ); break; case 'letter_all': default: // Consider it is 'letter_all'. this.viewMode = 'letter'; this.fetchMode = 'letter_all'; this.fetchFunction = AddonModGlossary.getEntriesByLetter.bind( AddonModGlossary.instance, this.glossary.id, 'ALL', ); this.fetchInvalidate = AddonModGlossary.invalidateEntriesByLetter.bind( AddonModGlossary.instance, this.glossary.id, 'ALL', ); break; } } /** * @inheritdoc */ protected async loadPageItems(page: number): Promise<{ items: AddonModGlossaryEntryItem[]; hasMoreItems: boolean }> { const glossary = this.glossary; const fetchFunction = this.fetchFunction; if (!glossary || !fetchFunction) { throw new Error('Can\'t load entries without glossary or fetch function'); } const entries: AddonModGlossaryEntryItem[] = []; if (page === 0) { const offlineEntries = await AddonModGlossaryOffline.getGlossaryNewEntries(glossary.id); offlineEntries.sort((a, b) => a.concept.localeCompare(b.concept)); entries.push(AddonModGlossaryEntriesSource.NEW_ENTRY); entries.push(...offlineEntries); } const from = page * this.getPageLength(); const pageEntries = await fetchFunction({ from, cmId: this.CM_ID }); entries.push(...pageEntries.entries); return { items: entries, hasMoreItems: from + pageEntries.entries.length < pageEntries.count, }; } /** * @inheritdoc */ protected getPageLength(): number { return AddonModGlossaryProvider.LIMIT_ENTRIES; } /** * @inheritdoc */ protected setItems(entries: AddonModGlossaryEntryItem[], hasMoreItems: boolean): void { this.onlineEntries = []; this.offlineEntries = []; entries.forEach(entry => { this.isOnlineEntry(entry) && this.onlineEntries.push(entry); this.isOfflineEntry(entry) && this.offlineEntries.push(entry); }); super.setItems(entries, hasMoreItems); } /** * @inheritdoc */ reset(): void { this.onlineEntries = []; this.offlineEntries = []; super.reset(); } } /** * Type of items that can be held by the entries manager. */ export type AddonModGlossaryEntryItem = AddonModGlossaryEntry | AddonModGlossaryOfflineEntry | AddonModGlossaryNewEntryForm; /** * Type to select the new entry form. */ export type AddonModGlossaryNewEntryForm = { newEntry: true }; /** * Fetch mode to sort entries. */ export type AddonModGlossaryFetchMode = 'author_all' | 'cat_all' | 'newest_first' | 'recently_updated' | 'letter_all';
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/invoiceSectionsMappers"; import * as Parameters from "../models/parameters"; import { BillingManagementClientContext } from "../billingManagementClientContext"; /** Class representing a InvoiceSections. */ export class InvoiceSections { private readonly client: BillingManagementClientContext; /** * Create a InvoiceSections. * @param {BillingManagementClientContext} client Reference to the service client. */ constructor(client: BillingManagementClientContext) { this.client = client; } /** * Lists the invoice sections that a user has access to. The operation is supported only for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param [options] The optional parameters * @returns Promise<Models.InvoiceSectionsListByBillingProfileResponse> */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.InvoiceSectionsListByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.InvoiceSectionListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param options The optional parameters * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InvoiceSectionListResult>): void; listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InvoiceSectionListResult>, callback?: msRest.ServiceCallback<Models.InvoiceSectionListResult>): Promise<Models.InvoiceSectionsListByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, options }, listByBillingProfileOperationSpec, callback) as Promise<Models.InvoiceSectionsListByBillingProfileResponse>; } /** * Gets an invoice section by its ID. The operation is supported only for billing accounts with * agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param [options] The optional parameters * @returns Promise<Models.InvoiceSectionsGetResponse> */ get(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.InvoiceSectionsGetResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param callback The callback */ get(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, callback: msRest.ServiceCallback<Models.InvoiceSection>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param options The optional parameters * @param callback The callback */ get(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InvoiceSection>): void; get(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InvoiceSection>, callback?: msRest.ServiceCallback<Models.InvoiceSection>): Promise<Models.InvoiceSectionsGetResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, invoiceSectionName, options }, getOperationSpec, callback) as Promise<Models.InvoiceSectionsGetResponse>; } /** * Creates or updates an invoice section. The operation is supported only for billing accounts with * agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param parameters The new or updated invoice section. * @param [options] The optional parameters * @returns Promise<Models.InvoiceSectionsCreateOrUpdateResponse> */ createOrUpdate(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, parameters: Models.InvoiceSection, options?: msRest.RequestOptionsBase): Promise<Models.InvoiceSectionsCreateOrUpdateResponse> { return this.beginCreateOrUpdate(billingAccountName,billingProfileName,invoiceSectionName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.InvoiceSectionsCreateOrUpdateResponse>; } /** * Creates or updates an invoice section. The operation is supported only for billing accounts with * agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param parameters The new or updated invoice section. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, parameters: Models.InvoiceSection, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { billingAccountName, billingProfileName, invoiceSectionName, parameters, options }, beginCreateOrUpdateOperationSpec, options); } /** * Lists the invoice sections that a user has access to. The operation is supported only for * billing accounts with agreement type Microsoft Customer Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.InvoiceSectionsListByBillingProfileNextResponse> */ listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.InvoiceSectionsListByBillingProfileNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.InvoiceSectionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InvoiceSectionListResult>): void; listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InvoiceSectionListResult>, callback?: msRest.ServiceCallback<Models.InvoiceSectionListResult>): Promise<Models.InvoiceSectionsListByBillingProfileNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByBillingProfileNextOperationSpec, callback) as Promise<Models.InvoiceSectionsListByBillingProfileNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InvoiceSectionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InvoiceSection }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.InvoiceSection, required: true } }, responses: { 200: { bodyMapper: Mappers.InvoiceSection, headersMapper: Mappers.InvoiceSectionsCreateOrUpdateHeaders }, 202: { headersMapper: Mappers.InvoiceSectionsCreateOrUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse, headersMapper: Mappers.InvoiceSectionsCreateOrUpdateHeaders } }, serializer }; const listByBillingProfileNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InvoiceSectionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { PDFOperator, PDFWidgetAnnotation } from 'src/core'; import PDFFont from 'src/api/PDFFont'; import PDFButton from 'src/api/form/PDFButton'; import PDFCheckBox from 'src/api/form/PDFCheckBox'; import PDFDropdown from 'src/api/form/PDFDropdown'; import PDFField from 'src/api/form/PDFField'; import PDFOptionList from 'src/api/form/PDFOptionList'; import PDFRadioGroup from 'src/api/form/PDFRadioGroup'; import PDFSignature from 'src/api/form/PDFSignature'; import PDFTextField from 'src/api/form/PDFTextField'; import { drawCheckBox, rotateInPlace, drawRadioButton, drawButton, drawTextField, drawOptionList, } from 'src/api/operations'; import { rgb, componentsToColor, setFillingColor, grayscale, cmyk, Color, } from 'src/api/colors'; import { reduceRotation, adjustDimsForRotation } from 'src/api/rotations'; import { layoutMultilineText, layoutCombedText, TextPosition, layoutSinglelineText, } from 'src/api/text/layout'; import { TextAlignment } from 'src/api/text/alignment'; import { setFontAndSize } from 'src/api/operators'; import { findLastMatch } from 'src/utils'; /*********************** Appearance Provider Types ****************************/ type CheckBoxAppearanceProvider = ( checkBox: PDFCheckBox, widget: PDFWidgetAnnotation, ) => AppearanceOrMapping<{ on: PDFOperator[]; off: PDFOperator[]; }>; type RadioGroupAppearanceProvider = ( radioGroup: PDFRadioGroup, widget: PDFWidgetAnnotation, ) => AppearanceOrMapping<{ on: PDFOperator[]; off: PDFOperator[]; }>; type ButtonAppearanceProvider = ( button: PDFButton, widget: PDFWidgetAnnotation, font: PDFFont, ) => AppearanceOrMapping<PDFOperator[]>; type DropdownAppearanceProvider = ( dropdown: PDFDropdown, widget: PDFWidgetAnnotation, font: PDFFont, ) => AppearanceOrMapping<PDFOperator[]>; type OptionListAppearanceProvider = ( optionList: PDFOptionList, widget: PDFWidgetAnnotation, font: PDFFont, ) => AppearanceOrMapping<PDFOperator[]>; type TextFieldAppearanceProvider = ( textField: PDFTextField, widget: PDFWidgetAnnotation, font: PDFFont, ) => AppearanceOrMapping<PDFOperator[]>; type SignatureAppearanceProvider = ( signature: PDFSignature, widget: PDFWidgetAnnotation, font: PDFFont, ) => AppearanceOrMapping<PDFOperator[]>; /******************* Appearance Provider Utility Types ************************/ export type AppearanceMapping<T> = { normal: T; rollover?: T; down?: T }; type AppearanceOrMapping<T> = T | AppearanceMapping<T>; // prettier-ignore export type AppearanceProviderFor<T extends PDFField> = T extends PDFCheckBox ? CheckBoxAppearanceProvider : T extends PDFRadioGroup ? RadioGroupAppearanceProvider : T extends PDFButton ? ButtonAppearanceProvider : T extends PDFDropdown ? DropdownAppearanceProvider : T extends PDFOptionList ? OptionListAppearanceProvider : T extends PDFTextField ? TextFieldAppearanceProvider : T extends PDFSignature ? SignatureAppearanceProvider : never; /********************* Appearance Provider Functions **************************/ export const normalizeAppearance = <T>( appearance: T | AppearanceMapping<T>, ): AppearanceMapping<T> => { if ('normal' in appearance) return appearance; return { normal: appearance }; }; // Examples: // `/Helv 12 Tf` -> ['/Helv 12 Tf', 'Helv', '12'] // `/HeBo 8.00 Tf` -> ['/HeBo 8 Tf', 'HeBo', '8.00'] const tfRegex = /\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/; const getDefaultFontSize = (field: { getDefaultAppearance(): string | undefined; }) => { const da = field.getDefaultAppearance() ?? ''; const daMatch = findLastMatch(da, tfRegex).match ?? []; const defaultFontSize = Number(daMatch[2]); return isFinite(defaultFontSize) ? defaultFontSize : undefined; }; // Examples: // `0.3 g` -> ['0.3', 'g'] // `0.3 1 .3 rg` -> ['0.3', '1', '.3', 'rg'] // `0.3 1 .3 0 k` -> ['0.3', '1', '.3', '0', 'k'] const colorRegex = /(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/; const getDefaultColor = (field: { getDefaultAppearance(): string | undefined; }) => { const da = field.getDefaultAppearance() ?? ''; const daMatch = findLastMatch(da, colorRegex).match; const [, c1, c2, c3, c4, colorSpace] = daMatch ?? []; if (colorSpace === 'g' && c1) { return grayscale(Number(c1)); } if (colorSpace === 'rg' && c1 && c2 && c3) { return rgb(Number(c1), Number(c2), Number(c3)); } if (colorSpace === 'k' && c1 && c2 && c3 && c4) { return cmyk(Number(c1), Number(c2), Number(c3), Number(c4)); } return undefined; }; const updateDefaultAppearance = ( field: { setDefaultAppearance(appearance: string): void }, color: Color, font?: PDFFont, fontSize: number = 0, ) => { const da = [ setFillingColor(color).toString(), setFontAndSize(font?.name ?? 'dummy__noop', fontSize).toString(), ].join('\n'); field.setDefaultAppearance(da); }; export const defaultCheckBoxAppearanceProvider: AppearanceProviderFor<PDFCheckBox> = ( checkBox, widget, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(checkBox.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()) ?? black; const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8); // Update color const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor) { updateDefaultAppearance(widget, textColor); } else { updateDefaultAppearance(checkBox.acroField, textColor); } const options = { x: 0 + borderWidth / 2, y: 0 + borderWidth / 2, width: width - borderWidth, height: height - borderWidth, thickness: 1.5, borderWidth, borderColor, markColor: textColor, }; return { normal: { on: [ ...rotate, ...drawCheckBox({ ...options, color: normalBackgroundColor, filled: true, }), ], off: [ ...rotate, ...drawCheckBox({ ...options, color: normalBackgroundColor, filled: false, }), ], }, down: { on: [ ...rotate, ...drawCheckBox({ ...options, color: downBackgroundColor, filled: true, }), ], off: [ ...rotate, ...drawCheckBox({ ...options, color: downBackgroundColor, filled: false, }), ], }, }; }; export const defaultRadioGroupAppearanceProvider: AppearanceProviderFor<PDFRadioGroup> = ( radioGroup, widget, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(radioGroup.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()) ?? black; const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8); // Update color const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor) { updateDefaultAppearance(widget, textColor); } else { updateDefaultAppearance(radioGroup.acroField, textColor); } const options = { x: width / 2, y: height / 2, width: width - borderWidth, height: height - borderWidth, borderWidth, borderColor, dotColor: textColor, }; return { normal: { on: [ ...rotate, ...drawRadioButton({ ...options, color: normalBackgroundColor, filled: true, }), ], off: [ ...rotate, ...drawRadioButton({ ...options, color: normalBackgroundColor, filled: false, }), ], }, down: { on: [ ...rotate, ...drawRadioButton({ ...options, color: downBackgroundColor, filled: true, }), ], off: [ ...rotate, ...drawRadioButton({ ...options, color: downBackgroundColor, filled: false, }), ], }, }; }; export const defaultButtonAppearanceProvider: AppearanceProviderFor<PDFButton> = ( button, widget, font, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(button.acroField); const widgetFontSize = getDefaultFontSize(widget); const fieldFontSize = getDefaultFontSize(button.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const captions = ap?.getCaptions(); const normalText = captions?.normal ?? ''; const downText = captions?.down ?? normalText ?? ''; const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()); const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8); const bounds = { x: borderWidth, y: borderWidth, width: width - borderWidth * 2, height: height - borderWidth * 2, }; const normalLayout = layoutSinglelineText(normalText, { alignment: TextAlignment.Center, fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); const downLayout = layoutSinglelineText(downText, { alignment: TextAlignment.Center, fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); // Update font size and color const fontSize = Math.min(normalLayout.fontSize, downLayout.fontSize); const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor || widgetFontSize !== undefined) { updateDefaultAppearance(widget, textColor, font, fontSize); } else { updateDefaultAppearance(button.acroField, textColor, font, fontSize); } const options = { x: 0 + borderWidth / 2, y: 0 + borderWidth / 2, width: width - borderWidth, height: height - borderWidth, borderWidth, borderColor, textColor, font: font.name, fontSize, }; return { normal: [ ...rotate, ...drawButton({ ...options, color: normalBackgroundColor, textLines: [normalLayout.line], }), ], down: [ ...rotate, ...drawButton({ ...options, color: downBackgroundColor, textLines: [downLayout.line], }), ], }; }; export const defaultTextFieldAppearanceProvider: AppearanceProviderFor<PDFTextField> = ( textField, widget, font, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(textField.acroField); const widgetFontSize = getDefaultFontSize(widget); const fieldFontSize = getDefaultFontSize(textField.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const text = textField.getText() ?? ''; const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()); const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); let textLines: TextPosition[]; let fontSize: number; const padding = textField.isCombed() ? 0 : 1; const bounds = { x: borderWidth + padding, y: borderWidth + padding, width: width - (borderWidth + padding) * 2, height: height - (borderWidth + padding) * 2, }; if (textField.isMultiline()) { const layout = layoutMultilineText(text, { alignment: textField.getAlignment(), fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); textLines = layout.lines; fontSize = layout.fontSize; } else if (textField.isCombed()) { const layout = layoutCombedText(text, { fontSize: widgetFontSize ?? fieldFontSize, font, bounds, cellCount: textField.getMaxLength() ?? 0, }); textLines = layout.cells; fontSize = layout.fontSize; } else { const layout = layoutSinglelineText(text, { alignment: textField.getAlignment(), fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); textLines = [layout.line]; fontSize = layout.fontSize; } // Update font size and color const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor || widgetFontSize !== undefined) { updateDefaultAppearance(widget, textColor, font, fontSize); } else { updateDefaultAppearance(textField.acroField, textColor, font, fontSize); } const options = { x: 0 + borderWidth / 2, y: 0 + borderWidth / 2, width: width - borderWidth, height: height - borderWidth, borderWidth: borderWidth ?? 0, borderColor, textColor, font: font.name, fontSize, color: normalBackgroundColor, textLines, padding, }; return [...rotate, ...drawTextField(options)]; }; export const defaultDropdownAppearanceProvider: AppearanceProviderFor<PDFDropdown> = ( dropdown, widget, font, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(dropdown.acroField); const widgetFontSize = getDefaultFontSize(widget); const fieldFontSize = getDefaultFontSize(dropdown.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const text = dropdown.getSelected()[0] ?? ''; const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()); const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); const padding = 1; const bounds = { x: borderWidth + padding, y: borderWidth + padding, width: width - (borderWidth + padding) * 2, height: height - (borderWidth + padding) * 2, }; const { line, fontSize } = layoutSinglelineText(text, { alignment: TextAlignment.Left, fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); // Update font size and color const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor || widgetFontSize !== undefined) { updateDefaultAppearance(widget, textColor, font, fontSize); } else { updateDefaultAppearance(dropdown.acroField, textColor, font, fontSize); } const options = { x: 0 + borderWidth / 2, y: 0 + borderWidth / 2, width: width - borderWidth, height: height - borderWidth, borderWidth: borderWidth ?? 0, borderColor, textColor, font: font.name, fontSize, color: normalBackgroundColor, textLines: [line], padding, }; return [...rotate, ...drawTextField(options)]; }; export const defaultOptionListAppearanceProvider: AppearanceProviderFor<PDFOptionList> = ( optionList, widget, font, ) => { // The `/DA` entry can be at the widget or field level - so we handle both const widgetColor = getDefaultColor(widget); const fieldColor = getDefaultColor(optionList.acroField); const widgetFontSize = getDefaultFontSize(widget); const fieldFontSize = getDefaultFontSize(optionList.acroField); const rectangle = widget.getRectangle(); const ap = widget.getAppearanceCharacteristics(); const bs = widget.getBorderStyle(); const borderWidth = bs?.getWidth() ?? 0; const rotation = reduceRotation(ap?.getRotation()); const { width, height } = adjustDimsForRotation(rectangle, rotation); const rotate = rotateInPlace({ ...rectangle, rotation }); const black = rgb(0, 0, 0); const borderColor = componentsToColor(ap?.getBorderColor()); const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor()); const options = optionList.getOptions(); const selected = optionList.getSelected(); if (optionList.isSorted()) options.sort(); let text = ''; for (let idx = 0, len = options.length; idx < len; idx++) { text += options[idx]; if (idx < len - 1) text += '\n'; } const padding = 1; const bounds = { x: borderWidth + padding, y: borderWidth + padding, width: width - (borderWidth + padding) * 2, height: height - (borderWidth + padding) * 2, }; const { lines, fontSize, lineHeight } = layoutMultilineText(text, { alignment: TextAlignment.Left, fontSize: widgetFontSize ?? fieldFontSize, font, bounds, }); const selectedLines: number[] = []; for (let idx = 0, len = lines.length; idx < len; idx++) { const line = lines[idx]; if (selected.includes(line.text)) selectedLines.push(idx); } const blue = rgb(153 / 255, 193 / 255, 218 / 255); // Update font size and color const textColor = widgetColor ?? fieldColor ?? black; if (widgetColor || widgetFontSize !== undefined) { updateDefaultAppearance(widget, textColor, font, fontSize); } else { updateDefaultAppearance(optionList.acroField, textColor, font, fontSize); } return [ ...rotate, ...drawOptionList({ x: 0 + borderWidth / 2, y: 0 + borderWidth / 2, width: width - borderWidth, height: height - borderWidth, borderWidth: borderWidth ?? 0, borderColor, textColor, font: font.name, fontSize, color: normalBackgroundColor, textLines: lines, lineHeight, selectedColor: blue, selectedLines, padding, }), ]; };
the_stack
import { getLabwareDefURI, MAGNETIC_MODULE_TYPE, LabwareDefinition2, } from '@opentrons/shared-data' import _fixtureTiprack300ul from '@opentrons/shared-data/labware/fixtures/2/fixture_tiprack_300_ul.json' import { makeContext, makeState, getTipColumn, getTiprackTipstate, DEFAULT_PIPETTE, } from '../fixtures' import { sortLabwareBySlot, getNextTiprack, _getNextTip, getModuleState, } from '../' import { InvariantContext } from '../types' let invariantContext: InvariantContext const fixtureTiprack300ul = _fixtureTiprack300ul as LabwareDefinition2 beforeEach(() => { invariantContext = makeContext() }) describe('sortLabwareBySlot', () => { it('sorts all labware by slot', () => { const labwareState = { six: { slot: '6', }, one: { slot: '1', }, eleven: { slot: '11', }, two: { slot: '2', }, } expect(sortLabwareBySlot(labwareState)).toEqual([ 'one', 'two', 'six', 'eleven', ]) }) it('with no labware, return empty array', () => { const labwareState = {} expect(sortLabwareBySlot(labwareState)).toEqual([]) }) }) describe('_getNextTip', () => { const getNextTipHelper = ( channel: 1 | 8, tiprackTipState: Record<string, boolean> ): string | null => { const pipetteId = channel === 1 ? DEFAULT_PIPETTE : 'p300MultiId' const tiprackId = 'testTiprack' const _invariantContext = makeContext() _invariantContext.labwareEntities[tiprackId] = { id: tiprackId, labwareDefURI: getLabwareDefURI(fixtureTiprack300ul), def: fixtureTiprack300ul, } const robotState = makeState({ invariantContext: _invariantContext, labwareLocations: { [tiprackId]: { slot: '8' } }, pipetteLocations: { p300SingleId: { mount: 'left' }, p300MultiId: { mount: 'right' }, }, tiprackSetting: { [tiprackId]: true }, }) robotState.tipState.tipracks[tiprackId] = tiprackTipState return _getNextTip({ pipetteId, tiprackId, invariantContext: _invariantContext, robotState, }) } it('empty tiprack should return null', () => { const channels = [1, 8] as const channels.forEach(channel => { const result = getNextTipHelper(channel, { ...getTiprackTipstate(false) }) expect(result).toBe(null) }) }) it('full tiprack should start at A1', () => { const result = getNextTipHelper(1, { ...getTiprackTipstate(true) }) expect(result).toEqual('A1') }) it('missing A1, go to B1', () => { const result = getNextTipHelper(1, { ...getTiprackTipstate(true), A1: false, }) expect(result).toEqual('B1') }) it('missing A1 and B1, go to C1', () => { const result = getNextTipHelper(1, { ...getTiprackTipstate(true), A1: false, B1: false, }) expect(result).toEqual('C1') }) it('missing first column, go to A2', () => { const result = getNextTipHelper(1, { ...getTiprackTipstate(true), ...getTipColumn(1, false), }) expect(result).toEqual('A2') }) it('missing a few random tips, go to lowest col, then lowest row', () => { const result = getNextTipHelper(1, { ...getTiprackTipstate(true), ...getTipColumn(1, false), ...getTipColumn(2, false), D2: true, }) expect(result).toEqual('D2') }) }) describe('getNextTiprack - single-channel', () => { it('single tiprack, missing A1', () => { const robotState = makeState({ invariantContext, labwareLocations: { tiprack1Id: { slot: '1' }, sourcePlateId: { slot: '2' }, }, pipetteLocations: { p300SingleId: { mount: 'left' } }, tiprackSetting: { tiprack1Id: true }, }) robotState.tipState.tipracks.tiprack1Id.A1 = false const result = getNextTiprack(DEFAULT_PIPETTE, invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('B1') }) it('single tiprack, empty, should return null', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '1' } }, tiprackSetting: { tiprack1Id: false }, }) const result = getNextTiprack(DEFAULT_PIPETTE, invariantContext, robotState) expect(result).toEqual(null) }) it('multiple tipracks, all full, should return the filled tiprack in the lowest slot', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '1' }, tiprack2Id: { slot: '11' }, }, tiprackSetting: { tiprack1Id: true, tiprack2Id: true }, }) const result = getNextTiprack(DEFAULT_PIPETTE, invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('A1') }) it('multiple tipracks, some partially full, should return the filled tiprack in the lowest slot', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, tiprack2Id: { slot: '11' }, }, tiprackSetting: { tiprack1Id: true, tiprack2Id: true }, }) // remove A1 tip from both racks robotState.tipState.tipracks.tiprack1Id.A1 = false robotState.tipState.tipracks.tiprack2Id.A1 = false const result = getNextTiprack(DEFAULT_PIPETTE, invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('B1') }) it('multiple tipracks, all empty, should return null', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, tiprack2Id: { slot: '11' }, }, tiprackSetting: { tiprack1Id: false, tiprack2Id: false }, }) const result = getNextTiprack(DEFAULT_PIPETTE, invariantContext, robotState) expect(result).toBe(null) }) }) describe('getNextTiprack - 8-channel', () => { it('single tiprack, totally full', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '1' }, }, tiprackSetting: { tiprack1Id: true }, }) const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('A1') }) it('single tiprack, partially full', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, }, tiprackSetting: { tiprack1Id: true }, }) robotState.tipState.tipracks.tiprack1Id = { ...robotState.tipState.tipracks.tiprack1Id, A1: false, A2: false, A5: false, } const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('A3') }) it('single tiprack, empty, should return null', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, }, tiprackSetting: { tiprack1Id: false }, }) const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result).toEqual(null) }) it('single tiprack, a well missing from each column, should return null', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, }, tiprackSetting: { tiprack1Id: true }, }) robotState.tipState.tipracks.tiprack1Id = { ...robotState.tipState.tipracks.tiprack1Id, F1: false, B2: false, C3: false, A4: false, H5: false, E6: false, B7: false, A8: false, C9: false, D10: false, G11: false, F12: false, } const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result).toEqual(null) }) it('multiple tipracks, all full, should return the filled tiprack in the lowest slot', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, tiprack2Id: { slot: '3' }, tiprack3Id: { slot: '10' }, }, tiprackSetting: { tiprack1Id: true, tiprack2Id: true, tiprack3Id: true }, }) const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack1Id') expect(result && result.well).toEqual('A1') }) it('multiple tipracks, some partially full, should return the filled tiprack in the lowest slot', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '1' }, tiprack2Id: { slot: '2' }, tiprack3Id: { slot: '3' }, }, tiprackSetting: { tiprack1Id: true, tiprack2Id: true, tiprack3Id: true }, }) // remove tips from state robotState.tipState.tipracks.tiprack1Id = { ...robotState.tipState.tipracks.tiprack1Id, // empty row, 8-channel cannot use A1: false, A2: false, A3: false, A4: false, A5: false, A6: false, A7: false, A8: false, A9: false, A10: false, A11: false, A12: false, } robotState.tipState.tipracks.tiprack2Id = { ...robotState.tipState.tipracks.tiprack2Id, // empty diagonal, 8-channel cannot use F1: false, B2: false, C3: false, A4: false, H5: false, E6: false, B7: false, A8: false, C9: false, D10: false, G11: false, F12: false, } robotState.tipState.tipracks.tiprack3Id = { ...robotState.tipState.tipracks.tiprack3Id, A1: false, } const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result && result.tiprackId).toEqual('tiprack3Id') expect(result && result.well).toEqual('A2') }) it('multiple tipracks, all empty, should return null', () => { const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '1' }, tiprack2Id: { slot: '2' }, tiprack3Id: { slot: '3' }, }, tiprackSetting: { tiprack1Id: false, tiprack2Id: false, tiprack3Id: false, }, }) const result = getNextTiprack('p300MultiId', invariantContext, robotState) expect(result).toEqual(null) }) }) describe('getModuleState', () => { it('returns the state for specified module', () => { const magModuleId = 'magdeck123' const magModuleState = { type: MAGNETIC_MODULE_TYPE, engaged: true, } const robotState = makeState({ invariantContext, pipetteLocations: { p300SingleId: { mount: 'left' } }, labwareLocations: { tiprack1Id: { slot: '2' }, }, tiprackSetting: { tiprack1Id: false }, moduleLocations: { [magModuleId]: { slot: '4', moduleState: magModuleState, }, }, }) const moduleState = getModuleState(robotState, magModuleId) expect(moduleState).toEqual(magModuleState) }) })
the_stack
import { SENSITIVE_STRING } from "@aws-sdk/smithy-client"; import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p> * You are not authorized to perform this action. * </p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; Message?: string; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } export interface CancelQueryRequest { /** * <p> * The id of the query that needs to be cancelled. <code>QueryID</code> is returned as part of QueryResult. * </p> */ QueryId: string | undefined; } export namespace CancelQueryRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelQueryRequest): any => ({ ...obj, }); } export interface CancelQueryResponse { /** * <p> * A <code>CancellationMessage</code> is returned when a <code>CancelQuery</code> request for the query specified by <code>QueryId</code> has already been issued. * </p> */ CancellationMessage?: string; } export namespace CancelQueryResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelQueryResponse): any => ({ ...obj, }); } /** * <p> * Timestream was unable to fully process this request because of an internal server error. * </p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; Message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>The requested endpoint was invalid.</p> */ export interface InvalidEndpointException extends __SmithyException, $MetadataBearer { name: "InvalidEndpointException"; $fault: "client"; Message?: string; } export namespace InvalidEndpointException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidEndpointException): any => ({ ...obj, }); } /** * <p>The request was denied due to request throttling.</p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; Message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * <p> * Invalid or malformed request. * </p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } export enum ScalarType { BIGINT = "BIGINT", BOOLEAN = "BOOLEAN", DATE = "DATE", DOUBLE = "DOUBLE", INTEGER = "INTEGER", INTERVAL_DAY_TO_SECOND = "INTERVAL_DAY_TO_SECOND", INTERVAL_YEAR_TO_MONTH = "INTERVAL_YEAR_TO_MONTH", TIME = "TIME", TIMESTAMP = "TIMESTAMP", UNKNOWN = "UNKNOWN", VARCHAR = "VARCHAR", } /** * <p> * Unable to poll results for a cancelled query. * </p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } export interface DescribeEndpointsRequest {} export namespace DescribeEndpointsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEndpointsRequest): any => ({ ...obj, }); } /** * <p>Represents an available endpoint against which to make API calls agaisnt, as well as the TTL for that endpoint.</p> */ export interface Endpoint { /** * <p>An endpoint address.</p> */ Address: string | undefined; /** * <p>The TTL for the endpoint, in minutes.</p> */ CachePeriodInMinutes: number | undefined; } export namespace Endpoint { /** * @internal */ export const filterSensitiveLog = (obj: Endpoint): any => ({ ...obj, }); } export interface DescribeEndpointsResponse { /** * <p>An <code>Endpoints</code> object is returned when a <code>DescribeEndpoints</code> request is made.</p> */ Endpoints: Endpoint[] | undefined; } export namespace DescribeEndpointsResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEndpointsResponse): any => ({ ...obj, }); } /** * <p> * Timestream was unable to run the query successfully. * </p> */ export interface QueryExecutionException extends __SmithyException, $MetadataBearer { name: "QueryExecutionException"; $fault: "client"; Message?: string; } export namespace QueryExecutionException { /** * @internal */ export const filterSensitiveLog = (obj: QueryExecutionException): any => ({ ...obj, }); } export interface QueryRequest { /** * <p> * The query to be executed by Timestream. * </p> */ QueryString: string | undefined; /** * <p> * Unique, case-sensitive string of up to 64 ASCII characters that you specify when you make a Query request. * Providing a <code>ClientToken</code> makes the call to <code>Query</code> idempotent, meaning that multiple identical calls * have the same effect as one single call. * </p> * * <p>Your query request will fail in the following cases:</p> * <ul> * <li> * <p> * If you submit a request with the same client token outside the 5-minute idepotency window. * </p> * </li> * <li> * <p> * If you submit a request with the same client token but a change in other parameters within the 5-minute idempotency window. * </p> * </li> * </ul> * * <p> * After 4 hours, any request with the same client token is treated as a new request. * </p> */ ClientToken?: string; /** * <p> * A pagination token passed to get a set of results. * </p> */ NextToken?: string; /** * <p> * The total number of rows to return in the output. If the total number of rows available * is more than the value specified, a NextToken is provided in the command's output. * To resume pagination, provide the NextToken value in the starting-token argument of a * subsequent command. * </p> */ MaxRows?: number; } export namespace QueryRequest { /** * @internal */ export const filterSensitiveLog = (obj: QueryRequest): any => ({ ...obj, ...(obj.QueryString && { QueryString: SENSITIVE_STRING }), ...(obj.ClientToken && { ClientToken: SENSITIVE_STRING }), }); } /** * <p>Information about the status of the query, including progress and bytes scannned.</p> */ export interface QueryStatus { /** * <p>The progress of the query, expressed as a percentage.</p> */ ProgressPercentage?: number; /** * <p>The amount of data scanned by the query in bytes. * This is a cumulative sum and represents the total amount of bytes scanned since the query was started. * </p> */ CumulativeBytesScanned?: number; /** * <p>The amount of data scanned by the query in bytes that you will be charged for. * This is a cumulative sum and represents the total amount of data that you will be charged * for since the query was started. * The charge is applied only once and is either applied when * the query completes execution or when the query is cancelled. * </p> */ CumulativeBytesMetered?: number; } export namespace QueryStatus { /** * @internal */ export const filterSensitiveLog = (obj: QueryStatus): any => ({ ...obj, }); } /** * <p> * Contains the meta data for query results such as the column names, data types, and other attributes. * </p> */ export interface ColumnInfo { /** * <p> * The name of the result set column. The name of the result set is available for columns of all data types except for arrays. * </p> */ Name?: string; /** * <p> * The data type of the result set column. The data type can be a scalar or complex. Scalar data types are integers, strings, doubles, booleans, and others. Complex data types are types such as arrays, rows, and others. * </p> */ Type: Type | undefined; } export namespace ColumnInfo { /** * @internal */ export const filterSensitiveLog = (obj: ColumnInfo): any => ({ ...obj, }); } /** * <p>Contains the data type of a column in a query result set. The data type can be scalar or complex. The supported scalar data types are integers, boolean, string, double, timestamp, date, time, and intervals. The supported complex data types are arrays, rows, and timeseries.</p> */ export interface Type { /** * <p>Indicates if the column is of type string, integer, boolean, double, timestamp, date, time. </p> */ ScalarType?: ScalarType | string; /** * <p>Indicates if the column is an array.</p> */ ArrayColumnInfo?: ColumnInfo; /** * <p>Indicates if the column is a timeseries data type.</p> */ TimeSeriesMeasureValueColumnInfo?: ColumnInfo; /** * <p>Indicates if the column is a row.</p> */ RowColumnInfo?: ColumnInfo[]; } export namespace Type { /** * @internal */ export const filterSensitiveLog = (obj: Type): any => ({ ...obj, }); } /** * <p> * Datum represents a single data point in a query result. * </p> */ export interface Datum { /** * <p> * Indicates if the data point is a scalar value such as integer, string, double, or boolean. * </p> */ ScalarValue?: string; /** * <p> * Indicates if the data point is of timeseries data type. * </p> */ TimeSeriesValue?: TimeSeriesDataPoint[]; /** * <p> * Indicates if the data point is an array. * </p> */ ArrayValue?: Datum[]; /** * <p> * Indicates if the data point is a row. * </p> */ RowValue?: Row; /** * <p> * Indicates if the data point is null. * </p> */ NullValue?: boolean; } export namespace Datum { /** * @internal */ export const filterSensitiveLog = (obj: Datum): any => ({ ...obj, }); } /** * <p>The timeseries datatype represents the values of a measure over time. A time series is an array of rows of timestamps and measure values, with rows sorted in ascending order of time. A TimeSeriesDataPoint is a single data point in the timeseries. It represents a tuple of (time, measure value) in a timeseries. </p> */ export interface TimeSeriesDataPoint { /** * <p>The timestamp when the measure value was collected.</p> */ Time: string | undefined; /** * <p>The measure value for the data point.</p> */ Value: Datum | undefined; } export namespace TimeSeriesDataPoint { /** * @internal */ export const filterSensitiveLog = (obj: TimeSeriesDataPoint): any => ({ ...obj, }); } /** * <p>Represents a single row in the query results.</p> */ export interface Row { /** * <p>List of data points in a single row of the result set.</p> */ Data: Datum[] | undefined; } export namespace Row { /** * @internal */ export const filterSensitiveLog = (obj: Row): any => ({ ...obj, }); } export interface QueryResponse { /** * <p> * A unique ID for the given query. * </p> */ QueryId: string | undefined; /** * <p> * A pagination token that can be used again on a <code>Query</code> call to get the next set of results. * </p> */ NextToken?: string; /** * <p> * The result set rows returned by the query. * </p> */ Rows: Row[] | undefined; /** * <p> * The column data types of the returned result set. * </p> */ ColumnInfo: ColumnInfo[] | undefined; /** * <p>Information about the status of the query, including progress and bytes scannned.</p> */ QueryStatus?: QueryStatus; } export namespace QueryResponse { /** * @internal */ export const filterSensitiveLog = (obj: QueryResponse): any => ({ ...obj, }); }
the_stack
import type { BigNumber } from '@ethersproject/bignumber'; import type { Bytes } from '@ethersproject/bytes'; export type BigNumberish = BigNumber | Bytes | bigint | string | number; export interface AddressesForChainV3 { exchange: string; erc20Proxy: string; erc721Proxy: string; multiAssetProxy: string; erc1155Proxy: string; forwarder: string; wrappedNativeToken?: string | null; } export type ContractAddresses = { [chainId: string]: AddressesForChainV3; }; export interface Order { makerAddress: string; takerAddress: string; feeRecipientAddress: string; senderAddress: string; makerAssetAmount: string; takerAssetAmount: string; makerFee: string; takerFee: string; expirationTimeSeconds: string; salt: string; makerAssetData: string; takerAssetData: string; makerFeeAssetData: string; takerFeeAssetData: string; signature?: string; } export interface SignedOrder extends Order { signature: string; } export declare enum SignatureType { Illegal = 0, Invalid = 1, EIP712 = 2, EthSign = 3, Wallet = 4, Validator = 5, PreSigned = 6, EIP1271Wallet = 7, NSignatureTypes = 8, } export enum AssetProxyId { ERC20 = '0xf47261b0', ERC721 = '0x02571792', MultiAsset = '0x94cfcdd7', ERC1155 = '0xa7cb5fb7', StaticCall = '0xc339d10a', ERC20Bridge = '0xdc1600f3', } export enum SupportedChainIdsV3 { Mainnet = 1, Ropsten = 3, Rinkeby = 4, Kovan = 42, Ganache = 1337, BSC = 56, Polygon = 137, PolygonMumbai = 80001, Avalanche = 43114, } export interface OrderInfoV3 { orderStatus: OrderStatusV3; orderHash: string; orderTakerAssetFilledAmount: BigNumber; } export enum OrderStatusV3 { Invalid = 0, InvalidMakerAssetAmount, InvalidTakerAssetAmount, Fillable, Expired, FullyFilled, Cancelled, } export const OrderStatusCodeLookup = { 0: 'Invalid', 1: 'InvalidMakerAssetAmount', 2: 'InvalidTakerAssetAmount', 3: 'Fillable', 4: 'Expired', 5: 'FullyFilled', 6: 'Cancelled', }; export interface ERC20AssetData { assetProxyId: string; tokenAddress: string; } export interface ERC20BridgeAssetData { assetProxyId: string; tokenAddress: string; bridgeAddress: string; bridgeData: string; } export interface ERC721AssetData { assetProxyId: string; tokenAddress: string; tokenId: BigNumber; } export interface ERC1155AssetData { assetProxyId: string; tokenAddress: string; tokenIds: BigNumber[]; tokenValues: BigNumber[]; callbackData: string; } export interface StaticCallAssetData { assetProxyId: string; callTarget: string; staticCallData: string; callResultHash: string; } export interface ERC1155AssetDataNoProxyId { tokenAddress: string; tokenValues: BigNumber[]; tokenIds: BigNumber[]; callbackData: string; } export declare type SingleAssetData = | ERC20AssetData | ERC20BridgeAssetData | ERC721AssetData | ERC1155AssetData | StaticCallAssetData; export interface MultiAssetData { assetProxyId: string; amounts: BigNumber[]; nestedAssetData: string[]; } export interface MultiAssetDataWithRecursiveDecoding { assetProxyId: string; amounts: BigNumber[]; nestedAssetData: SingleAssetData[]; } export interface MultiAssetDataWithRecursiveDecoding { assetProxyId: string; amounts: BigNumber[]; nestedAssetData: SingleAssetData[]; } export interface DutchAuctionData { assetData: AssetData; beginTimeSeconds: BigNumber; beginAmount: BigNumber; } export declare type AssetData = | SingleAssetData | MultiAssetData | MultiAssetDataWithRecursiveDecoding; export type AvailableSingleAssetDataTypes = | ERC20AssetData | ERC721AssetData | ERC1155AssetData; export type AvailableAssetDataTypes = | AvailableSingleAssetDataTypes | MultiAssetData; export interface MultiAssetDataSerialized { assetProxyId: string; amounts: string[]; nestedAssetData: string[]; } // User facing export interface UserFacingERC20AssetDataSerialized { tokenAddress: string; type: 'ERC20'; amount: string; } export interface UserFacingERC721AssetDataSerialized { tokenAddress: string; tokenId: string; type: 'ERC721'; } export interface UserFacingERC1155AssetDataSerialized { tokenAddress: string; tokens: Array<{ tokenId: string; tokenValue: string }>; type: 'ERC1155'; } /** * Mimic the erc721 duck type */ export interface UserFacingERC1155AssetDataSerializedNormalizedSingle { tokenAddress: string; tokenId: string; type: 'ERC1155'; amount?: string; // Will default to '1' } export type UserFacingSerializedSingleAssetDataTypes = | UserFacingERC20AssetDataSerialized | UserFacingERC721AssetDataSerialized | UserFacingERC1155AssetDataSerialized; export interface ERC20AssetDataSerialized { assetProxyId: string; tokenAddress: string; } export interface ERC721AssetDataSerialized { assetProxyId: string; tokenAddress: string; tokenId: string; } export interface ERC1155AssetDataSerialized { assetProxyId: string; tokenAddress: string; tokenIds: string[]; tokenValues: string[]; callbackData: string; } export type SerializedSingleAssetDataTypes = | ERC20AssetDataSerialized | ERC721AssetDataSerialized | ERC1155AssetDataSerialized; export type SerializedAvailableAssetDataTypes = | SerializedSingleAssetDataTypes | MultiAssetDataSerialized; export interface MultiAssetDataSerializedRecursivelyDecoded { assetProxyId: string; amounts: string[]; nestedAssetData: SerializedSingleAssetDataTypes[]; } export type SerializedAvailableAssetDataTypesDecoded = | SerializedSingleAssetDataTypes | MultiAssetDataSerializedRecursivelyDecoded; export enum ORDER_BUILDER_ERROR_CODES { MISSING_CONTRACT_WRAPPERS_ERROR = 'MISSING_CONTRACT_WRAPPERS_ERROR', } export enum SupportedTokenTypes { ERC20 = 'ERC20', ERC721 = 'ERC721', ERC1155 = 'ERC1155', } export type SupportedTokenTypesType = | SupportedTokenTypes.ERC20 | SupportedTokenTypes.ERC721 | SupportedTokenTypes.ERC1155; export interface TradeableAssetItem<TMetadata = any> { amount: string; userInputtedAmount?: string; assetData: SerializedSingleAssetDataTypes; type: SupportedTokenTypesType; id: string; // unique id metadata?: TMetadata; } // Convenience type wrappers export interface Erc20TradeableAsset extends TradeableAssetItem { assetData: ERC20AssetDataSerialized; type: SupportedTokenTypes.ERC20; } export interface Erc721TradeableAsset extends TradeableAssetItem { assetData: ERC721AssetDataSerialized; type: SupportedTokenTypes.ERC721; } export interface Erc1155TradeableAsset extends TradeableAssetItem { assetData: ERC1155AssetDataSerialized; type: SupportedTokenTypes.ERC1155; } export type AvailableTradeableAssets = | Erc20TradeableAsset | Erc721TradeableAsset | Erc1155TradeableAsset; export interface AdditionalOrderConfig { makerAddress: string; // only field required chainId?: number; takerAddress?: string; expiration?: Date | number; exchangeAddress?: string; salt?: string; feeRecipientAddress?: string; makerFeeAssetData?: string; takerFeeAssetData?: string; makerFee?: string; } export interface ZeroExOrder { makerAddress: string; takerAddress: string; feeRecipientAddress: string; senderAddress: string; makerAssetAmount: string; takerAssetAmount: string; makerFee: string; takerFee: string; expirationTimeSeconds: string; salt: string; makerAssetData: string; takerAssetData: string; makerFeeAssetData: string; takerFeeAssetData: string; } export interface ZeroExSignedOrder extends ZeroExOrder { signature: string; } export interface EipDomain { name: string; version: string; chainId: string; verifyingContract: string; } export interface TypedData { domain: EipDomain; types: { Order: { name: string; type: string; }[]; }; value: Order; } export const EIP712_TYPES = { Order: [ { name: 'makerAddress', type: 'address' }, { name: 'takerAddress', type: 'address' }, { name: 'feeRecipientAddress', type: 'address' }, { name: 'senderAddress', type: 'address' }, { name: 'makerAssetAmount', type: 'uint256' }, { name: 'takerAssetAmount', type: 'uint256' }, { name: 'makerFee', type: 'uint256' }, { name: 'takerFee', type: 'uint256' }, { name: 'expirationTimeSeconds', type: 'uint256' }, { name: 'salt', type: 'uint256' }, { name: 'makerAssetData', type: 'bytes' }, { name: 'takerAssetData', type: 'bytes' }, { name: 'makerFeeAssetData', type: 'bytes' }, { name: 'takerFeeAssetData', type: 'bytes' }, ], }; export type SwappableAsset = | UserFacingERC20AssetDataSerialized | UserFacingERC721AssetDataSerialized | UserFacingERC1155AssetDataSerializedNormalizedSingle; export enum RevertReason { OrderUnfillable = 'ORDER_UNFILLABLE', InvalidMaker = 'INVALID_MAKER', InvalidTaker = 'INVALID_TAKER', InvalidSender = 'INVALID_SENDER', InvalidOrderSignature = 'INVALID_ORDER_SIGNATURE', InvalidTakerAmount = 'INVALID_TAKER_AMOUNT', DivisionByZero = 'DIVISION_BY_ZERO', RoundingError = 'ROUNDING_ERROR', InvalidSignature = 'INVALID_SIGNATURE', SignatureIllegal = 'SIGNATURE_ILLEGAL', SignatureInvalid = 'SIGNATURE_INVALID', SignatureUnsupported = 'SIGNATURE_UNSUPPORTED', TakerOverpay = 'TAKER_OVERPAY', OrderOverfill = 'ORDER_OVERFILL', InvalidFillPrice = 'INVALID_FILL_PRICE', InvalidNewOrderEpoch = 'INVALID_NEW_ORDER_EPOCH', CompleteFillFailed = 'COMPLETE_FILL_FAILED', NegativeSpreadRequired = 'NEGATIVE_SPREAD_REQUIRED', ReentrancyIllegal = 'REENTRANCY_ILLEGAL', InvalidTxHash = 'INVALID_TX_HASH', InvalidTxSignature = 'INVALID_TX_SIGNATURE', FailedExecution = 'FAILED_EXECUTION', LengthGreaterThan0Required = 'LENGTH_GREATER_THAN_0_REQUIRED', LengthGreaterThan3Required = 'LENGTH_GREATER_THAN_3_REQUIRED', LengthGreaterThan131Required = 'LENGTH_GREATER_THAN_131_REQUIRED', Length0Required = 'LENGTH_0_REQUIRED', Length65Required = 'LENGTH_65_REQUIRED', InvalidAmount = 'INVALID_AMOUNT', TransferFailed = 'TRANSFER_FAILED', SenderNotAuthorized = 'SENDER_NOT_AUTHORIZED', TargetNotAuthorized = 'TARGET_NOT_AUTHORIZED', TargetAlreadyAuthorized = 'TARGET_ALREADY_AUTHORIZED', IndexOutOfBounds = 'INDEX_OUT_OF_BOUNDS', AuthorizedAddressMismatch = 'AUTHORIZED_ADDRESS_MISMATCH', OnlyContractOwner = 'ONLY_CONTRACT_OWNER', MakerNotWhitelisted = 'MAKER_NOT_WHITELISTED', TakerNotWhitelisted = 'TAKER_NOT_WHITELISTED', AssetProxyDoesNotExist = 'ASSET_PROXY_DOES_NOT_EXIST', LengthMismatch = 'LENGTH_MISMATCH', LibBytesGreaterThanZeroLengthRequired = 'GREATER_THAN_ZERO_LENGTH_REQUIRED', LibBytesGreaterOrEqualTo4LengthRequired = 'GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED', LibBytesGreaterOrEqualTo20LengthRequired = 'GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED', LibBytesGreaterOrEqualTo32LengthRequired = 'GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED', LibBytesGreaterOrEqualToNestedBytesLengthRequired = 'GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED', LibBytesGreaterOrEqualToSourceBytesLengthRequired = 'GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED', Erc20InsufficientBalance = 'ERC20_INSUFFICIENT_BALANCE', Erc20InsufficientAllowance = 'ERC20_INSUFFICIENT_ALLOWANCE', FeePercentageTooLarge = 'FEE_PERCENTAGE_TOO_LARGE', ValueGreaterThanZero = 'VALUE_GREATER_THAN_ZERO', InvalidMsgValue = 'INVALID_MSG_VALUE', InsufficientEthRemaining = 'INSUFFICIENT_ETH_REMAINING', Uint256Overflow = 'UINT256_OVERFLOW', Erc721ZeroToAddress = 'ERC721_ZERO_TO_ADDRESS', Erc721OwnerMismatch = 'ERC721_OWNER_MISMATCH', Erc721InvalidSpender = 'ERC721_INVALID_SPENDER', Erc721ZeroOwner = 'ERC721_ZERO_OWNER', Erc721InvalidSelector = 'ERC721_INVALID_SELECTOR', WalletError = 'WALLET_ERROR', ValidatorError = 'VALIDATOR_ERROR', InvalidFunctionSelector = 'INVALID_FUNCTION_SELECTOR', InvalidAssetData = 'INVALID_ASSET_DATA', InvalidAssetProxy = 'INVALID_ASSET_PROXY', UnregisteredAssetProxy = 'UNREGISTERED_ASSET_PROXY', TxFullyConfirmed = 'TX_FULLY_CONFIRMED', TxNotFullyConfirmed = 'TX_NOT_FULLY_CONFIRMED', TimeLockIncomplete = 'TIME_LOCK_INCOMPLETE', InvalidFreeMemoryPtr = 'INVALID_FREE_MEMORY_PTR', AuctionInvalidAmount = 'INVALID_AMOUNT', AuctionExpired = 'AUCTION_EXPIRED', AuctionNotStarted = 'AUCTION_NOT_STARTED', AuctionInvalidBeginTime = 'INVALID_BEGIN_TIME', InvalidAssetDataEnd = 'INVALID_ASSET_DATA_END', InvalidOrBlockedExchangeSelector = 'INVALID_OR_BLOCKED_EXCHANGE_SELECTOR', BalanceQueryFailed = 'BALANCE_QUERY_FAILED', AtLeastOneAddressDoesNotMeetBalanceThreshold = 'AT_LEAST_ONE_ADDRESS_DOES_NOT_MEET_BALANCE_THRESHOLD', FromLessThanToRequired = 'FROM_LESS_THAN_TO_REQUIRED', ToLessThanLengthRequired = 'TO_LESS_THAN_LENGTH_REQUIRED', InvalidApprovalSignature = 'INVALID_APPROVAL_SIGNATURE', ApprovalExpired = 'APPROVAL_EXPIRED', InvalidOrigin = 'INVALID_ORIGIN', AmountEqualToOneRequired = 'AMOUNT_EQUAL_TO_ONE_REQUIRED', BadReceiverReturnValue = 'BAD_RECEIVER_RETURN_VALUE', CannotTransferToAddressZero = 'CANNOT_TRANSFER_TO_ADDRESS_ZERO', InsufficientAllowance = 'INSUFFICIENT_ALLOWANCE', NFTNotOwnedByFromAddress = 'NFT_NOT_OWNED_BY_FROM_ADDRESS', OwnersAndIdsMustHaveSameLength = 'OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH', TokenAndValuesLengthMismatch = 'TOKEN_AND_VALUES_LENGTH_MISMATCH', TransferRejected = 'TRANSFER_REJECTED', Uint256Underflow = 'UINT256_UNDERFLOW', InvalidIdsOffset = 'INVALID_IDS_OFFSET', InvalidValuesOffset = 'INVALID_VALUES_OFFSET', InvalidDataOffset = 'INVALID_DATA_OFFSET', InvalidAssetDataLength = 'INVALID_ASSET_DATA_LENGTH', InvalidStaticCallDataOffset = 'INVALID_STATIC_CALL_DATA_OFFSET', TargetNotEven = 'TARGET_NOT_EVEN', UnexpectedStaticCallResult = 'UNEXPECTED_STATIC_CALL_RESULT', TransfersSuccessful = 'TRANSFERS_SUCCESSFUL', InsufficientFunds = 'INSUFFICIENT_FUNDS', TxAlreadyExecuted = 'TX_ALREADY_EXECUTED', DefaultTimeLockIncomplete = 'DEFAULT_TIME_LOCK_INCOMPLETE', CustomTimeLockIncomplete = 'CUSTOM_TIME_LOCK_INCOMPLETE', EqualLengthsRequired = 'EQUAL_LENGTHS_REQUIRED', OnlyCallableByWallet = 'ONLY_CALLABLE_BY_WALLET', } export type AvailableSignatureTypesV3 = 'eoa' | 'eip1271'; export interface SigningOptionsV3 { signatureType: AvailableSignatureTypesV3; // | 'autodetect' ? and remove autodetectSignatureType maybe? autodetectSignatureType: boolean; }
the_stack
module WinJSTests { "use strict"; var ListView = <typeof WinJS.UI.PrivateListView> WinJS.UI.ListView; var _oldMaxTimePerCreateContainers; var testRootEl, smallGroups = [], bigGroups = [], LAST_LETTER = 26, SMALL_GROUPS_COUNT = LAST_LETTER * 5, BIG_GROUPS_COUNT = LAST_LETTER * 15; function firstLetter(index, count) { var pom = index * LAST_LETTER / count, letterIndex = Math.floor(pom); return String.fromCharCode("A".charCodeAt(0) + letterIndex); } function createDataSource(array, async = false) { var dataSource = { itemsFromIndex: function (index, countBefore, countAfter) { return new WinJS.Promise(function (complete, error) { if (index >= 0 && index < array.length) { var startIndex = Math.max(0, index - countBefore), endIndex = Math.min(index + countAfter, array.length - 1), size = endIndex - startIndex + 1; var items = []; for (var i = startIndex; i < startIndex + size; i++) { items.push({ key: i.toString(), data: array[i] }); } var retVal = { items: items, offset: index - startIndex, totalCount: array.length, absoluteIndex: index }; if (async) { WinJS.Promise.timeout(50).then(function () { complete(retVal); }); } else { complete(retVal); } } else { complete({}); } }); }, getCount: function () { return new WinJS.Promise(function (complete) { if (async) { WinJS.Promise.timeout(50).then(function () { complete(array.length); }); } else { complete(array.length); } }); } }; return new WinJS.UI.ListDataSource(dataSource); } function checkTile(listView, groupIndex, index, left, top, caption?) { var tile = listView.elementFromIndex(index), container = Helper.ListView.containerFrom(tile), offsetXFromSurface = listView._rtl() ? Helper.ListView.offsetRightFromSurface : Helper.ListView.offsetLeftFromSurface; LiveUnit.Assert.areEqual(caption ? caption : (String.fromCharCode("A".charCodeAt(0) + groupIndex) + " tile " + index), tile.textContent.trim()); LiveUnit.Assert.areEqual(left, offsetXFromSurface(listView, container)); LiveUnit.Assert.areEqual(top, Helper.ListView.offsetTopFromSurface(listView, container)); } function checkHeader(listView, groupIndex, left, top, id, caption?) { var tile = document.getElementById(id + groupIndex), container = Helper.ListView.headerContainerFrom(listView, tile), offsetXFromSurface = listView._rtl() ? Helper.ListView.offsetRightFromSurface : Helper.ListView.offsetLeftFromSurface; LiveUnit.Assert.areEqual(caption ? caption : String.fromCharCode("A".charCodeAt(0) + groupIndex), tile.textContent.trim()); LiveUnit.Assert.areEqual(left, offsetXFromSurface(listView, container)); LiveUnit.Assert.areEqual(top, Helper.ListView.offsetTopFromSurface(listView, container)); return container; } function createListView(dataSource, options, id?, elementId?) { function firstLetter(item) { return item.data.text.toUpperCase().charAt(0); } function groupKey(item) { return firstLetter(item); } function groupData(item) { return { title: firstLetter(item) }; } var element = document.getElementById(elementId ? elementId : "groupTestList"), itemDataSource = WinJS.UI.computeDataSourceGroups(dataSource, groupKey, groupData), listView = new ListView(element, Helper.ListView.extend(options, { layout: Helper.ListView.extend(options.layout, { groupHeaderPosition: WinJS.UI.HeaderPosition.left }), itemDataSource: itemDataSource, itemTemplate: Helper.ListView.createRenderer("groupTestTemplate"), groupDataSource: itemDataSource.groups, groupHeaderTemplate: Helper.ListView.createRenderer("groupHeaderTemplate", id) })); return listView; } function trackState(element) { var listViewComplete, listViewCompletePromise = new WinJS.Promise(function (complete) { listViewComplete = complete; }); var listViewLoaded, listViewLoadedPromise = new WinJS.Promise(function (complete) { listViewLoaded = complete; }); var state: any = { states: [] }; function loadingStateChanged(eventObject) { var control = eventObject.target.winControl; state.states.push(control.loadingState); if (control.loadingState === "itemsLoaded") { listViewLoaded(); } else if (control.loadingState === "complete") { listViewComplete(); } } element.addEventListener("loadingstatechanged", loadingStateChanged, false); state.loadedPromise = listViewLoadedPromise; state.completePromise = WinJS.Promise.join([WinJS.Promise.timeout(500), listViewCompletePromise]).then(function () { element.removeEventListener("loadingstatechanged", loadingStateChanged, false); return state.states; }); return state; } export class GroupsTests { // This is the setup function that will be called at the beginning of each test function. setUp() { LiveUnit.LoggingCore.logComment("In setup"); smallGroups = []; bigGroups = []; for (var i = 0; i < SMALL_GROUPS_COUNT; ++i) { smallGroups.push({ text: firstLetter(i, SMALL_GROUPS_COUNT) + " tile " + i }); } for (i = 0; i < BIG_GROUPS_COUNT; ++i) { bigGroups.push({ text: firstLetter(i, BIG_GROUPS_COUNT) + " tile " + i }); } testRootEl = document.createElement("div"); testRootEl.className = "file-listview-css"; var newNode = document.createElement("div"); newNode.id = "GroupsTests"; newNode.innerHTML = "<div id='groupTestList' style='width:1000px; height:400px'></div>" + "<div id='groupRtlTestList' dir='rtl' style='width:1000px; height:400px'></div>" + "<div id='groupTestTemplate' style='display: none; width:100px; height:100px'>" + " <div>{{text}}</div>" + "</div>" + "<div id='groupHeaderTemplate' style='display: none; width:200px; height:200px'>" + " <div>{{title}}</div>" + "</div>" + "<div id='smallGroupHeaderTemplate' style='display: none; width:100px; height:100px'>" + " <div>{{title}}</div>" + "</div>"; testRootEl.appendChild(newNode); document.body.appendChild(testRootEl); _oldMaxTimePerCreateContainers = WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers; WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers = Number.MAX_VALUE; } tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers = _oldMaxTimePerCreateContainers; WinJS.Utilities.disposeSubTree(testRootEl); document.body.removeChild(testRootEl); WinJS.Utilities.stopLog(); Helper.cleanupUnhandledErrors(); } // Verifies that when you read indexOfFirstVisible after setting it, it returns the // value that you set it to. It verifies this under the following conditions: // - win-groupleader has no margins // - win-container has margins // This permits the first group on screen to not have any of its items' contents on // screen which is what triggered WinBlue#246863. testIndexOfFirstVisibleWithoutGroupMargins = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(bigGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI.GridLayout, groupHeaderPosition: WinJS.UI.HeaderPosition.top }, groupHeaderTemplate: Helper.ListView.createRenderer("smallGroupHeaderTemplate", "groupScrollTo") }); WinJS.Utilities.addClass(listView.element, "noGroupMargins"); var itemsPerGroup = 15, firstIndexOfGroup10 = itemsPerGroup * 10; Helper.ListView.runTests(listView, [ function () { // Verify the conditions required for triggering the bug. var groupHeaderContainer = listView.element.querySelector(".win-groupheadercontainer"); var itemsContainer = listView.element.querySelector(".win-itemscontainer"); var container = listView.element.querySelector(".win-container"); LiveUnit.Assert.areEqual("0px", getComputedStyle(groupHeaderContainer).marginLeft, "win-groupleader should have margin-left set to 0"); LiveUnit.Assert.areEqual("0px", getComputedStyle(itemsContainer).marginLeft, "win-groupleader should have margin-left set to 0"); LiveUnit.Assert.areEqual("5px", getComputedStyle(container).marginRight, "win-container should have a margin right of 5px"); listView.indexOfFirstVisible = firstIndexOfGroup10; }, function () { LiveUnit.Assert.areEqual(firstIndexOfGroup10, listView.indexOfFirstVisible, "indexOfFirstVisible returned a value different from the one it was set to"); complete(); } ]); }; // Verifies that indexOfLastVisible returns the correct value when the ListView // is scrolled such that the last visible thing is the last column of a partially // filled group. // Regression test for WinBlue#259740. testIndexOfLastVisibleInLastColumnOfAGroup = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(bigGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI.GridLayout, groupHeaderPosition: WinJS.UI.HeaderPosition.top }, groupHeaderTemplate: Helper.ListView.createRenderer("groupHeaderTemplate", "groupScrollTo") }); var itemsPerGroup = 15, lastIndexOfGroup9 = itemsPerGroup * 10 - 1; Helper.ListView.runTests(listView, [ function () { // Verify the conditions required for triggering the bug. LiveUnit.Assert.isTrue(itemsPerGroup % listView.layout['_itemsPerBar'] > 0, "The last column should have some empty rows"); // Ensure lastIndexOfGroup9 is visible so that we can inspect its offsetLeft and offsetWidth listView.ensureVisible(lastIndexOfGroup9); }, function () { // Scroll the ListView so that the last thing visible is the last column of group 9. var container = Helper.ListView.containerFrom(listView.elementFromIndex(lastIndexOfGroup9)); listView.scrollPosition = container.offsetLeft + container.offsetWidth - listView._getViewportLength(); }, function () { LiveUnit.Assert.areEqual(lastIndexOfGroup9, listView.indexOfLastVisible, "indexOfLastVisible is incorrect"); complete(); } ]); }; // Regression test for WinBlue:212689 testSwitchingFromNoStructureNodesToStructureNodesWithGroups = function (complete) { var list = new WinJS.Binding.List<{ startDate: Date; text: string; }>(); var element = document.getElementById("groupTestList"); element.style.width = "700px" var listView = new WinJS.UI.ListView(element); listView.itemTemplate = function (itemPromise) { return itemPromise.then(function (data) { var item = document.createElement("div"); item.textContent = data.data.text; item.style.height = "400px"; item.style.width = "100px"; return item; }); }; var groupTimelineList = list.createGrouped( function (event) { var startDate = event.startDate; var year = startDate.getFullYear(); var month = startDate.getMonth(); var day = startDate.getDate(); return "" + year + (month < 10 ? "0" + month : month.toString()) + (day < 10 ? "0" + day : day.toString()); }, function (event) { return event.startDate; }, function (leftKey, rightKey) { return leftKey.localeCompare(rightKey); }); listView.itemDataSource = groupTimelineList.dataSource; listView.groupDataSource = groupTimelineList.groups.dataSource; Helper.ListView.waitForDeferredAction(listView)().then(function () { WinJS.Utilities._setImmediate(function () { list.splice(0, 1, { startDate: new Date(2013, 4, 12, 5), text: "Fri 5am" }), list.splice(1, 1, { startDate: new Date(2013, 4, 12, 6), text: "Fri 6am" }), list.splice(2, 1, { startDate: new Date(2013, 4, 12, 10), text: "Fri 10am" }), list.splice(3, 1, { startDate: new Date(2013, 4, 12, 12), text: "Fri 12am" }), list.splice(4, 1, { startDate: new Date(2013, 4, 13, 8), text: "Sat 8am" }), list.splice(5, 1, { startDate: new Date(2013, 4, 13, 10), text: "Sat 10am" }), list.splice(6, 1, { startDate: new Date(2013, 4, 13, 16), text: "Sat 4pm" }), list.splice(7, 1, { startDate: new Date(2013, 4, 13, 17), text: "Sat 5pm" }) list.splice(8, 1, { startDate: new Date(2013, 4, 14, 15), text: "Sat 3pm" }) list.splice(9, 1, { startDate: new Date(2013, 4, 14, 14), text: "Sat 2pm" }) list.splice(10, 1, { startDate: new Date(2013, 4, 14, 13), text: "Sat 1pm" }) list.splice(11, 1, { startDate: new Date(2013, 4, 15, 14), text: "Sat 2pm" }) list.splice(12, 1, { startDate: new Date(2013, 4, 16, 15), text: "Sat 3pm" }) list.splice(13, 1, { startDate: new Date(2013, 4, 17, 16), text: "Sat 4pm" }) list.splice(14, 1, { startDate: new Date(2013, 4, 18, 17), text: "Sat 5pm" }) list.splice(15, 1, { startDate: new Date(2013, 4, 19, 18), text: "Sat 6pm" }) list.splice(16, 1, { startDate: new Date(2013, 4, 20, 19), text: "Sat 7pm" }) list.splice(17, 1, { startDate: new Date(2013, 4, 21, 20), text: "Sat 8pm" }) list.splice(18, 1, { startDate: new Date(2013, 4, 22, 21), text: "Sat 9pm" }) }); Helper.ListView.waitForDeferredAction(listView)().then(function () { list.splice(5, 1); Helper.ListView.waitForDeferredAction(listView)(400).then(function () { list.splice(2, 0, { startDate: new Date(2013, 4, 12, 11), text: "Fri 11am" }) Helper.ListView.waitForDeferredAction(listView)(400).then(complete); }); }); }); }; testCustomGroupDataSource = function (complete) { var flavors = [ { text: "Banana Blast", kind: "IC" }, { text: "Lavish Lemon Ice", kind: "ST" }, { text: "Marvelous Mint", kind: "IC" }, { text: "Creamy Orange", kind: "IC" }, { text: "Succulent Strawberry", kind: "ST" }, { text: "Very Vanilla", kind: "IC" }, { text: "Banana Blast", kind: "FY" }, { text: "Lavish Lemon Ice", kind: "ST" }, { text: "Marvelous Mint", kind: "GO" }, { text: "Creamy Orange", kind: "ST" }, { text: "Succulent Strawberry", kind: "IC" }, ]; var desertTypes: any = [ { key: "IC", title: "Ice Cream" }, { key: "FY", title: "Low-fat frozen yogurt" }, { key: "ST", title: "Sorbet" }, { key: "GO", title: "Gelato" } ]; // // Flavors Data Adapter // // Data adapter for items. Follows the same pattern as the Bing Search adapter. The main concerns when // creating a data adapter for grouping are: // * Listview works on an item-first mechanism, so the items need to be sorted and already arranged by group. // * Supply the key for the group using the groupKey property for each item // var flavorsDataAdapter = WinJS.Class.define( function (data) { // Constructor this._itemData = data; }, // Data Adapter interface methods // These define the contract between the virtualized datasource and the data adapter. // These methods will be called by virtualized datasource to fetch items, count etc. { // This example only implements the itemsFromIndex and count methods // Called to get a count of the items, result should be a promise for the items getCount: function () { var that = this; return WinJS.Promise.wrap(that._itemData.length); }, // Called by the virtualized datasource to fetch items // It will request a specific item index and hints for a number of items either side of it // The implementation should return the specific item, and can choose how many either side. // to also send back. It can be more or less than those requested. // // Must return back an object containing fields: // items: The array of items of the form: // [{ key: key1, groupKey: group1, data : { field1: value, field2: value, ... }}, { key: key2, groupKey: group1, data : {...}}, ...] // offset: The offset into the array for the requested item // totalCount: (optional) Update the count for the collection itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; if (requestIndex >= that._itemData.length) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist.toString())); } var lastFetchIndex = Math.min(requestIndex + countAfter, that._itemData.length - 1); var fetchIndex = Math.max(requestIndex - countBefore, 0); var results = []; // iterate and form the collection of items for (var i = fetchIndex; i <= lastFetchIndex; i++) { var item = that._itemData[i]; results.push({ key: i.toString(), // the key for the item itself groupKey: item.kind, // the key for the group for the item data: item // the data fields for the item }); } // return a promise for the results return WinJS.Promise.wrap({ items: results, // The array of items offset: requestIndex - fetchIndex, // The offset into the array for the requested item totalCount: that._itemData.length // the total count }); } }); // Create a DataSource by deriving and wrapping the data adapter with a VirtualizedDataSource var flavorsDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (data) { this._baseDataSourceConstructor(new flavorsDataAdapter(data)); }); // // Groups Data Adapter // // Data adapter for the groups. Follows the same pattern as the items data adapter, but each item is a group. // The main concerns when creating a data adapter for groups are: // * Groups can be enumerated by key or index, so the adapter needs to implement both itemsFromKey and itemsFromIndex // * Each group should supply a firstItemIndexHint which is the index of the first item in the group. This enables listview // to figure out the position of an item in the group so it can get the columns correct. // var desertsDataAdapter = WinJS.Class.define( function (groupData) { // Constructor this._groupData = groupData; }, // Data Adapter interface methods // These define the contract between the virtualized datasource and the data adapter. // These methods will be called by virtualized datasource to fetch items, count etc. { // This example only implements the itemsFromIndex, itemsFromKey and count methods // Called to get a count of the items, this can be async so return a promise for the count getCount: function () { var that = this; return WinJS.Promise.wrap(that._groupData.length); }, // Called by the virtualized datasource to fetch a list of the groups based on group index // It will request a specific group and hints for a number of groups either side of it // The implementation should return the specific group, and can choose how many either side // to also send back. It can be more or less than those requested. // // Must return back an object containing fields: // items: The array of groups of the form: // [{ key: groupkey1, firstItemIndexHint: 0, data : { field1: value, field2: value, ... }}, { key: groupkey2, firstItemIndexHint: 27, data : {...}}, ... // offset: The offset into the array for the requested group // totalCount: (optional) an update of the count of items itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; if (requestIndex >= that._groupData.length) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist.toString())); } var lastFetchIndex = Math.min(requestIndex + countAfter, that._groupData.length - 1); var fetchIndex = Math.max(requestIndex - countBefore, 0); var results = []; // form the array of groups for (var i = fetchIndex; i <= lastFetchIndex; i++) { var group = that._groupData[i]; results.push({ key: group.key, firstItemIndexHint: group.firstItemIndex, data: group }); } return WinJS.Promise.wrap({ items: results, // The array of items offset: requestIndex - fetchIndex, // The offset into the array for the requested item totalCount: that._groupData.length // The total count }); }, // Called by the virtualized datasource to fetch groups based on the group's key // It will request a specific group and hints for a number of groups either side of it // The implementation should return the specific group, and can choose how many either side // to also send back. It can be more or less than those requested. // // Must return back an object containing fields: // [{ key: groupkey1, firstItemIndexHint: 0, data : { field1: value, field2: value, ... }}, { key: groupkey2, firstItemIndexHint: 27, data : {...}}, ... // offset: The offset into the array for the requested group // absoluteIndex: the index into the list of groups of the requested group // totalCount: (optional) an update of the count of items itemsFromKey: function (requestKey, countBefore, countAfter) { var that = this; var requestIndex = null; // Find the group in the collection for (var i = 0, len = that._groupData.length; i < len; i++) { if (that._groupData[i].key === requestKey) { requestIndex = i; break; } } if (requestIndex === null) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist.toString())); } var lastFetchIndex = Math.min(requestIndex + countAfter, that._groupData.length - 1); var fetchIndex = Math.max(requestIndex - countBefore, 0); var results = []; //iterate and form the collection of the results for (var j = fetchIndex; j <= lastFetchIndex; j++) { var group = that._groupData[j]; results.push({ key: group.key, // The key for the group firstItemIndexHint: group.firstItemIndex, // The index into the items for the first item in the group data: group // The data for the specific group }); } // Results can be async so the result is supplied as a promise return WinJS.Promise.wrap({ items: results, // The array of items offset: requestIndex - fetchIndex, // The offset into the array for the requested item absoluteIndex: requestIndex, // The index into the collection of the item referenced by key totalCount: that._groupData.length // The total length of the collection }); }, }); // Create a DataSource by deriving and wrapping the data adapter with a VirtualizedDataSource var desertsDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (data) { this._baseDataSourceConstructor(new desertsDataAdapter(data)); }); // form an array of the keys to help with the sort var groupKeys = []; for (var i = 0; i < desertTypes.length; i++) { groupKeys[i] = desertTypes[i].key; } var itemData = flavors; itemData.sort(function CompareForSort(item1, item2) { var first = groupKeys.indexOf(item1.kind), second = groupKeys.indexOf(item2.kind); if (first === second) { return item1.text.localeCompare(item2.text); } else if (first < second) { return -1; } else { return 1; } }); // Calculate the indexes of the first item for each group, ideally this should also be done at the source of the data var itemIndex = 0; for (var j = 0, len = desertTypes.length; j < len; j++) { desertTypes[j].firstItemIndex = itemIndex; var key = desertTypes[j].key; for (var k = itemIndex, len2 = itemData.length; k < len2; k++) { if (itemData[k].kind !== key) { itemIndex = k; break; } } } // Create the datasources that will then be set on the datasource var itemDataSource = new flavorsDataSource(itemData); var groupDataSource = new desertsDataSource(desertTypes); var listView = new WinJS.UI.ListView(document.getElementById("groupTestList"), { itemDataSource: itemDataSource, groupDataSource: groupDataSource, itemTemplate: Helper.ListView.createRenderer("groupTestTemplate"), groupHeaderTemplate: Helper.ListView.createRenderer("groupHeaderTemplate") }); return Helper.ListView.waitForReady(listView, -1)().then(function () { checkTile(listView, 0, 0, 50, 200, "Banana Blast"); complete(); }); }; testRequestGroupBeforeListViewReady = function (complete) { var data = []; for (var i = 0; i < 100; i++) { data.push({ data: i + "" }); } var list = new WinJS.Binding.List(data); var glist = list.createGrouped(function (item) { return Math.floor(item.data / 10) + ""; }, function (item) { return { data: Math.floor(item.data / 10) + "" }; }); var lv = new ListView(); lv.itemDataSource = glist.dataSource; lv.groupDataSource = glist.groups.dataSource; testRootEl.appendChild(lv.element); lv._groups.requestHeader(0).then(function () { testRootEl.removeChild(lv.element); complete(); }); }; }; function generateSimpleLayout(layout) { GroupsTests.prototype["testSimpleLayout" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var listView = createListView(createDataSource(smallGroups), { layout: { type: WinJS.UI[layout] } }, "groupSimpleLayout"); Helper.ListView.whenLoadingComplete(listView, function () { // first group checkHeader(listView, 0, 50, 0, "groupSimpleLayout"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupSimpleLayout"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); complete(); }); }; }; generateSimpleLayout("GridLayout"); function generateSimpleLayoutAsyncDataSource(layout) { GroupsTests.prototype["testSimpleLayoutAsyncDataSource" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var listView = createListView(createDataSource(smallGroups, true), { layout: { type: WinJS.UI[layout] } }, "groupSimpleLayoutAsyncDataSource"); Helper.ListView.whenLoadingComplete(listView, function () { // first group checkHeader(listView, 0, 50, 0, "groupSimpleLayoutAsyncDataSource"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupSimpleLayoutAsyncDataSource"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); complete(); }); }; }; generateSimpleLayoutAsyncDataSource("GridLayout"); function generateSimpleLayoutAsyncRenderer(layout) { GroupsTests.prototype["testSimpleLayoutAsyncRenderer" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var listView = createListView(createDataSource(smallGroups, true), { layout: { type: WinJS.UI[layout] }, itemTemplate: Helper.ListView.createAsyncRenderer("groupTestTemplate", 100, 100), groupHeaderTemplate: Helper.ListView.createAsyncRenderer("groupHeaderTemplate", 200, 200, "groupSimpleLayoutAsyncRenderer") }); Helper.ListView.whenLoadingComplete(listView, function () { // first group checkHeader(listView, 0, 50, 0, "groupSimpleLayoutAsyncRenderer"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupSimpleLayoutAsyncRenderer"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); complete(); }); }; }; generateSimpleLayoutAsyncRenderer("GridLayout"); function generateHeaderAbove(layout) { GroupsTests.prototype["testHeaderAbove" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var myData = [], c = 0; function addGroup(letter, count) { for (var i = 0; i < count; ++i) { myData.push({ text: letter + " tile " + c }); c++; } } addGroup("A", 5); addGroup("B", 5); addGroup("C", 1); addGroup("D", 4); addGroup("E", 10); var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(myData); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout], groupHeaderPosition: WinJS.UI.HeaderPosition.top } }, "groupHeaderAbove"); Helper.ListView.whenLoadingComplete(listView, function () { // first group var header = checkHeader(listView, 0, 50, 0, "groupHeaderAbove"); LiveUnit.Assert.areEqual(300, header.offsetWidth); checkTile(listView, 0, 0, 50, 200); checkTile(listView, 0, 1, 50, 300); checkTile(listView, 0, 4, 250, 200); // second group checkHeader(listView, 1, 400, 0, "groupHeaderAbove"); checkTile(listView, 1, 5, 400, 200); checkTile(listView, 1, 6, 400, 300); checkTile(listView, 1, 9, 600, 200); header = checkHeader(listView, 2, 750, 0, "groupHeaderAbove"); LiveUnit.Assert.areEqual(100, header.offsetWidth); header = checkHeader(listView, 3, 900, 0, "groupHeaderAbove"); LiveUnit.Assert.areEqual(200, header.offsetWidth); complete(); }); }; }; generateHeaderAbove("GridLayout"); function generateRtl(layout) { GroupsTests.prototype["testRtl" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(smallGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] } }, "groupRtlTestList", "groupRtlTestList"); Helper.ListView.whenLoadingComplete(listView, function () { // first group checkHeader(listView, 0, 50, 0, "groupRtlTestList"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupRtlTestList"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); complete(); }); }; }; generateRtl("GridLayout"); function generateScrollTo(layout) { GroupsTests.prototype["testScrollTo" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(bigGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] }, groupHeaderTemplate: Helper.ListView.createRenderer("smallGroupHeaderTemplate", "groupScrollTo") }); Helper.ListView.runTests(listView, [ function () { checkHeader(listView, 0, 50, 0, "groupScrollTo"); checkTile(listView, 0, 0, 150, 0); listView.indexOfFirstVisible = 106; }, function () { var element = document.getElementById("groupTestList"), viewportElement = Helper.ListView.viewport(element), scrollOffset = WinJS.Utilities.getScrollPosition(viewportElement).scrollLeft; checkHeader(listView, 7, scrollOffset - 50, 0, "groupScrollTo"); checkTile(listView, 7, 105, scrollOffset + 50, 0); checkTile(listView, 7, 106, scrollOffset + 50, 100); checkTile(listView, 7, 109, scrollOffset + 150, 0); complete(); } ]); }; }; generateScrollTo("GridLayout"); function generateScrollLeft(layout) { GroupsTests.prototype["testScrollLeft" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(bigGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] }, groupHeaderTemplate: Helper.ListView.createRenderer("smallGroupHeaderTemplate", "groupScrollLeft") }), element = document.getElementById("groupTestList"), viewportElement = Helper.ListView.viewport(element); Helper.ListView.runTests(listView, [ function () { checkHeader(listView, 0, 50, 0, "groupScrollLeft"); checkTile(listView, 0, 0, 150, 0); listView.indexOfFirstVisible = 340; return true; }, function () { var position = WinJS.Utilities.getScrollPosition(viewportElement); position.scrollLeft = position.scrollLeft - viewportElement.offsetWidth; LiveUnit.Assert.areEqual(338, listView.indexOfFirstVisible); // Verify that we have realized content for the item checkTile(listView, 22, 338, 12450, 0); LiveUnit.LoggingCore.logComment("scrolling from " + WinJS.Utilities.getScrollPosition(viewportElement).scrollLeft + " to " + position.scrollLeft); WinJS.Utilities.setScrollPosition(viewportElement, position); return true; }, function () { //LiveUnit.Assert.areEqual(337, listView.lastVisible()); LiveUnit.LoggingCore.logComment("scrollPos=" + WinJS.Utilities.getScrollPosition(viewportElement).scrollLeft + " lastVisible=" + listView.indexOfLastVisible); complete(); } ]); }; }; generateScrollLeft("GridLayout"); function generateAdd(layout) { GroupsTests.prototype["testAdd" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(smallGroups); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] } }, "groupAdd"); Helper.ListView.runTests(listView, [ function () { // first group checkHeader(listView, 0, 50, 0, "groupAdd"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupAdd"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); Helper.ListView.getDataObjects(listView.itemDataSource, [5]).done(function (dataObjects) { listView.itemDataSource.beginEdits(); listView.itemDataSource.insertBefore(null, { text: "A NewTile" }, dataObjects[0].key); listView.itemDataSource.insertBefore(null, { text: "A NewTile" }, dataObjects[0].key); listView.itemDataSource.insertBefore(null, { text: "A NewTile" }, dataObjects[0].key); listView.itemDataSource.insertBefore(null, { text: "A NewTile" }, dataObjects[0].key); listView.itemDataSource.endEdits(); }); return true; }, function () { checkHeader(listView, 0, 50, 0, "groupAdd"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); checkTile(listView, 0, 5, 350, 100, "A NewTile"); checkTile(listView, 0, 6, 350, 200, "A NewTile"); checkTile(listView, 0, 7, 350, 300, "A NewTile"); checkTile(listView, 0, 8, 450, 0, "A NewTile"); // second group checkHeader(listView, 1, 600, 0, "groupAdd"); checkTile(listView, 1, 9, 800, 0, "B tile 5"); checkTile(listView, 1, 10, 800, 100, "B tile 6"); complete(); } ]); }; }; generateAdd("GridLayout"); function generateAddGroup(layout) { GroupsTests.prototype["testAddGroup" + (layout == "GridLayout" ? "" : layout)] = function (complete) { function test(itemDataSource, groupDataSource, edit) { return new WinJS.Promise(function (testComplete) { var listView = new WinJS.UI.ListView(document.getElementById("groupTestList"), { layout: { type: WinJS.UI[layout] }, itemDataSource: itemDataSource, itemTemplate: Helper.ListView.createRenderer("groupTestTemplate"), groupDataSource: groupDataSource, groupHeaderTemplate: Helper.ListView.createRenderer("smallGroupHeaderTemplate", "groupAddGroup") }); Helper.ListView.runTests(listView, [ function () { // first group checkHeader(listView, 0, 50, 0, "groupAddGroup"); checkTile(listView, 0, 0, 50, 100); checkTile(listView, 0, 1, 50, 200); checkTile(listView, 0, 2, 50, 300); checkTile(listView, 0, 3, 150, 100); checkTile(listView, 0, 4, 150, 200); // second group checkHeader(listView, 1, 300, 0, "groupAddGroup", "C"); checkTile(listView, 1, 5, 300, 100, "C tile 5"); edit(); return true; }, function () { // first group checkHeader(listView, 0, 50, 0, "groupAddGroup"); checkTile(listView, 0, 0, 50, 100); checkTile(listView, 0, 1, 50, 200); checkTile(listView, 0, 2, 50, 300); checkTile(listView, 0, 3, 150, 100); checkTile(listView, 0, 4, 150, 200); // new group checkHeader(listView, 1, 300, 0, "groupAddGroup", "B"); checkTile(listView, 1, 5, 300, 100, "B New tile"); // third group checkHeader(listView, 2, 450, 0, "groupAddGroup", "C"); checkTile(listView, 2, 6, 450, 100, "C tile 5"); listView.forceLayout(); return true; }, function () { // first group checkHeader(listView, 0, 50, 0, "groupAddGroup"); checkTile(listView, 0, 0, 50, 100); // new group checkHeader(listView, 1, 300, 0, "groupAddGroup", "B"); checkTile(listView, 1, 5, 300, 100, "B New tile"); testComplete(); } ]); }); } function getData() { var myData = [], c = 0; function addGroup(letter, count) { for (var i = 0; i < count; ++i) { myData.push({ text: letter + " tile " + c }); c++; } } addGroup("A", 5); addGroup("C", 5); addGroup("D", 5); return myData; } var list = (new WinJS.Binding.List(getData())).createGrouped(function (item) { return item.text.charAt(0); }, function (item) { return { title: item.text.charAt(0) }; }); var dataSource = WinJS.UI.computeDataSourceGroups(Helper.ItemsManager.simpleSynchronousArrayDataSource(getData()), function (item) { return item.data.text.charAt(0); }, function (item) { return { title: item.data.text.charAt(0) }; }); function editList() { list.splice(5, 0, { text: "B New tile" }); } function editDataSource() { Helper.ListView.getDataObjects(dataSource, [5]).then(function (dataObjects) { dataSource.insertBefore(null, { text: "B New tile" }, dataObjects[0].key); }); } test(list.dataSource, list.groups.dataSource, editList).then(function () { return test(dataSource, dataSource.groups, editDataSource); }).then(function () { complete(); }); }; }; generateAddGroup("GridLayout"); function generateDelete(layout) { GroupsTests.prototype["testDelete" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(smallGroups); var i, listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] } }, "groupDelete"); Helper.ListView.waitForReady(listView, -1)().then(function () { // first group checkHeader(listView, 0, 50, 0, "groupDelete"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); checkTile(listView, 0, 4, 350, 0); // second group checkHeader(listView, 1, 500, 0, "groupDelete"); checkTile(listView, 1, 5, 700, 0); checkTile(listView, 1, 6, 700, 100); checkTile(listView, 1, 9, 800, 0); Helper.ListView.getDataObjects(listView.itemDataSource, [1, 2, 3, 4]).then(function (dataObjects) { listView.itemDataSource.beginEdits(); for (i = 0; i < dataObjects.length; ++i) { listView.itemDataSource.remove(dataObjects[i].key); } listView.itemDataSource.endEdits(); }); return Helper.ListView.waitForState(listView, "viewPortLoaded", -1)() }).then(function () { var headerContainer = <any>listView.element.querySelector(".win-groupheadercontainer"); LiveUnit.Assert.areEqual(1, headerContainer.children.length); return Helper.ListView.waitForReady(listView, -1)(); }).then(function () { // first group checkHeader(listView, 0, 50, 0, "groupDelete"); checkTile(listView, 0, 0, 250, 0); // second group checkHeader(listView, 1, 400, 0, "groupDelete"); checkTile(listView, null, 1, 600, 0, "B tile 5"); checkTile(listView, null, 2, 600, 100, "B tile 6"); checkTile(listView, null, 5, 700, 0, "B tile 9"); Helper.ListView.getDataObjects(listView.itemDataSource, [0]).then(function (dataObjects) { listView.itemDataSource.remove(dataObjects[0].key); }); listView._raiseViewLoading(); return Helper.ListView.waitForReady(listView, -1)(); }).then(function () { checkHeader(listView, 0, 50, 0, "groupDelete", "B"); checkTile(listView, null, 0, 250, 0, "B tile 5"); checkTile(listView, null, 1, 250, 100, "B tile 6"); checkTile(listView, null, 4, 350, 0, "B tile 9"); complete(); }); }; }; generateDelete("GridLayout"); function generateDeleteAll(layout) { GroupsTests.prototype["testDeleteAll" + (layout == "GridLayout" ? "" : layout)] = function (complete) { function test(itemDataSource, groupDataSource) { return new WinJS.Promise(function (testComplete) { var listView = new WinJS.UI.ListView(document.getElementById("groupTestList"), { layout: { type: WinJS.UI[layout], groupHeaderPosition: WinJS.UI.HeaderPosition.left }, itemDataSource: itemDataSource, itemTemplate: Helper.ListView.createRenderer("groupTestTemplate"), groupDataSource: groupDataSource, groupHeaderTemplate: Helper.ListView.createRenderer("groupHeaderTemplate", "groupDeleteAll") }); Helper.ListView.runTests(listView, [ function () { // first group checkHeader(listView, 0, 50, 0, "groupDeleteAll"); checkTile(listView, 0, 0, 250, 0); checkTile(listView, 0, 1, 250, 100); // second group checkHeader(listView, 1, 400, 0, "groupDeleteAll"); checkTile(listView, 1, 2, 600, 0); Helper.ListView.getDataObjects(listView.itemDataSource, [0, 1, 2]).then(function (dataObjects) { listView.itemDataSource.beginEdits(); for (var i = 0; i < dataObjects.length; ++i) { listView.itemDataSource.remove(dataObjects[i].key); } listView.itemDataSource.endEdits(); }); return true; }, function () { LiveUnit.Assert.areEqual(0, listView.element.querySelectorAll(".win-container").length); LiveUnit.Assert.areEqual(0, listView.element.querySelectorAll(".win-groupheader").length); testComplete(); } ]); }); } function getData() { return [ { text: "A tile 0" }, { text: "A tile 1" }, { text: "B tile 2" } ]; } var list = (new WinJS.Binding.List(getData())).createGrouped(function (item) { return item.text.charAt(0); }, function (item) { return { title: item.text.charAt(0) }; }); test(list.dataSource, list.groups.dataSource).then(function () { var dataSource = WinJS.UI.computeDataSourceGroups(Helper.ItemsManager.simpleSynchronousArrayDataSource(getData()), function (item) { return item.data.text.charAt(0); }, function (item) { return { title: item.data.text.charAt(0) }; }); return test(dataSource, dataSource.groups); }).then(function () { complete(); }); }; }; generateDeleteAll("GridLayout"); function generateReload(layout) { GroupsTests.prototype["testReload" + (layout == "GridLayout" ? "" : layout)] = function (complete) { function checkTileLabel(listView, index, caption) { var tile = listView.elementFromIndex(index); LiveUnit.Assert.areEqual(caption, tile.textContent.trim()); } function checkHeaderLabel(listView, id, groupIndex, caption) { var tile = document.getElementById(id + groupIndex); LiveUnit.Assert.areEqual(caption, tile.textContent.trim()); } var myData = [], c = 0; function addGroup(letter, count) { for (var i = 0; i < count; ++i) { myData.push({ text: letter + " tile " + c }); c++; } } addGroup("A", 3); addGroup("B", 3); var dataSource = Helper.ItemsManager.simpleSynchronousArrayDataSource(myData); var listView = createListView(dataSource, { layout: { type: WinJS.UI[layout] } }, "groupReload"); var tests = [ function () { listView.currentItem = { index: 4 }; LiveUnit.Assert.areEqual(4, listView.currentItem.index, "ListView's currentItem wasn't set properly"); checkTileLabel(listView, 0, "A tile 0"); checkTileLabel(listView, 3, "B tile 3"); checkHeaderLabel(listView, "groupReload", 0, "A"); checkHeaderLabel(listView, "groupReload", 1, "B"); myData = []; c = 0; addGroup("C", 2); addGroup("D", 2); var items = []; for (var i = 0; i < myData.length; i++) { items.push({ key: i.toString(), data: myData[i] }); } listView.itemDataSource['testDataAdapter'].replaceItems(items); listView.itemDataSource['testDataAdapter'].reload(); }, function () { Helper.ListView.validateResetFocusState(listView, "after calling reload"); checkTileLabel(listView, 0, "C tile 0"); checkTileLabel(listView, 2, "D tile 2"); checkHeaderLabel(listView, "groupReload", 0, "C"); checkHeaderLabel(listView, "groupReload", 1, "D"); complete(); } ]; Helper.ListView.runTests(listView, tests); }; }; generateReload("GridLayout"); var correctStates = ["itemsLoading", "viewPortLoaded", "itemsLoaded", "complete"]; function generateLoadingStateEmpty(layout) { GroupsTests.prototype["testLoadingStateEmpty" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var element = document.getElementById("groupTestList"); var state = trackState(element); var list = new WinJS.Binding.List([]); var listView = new WinJS.UI.ListView(element, { layout: { type: WinJS.UI[layout] }, itemDataSource: list.dataSource, itemTemplate: Helper.ListView.createRenderer("groupTestTemplate") }); state.completePromise.then(function (states) { Helper.ListView.elementsEqual(correctStates, states); complete(); }); }; }; generateLoadingStateEmpty("GridLayout"); function generateLoadingStateSync(layout) { GroupsTests.prototype["testLoadingStateSync" + (layout == "GridLayout" ? "" : layout)] = function (complete) { WinJS.Utilities.startLog({ action: function (message, tag, type) { LiveUnit.LoggingCore.logComment(type + ": " + message + " (" + tag + ")"); } }); var element = document.getElementById("groupTestList"); var state = trackState(element); var listView = new ListView(element, { layout: { type: WinJS.UI[layout] }, itemDataSource: createDataSource(smallGroups), itemTemplate: Helper.ListView.createRenderer("groupTestTemplate") }); state.completePromise.then(function (states) { Helper.ListView.elementsEqual(correctStates, states); var state = trackState(listView._element); listView.indexOfFirstVisible = 70; return state.completePromise; }).then(function (states) { Helper.ListView.elementsEqual(correctStates, states); var state = trackState(listView._element); listView.scrollPosition = listView.scrollPosition + 5; return state.completePromise; }).then(function (states) { Helper.ListView.elementsEqual(correctStates, states); WinJS.Utilities.stopLog(); }).then(null, function () { WinJS.Utilities.stopLog(); }). done(complete); }; }; generateLoadingStateSync("GridLayout"); function generateLoadingStateAsync(layout) { GroupsTests.prototype["testLoadingStateAsync" + (layout == "GridLayout" ? "" : layout)] = function (complete) { WinJS.Utilities.startLog({ action: function (message, tag, type) { LiveUnit.LoggingCore.logComment(type + ": " + message + " (" + tag + ")"); } }); var element = document.getElementById("groupTestList"); var state = trackState(element); var listView = new WinJS.UI.ListView(element, { layout: { type: WinJS.UI[layout] }, itemDataSource: createDataSource(smallGroups, true), itemTemplate: Helper.ListView.createAsyncRenderer("groupTestTemplate", 100, 100, "", 500) }); state.loadedPromise.then(function (states) { //checkTile(listView, 0, 1, 0, 100, "Loading"); return state.completePromise; }).then(function (states) { Helper.ListView.elementsEqual(correctStates, states); checkTile(listView, 0, 1, 0, 100); WinJS.Utilities.stopLog(); }). then(null, function () { WinJS.Utilities.stopLog(); }). done(complete); }; }; generateLoadingStateAsync("GridLayout"); function generateGroupFocusAfterDataSourceMutation(layout) { GroupsTests.prototype["testGroupFocusAfterDataSourceMutation" + (layout == "GridLayout" ? "" : layout)] = function (complete) { var data = []; for (var i = 0; i < 100; i++) { data.push({ data: i + "" }); } var list = new WinJS.Binding.List(data); var glist = list.createGrouped(function (item) { return Math.floor(item.data / 10) + ""; }, function (item) { return { data: Math.floor(item.data / 10) + "" }; }); var element = document.getElementById("groupTestList"); var listView = new WinJS.UI.ListView(element, { layout: { type: WinJS.UI[layout] }, itemDataSource: glist.dataSource, groupDataSource: glist.groups.dataSource }); var header = null; Helper.ListView.waitForReady(listView)(). then(function () { listView.currentItem = { type: WinJS.UI.ObjectType.groupHeader, index: 0, hasFocus: true }; header = listView.element.querySelector(".win-groupheader"); LiveUnit.Assert.areEqual(header, document.activeElement); listView.itemDataSource.remove("8"); return Helper.ListView.waitForReady(listView, -1)(); }).done(function () { LiveUnit.Assert.isTrue(document.activeElement && document.activeElement !== header && document.activeElement === listView.element.querySelector(".win-groupheader")); complete(); }); }; }; generateGroupFocusAfterDataSourceMutation("GridLayout"); function generateRealizeRenderDuringScrolling(layout) { var testName = "testRealizeRenderAndResetDuringScrolling" + (layout == "GridLayout" ? "" : layout); GroupsTests.prototype[testName] = function (complete) { Helper.initUnhandledErrors(); var refItems = {}; var stopScrolling = false; var failures = 0; var scrollPosition = 0; WinJS.Utilities.startLog({ action: function (message, tag, type) { LiveUnit.LoggingCore.logComment(type + ": " + message + " (" + tag + ")"); } }); function getItemTemplate() { var realRenderer = Helper.ListView.createAsyncRenderer("groupTestTemplate", 200, 200, "", 1000); return function (itemPromise) { itemPromise.then(function (item) { if (item.key) { if (refItems[item.key]) { failures++; } else { refItems[item.key] = item; } } }); return realRenderer(itemPromise); }; } var element = document.getElementById("groupTestList"); var state = trackState(element); var listView = new ListView(element, { layout: new WinJS.UI[layout](), itemDataSource: createDataSource(bigGroups, true), itemTemplate: getItemTemplate() }); function scrollListView() { if (!stopScrolling && document.body.contains(listView.element)) { var scrollProperty = listView.layout.orientation === WinJS.UI.Orientation.horizontal ? "scrollLeft" : "scrollTop"; scrollPosition += 10; var newPos: any = {}; newPos[scrollProperty] = scrollPosition; WinJS.Utilities.setScrollPosition(listView._viewport, newPos); setTimeout(scrollListView, 16); } } scrollListView(); state.loadedPromise. then(function (states) { return state.completePromise; }). then(function () { return WinJS.Promise.timeout(16).then(function () { scrollPosition = listView.scrollPosition = 4000; }); }). then(function () { LiveUnit.Assert.areEqual(0, failures); }). then(function () { return WinJS.Promise.timeout(16).then(function () { scrollPosition = listView.scrollPosition = 14100; }); }). then(function () { return WinJS.Promise.timeout(16).then(function () { scrollPosition = listView.scrollPosition = 14400; }); }). then(function () { return WinJS.Promise.timeout(16).then(function () { scrollPosition = listView.scrollPosition = 14150; stopScrolling = true; }); }). then(Helper.validateUnhandledErrorsOnIdle). done(function () { WinJS.Utilities.stopLog(); complete(); }); }; GroupsTests.prototype[testName].timeout = 60000; }; generateRealizeRenderDuringScrolling("GridLayout"); function generateLoadingStateScrolling(layout) { var testName = "testLoadingStateScrolling" + (layout == "GridLayout" ? "" : layout); GroupsTests.prototype[testName] = function (complete) { WinJS.Utilities.startLog({ action: function (message, tag, type) { LiveUnit.LoggingCore.logComment(type + ": " + message + " (" + tag + ")"); } }); var element = document.getElementById("groupTestList"); var state = trackState(element); var listView = new ListView(element, { layout: { type: WinJS.UI[layout] }, itemDataSource: createDataSource(smallGroups, true), itemTemplate: Helper.ListView.createRenderer("groupTestTemplate") }); var stopScrolling = false; var failedEvents = 0; var scrollPosition = 0; function scrollListView() { if (!stopScrolling && document.body.contains(listView.element)) { var scrollProperty = listView.layout.orientation === WinJS.UI.Orientation.horizontal ? "scrollLeft" : "scrollTop"; scrollPosition += 5; var newPos: any = {}; newPos[scrollProperty] = scrollPosition; WinJS.Utilities.setScrollPosition(listView._viewport, newPos); setTimeout(scrollListView, 16); } } scrollListView(); listView.addEventListener("loadingstatechanged", function () { if (!stopScrolling) { if (listView.loadingState !== 'itemsLoading') { var indexOfFirstVisible = listView.indexOfFirstVisible; var indexOfLastVisible = listView.indexOfLastVisible; var firstElement = listView.elementFromIndex(indexOfFirstVisible); var lastElement = listView.elementFromIndex(indexOfLastVisible); if (!firstElement || !lastElement) { failedEvents++; } } } }); state.loadedPromise. then(function (states) { stopScrolling = true; return state.completePromise; }). then(function (states) { LiveUnit.Assert.areEqual(0, failedEvents); }). then(Helper.validateUnhandledErrorsOnIdle) .done(function () { WinJS.Utilities.stopLog(); complete(); }); }; GroupsTests.prototype[testName].timeout = 60000; }; generateLoadingStateScrolling("GridLayout"); } // register the object as a test class by passing in the name LiveUnit.registerTestClass("WinJSTests.GroupsTests");
the_stack
import test from 'ava'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonProperty} from '../src/decorators/JsonProperty'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {JsonTypeInfo, JsonTypeInfoAs, JsonTypeInfoId} from '../src/decorators/JsonTypeInfo'; import {JsonSubTypes} from '../src/decorators/JsonSubTypes'; import {JacksonError} from '../src/core/JacksonError'; import {JsonCreator} from '../src/decorators/JsonCreator'; import {JsonIdentityInfo, ObjectIdGenerator} from '../src/decorators/JsonIdentityInfo'; test('DeserializationFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; constructor(UserID: number) { this.id = UserID; } } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.ACCEPT_CASE_INSENSITIVE_PROPERTIES = true; // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"USERID":1,"eMaIl":"john.alfa@gmail.com","firstName":"John","lastName":"Alfa"}', { mainCreator: () => [User], }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); }); test('DeserializationFeature.ALLOW_COERCION_OF_SCALARS set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [BigInt]}) age: BigInt; @JsonProperty() @JsonClassType({type: () => [Boolean]}) active: boolean; @JsonProperty() @JsonClassType({type: () => [Boolean]}) deleted: boolean; } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.ALLOW_COERCION_OF_SCALARS = true; // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":"1","email":"john.alfa@gmail.com","age":45,"active":"false","deleted":1}', { mainCreator: () => [User], }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.age, BigInt(45)); t.is(userParsed.active, false); t.is(userParsed.deleted, true); }); test('DeserializationFeature.FAIL_ON_INVALID_SUBTYPE set to false', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { } class Cat extends Animal { } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_INVALID_SUBTYPE = false; const animalsParsed = objectMapper.parse<Array<Animal>>( '[{"name":"Arthur","@type":"WrongTypeDog"},{"name":"Merlin","@type":"Cat"}]', {mainCreator: () => [Array, [Animal]]}); t.assert(animalsParsed instanceof Array); t.is(animalsParsed.length, 2); t.assert(animalsParsed[0] instanceof Animal); t.assert(!(animalsParsed[0] instanceof Dog)); t.is(animalsParsed[0].name, 'Arthur'); t.assert(animalsParsed[1] instanceof Cat); t.is(animalsParsed[1].name, 'Merlin'); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_INVALID_SUBTYPE = true; const errFailOnInvalidSubtype = t.throws<JacksonError>(() => { objectMapper.parse<Array<Animal>>( '[{"name":"Arthur","@type":"WrongTypeDog"},{"name":"Merlin","@type":"Cat"}]', {mainCreator: () => [Array, [Animal]]}); }); t.assert(errFailOnInvalidSubtype instanceof JacksonError); }); test('DeserializationFeature.FAIL_ON_MISSING_TYPE_ID set to false', t => { @JsonTypeInfo({ use: JsonTypeInfoId.NAME, include: JsonTypeInfoAs.PROPERTY }) @JsonSubTypes({ types: [ {class: () => Dog}, {class: () => Cat}, ] }) class Animal { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { } class Cat extends Animal { } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_MISSING_TYPE_ID = false; const animalsParsed = objectMapper.parse<Array<Animal>>( '[{"name":"Arthur"},{"name":"Merlin"}]', {mainCreator: () => [Array, [Animal]]}); t.assert(animalsParsed instanceof Array); t.is(animalsParsed.length, 2); t.assert(animalsParsed[0] instanceof Animal); t.assert(!(animalsParsed[0] instanceof Dog)); t.is(animalsParsed[0].name, 'Arthur'); t.assert(animalsParsed[1] instanceof Animal); t.assert(!(animalsParsed[1] instanceof Cat)); t.is(animalsParsed[1].name, 'Merlin'); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_MISSING_TYPE_ID = true; const errFailOnMissinTypeId = t.throws<JacksonError>(() => { objectMapper.parse<Array<Animal>>( '[{"name":"Arthur"},{"name":"Merlin"}]', {mainCreator: () => [Array, [Animal]]}); }); t.assert(errFailOnMissinTypeId instanceof JacksonError); }); test('DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) otherInfo: Array<string>; } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT = true; const userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfo":[]}', { mainCreator: () => [User] }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.otherInfo, null); }); test('DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Map, [String, String]]}) otherInfoMap: Map<string, string> = new Map(); @JsonProperty() @JsonClassType({type: () => [Object, [String, String]]}) otherInfoObjLiteral: {phone?: string; address?: string} = {}; } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT = true; // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"","otherInfoMap":{"phone":""},"otherInfoObjLiteral":{"address":""}}', { mainCreator: () => [User] }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, null); t.assert(userParsed.otherInfoMap instanceof Map); t.is(userParsed.otherInfoMap.get('phone'), null); t.is(userParsed.otherInfoObjLiteral.address, null); }); test('DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES set to false', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_UNKNOWN_PROPERTIES = false; const userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","unknownProperty": true}', { mainCreator: () => [User] }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(!Object.hasOwnProperty.call(userParsed, 'unknownProperty')); }); test('DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_NULL_FOR_PRIMITIVES = true; const errFailOnNullForPrimitives = t.throws<JacksonError>(() => { objectMapper.parse<User>('{"id":null,"firstname":"John","lastname":"Alfa"}', { mainCreator: () => [User] }); }); t.assert(errFailOnNullForPrimitives instanceof JacksonError); }); test('DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES set to true', t => { @JsonCreator() class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_MISSING_CREATOR_PROPERTIES = true; const errFailOnNullForPrimitives = t.throws<JacksonError>(() => { objectMapper.parse<User>('{"firstname":"John","lastname":"Alfa"}', { mainCreator: () => [User] }); }); t.assert(errFailOnNullForPrimitives instanceof JacksonError); }); test('DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES set to true', t => { @JsonCreator() class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_NULL_CREATOR_PROPERTIES = true; const errFailOnNullForPrimitives = t.throws<JacksonError>(() => { objectMapper.parse<User>('{"id":null,"firstname":"John","lastname":"Alfa"}', { mainCreator: () => [User] }); }); t.assert(errFailOnNullForPrimitives instanceof JacksonError); }); test('DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS set to false', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } } const objectMapper = new ObjectMapper(); objectMapper.defaultParserContext.features.deserialization.FAIL_ON_UNRESOLVED_OBJECT_IDS = false; // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"items":[{"id":1,"name":"Book","owner":2}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}', { mainCreator: () => [User] }); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 1); t.assert(userParsed.items[0] instanceof Item); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Book'); // @ts-ignore t.is(userParsed.items[0].owner, null); });
the_stack
import {NativePath, npath, PortablePath, ppath, xfs} from '@yarnpkg/fslib'; import {createTemporaryFolder} from 'pkg-tests-core/sources/utils/fs'; import {yarn} from 'pkg-tests-core'; export type Manifest = { name: string; main?: string; exports?: string | object; }; export async function writeTestPackage(path: PortablePath, manifest: Manifest, files: Array<string>) { await yarn.writePackage(path, {...manifest, version: `1.0.0`}); await Promise.all((files as Array<PortablePath>).map(async file => { const p = ppath.join(path, file); await xfs.mkdirpPromise(ppath.dirname(p)); await xfs.writeFilePromise(p, `module.exports = __filename;\n`); })); } export type Assertions = { pass?: Array<[/*request: */string, /*resolved: */string]>, fail?: Array<[/*request: */string, /*error: */string | {message: string, code?: string, pnpCode?: string}]>, }; export function makeTemporaryExportsEnv(testPackageName: string, manifest: Omit<Manifest, 'name'>, files: Array<string>, {pass, fail}: Assertions) { return makeTemporaryEnv({ dependencies: { [testPackageName]: `file:./${testPackageName}`, }, }, async ({path, run, source}) => { await writeTestPackage(`${path}/${testPackageName}` as PortablePath, { name: testPackageName, ...manifest, }, files); await run(`install`); const makeScript = (request: string) => `require(${JSON.stringify(request)})`; const getPathRelativeToPackageRoot = (filename: NativePath) => { const match = /node_modules\/.+?\/(.+)$/.exec(ppath.relative(path, npath.toPortablePath(filename))); if (match === null) throw new Error(`Assertion failed: Expected the match to be successful`); return match[1] as PortablePath; }; const sourceRequest = (request: string) => source(makeScript(interpolateVariables(request))).then(p => getPathRelativeToPackageRoot(p as any)); const interpolateVariables = (input: string) => input.replace(`$PKG`, testPackageName); if (typeof pass !== `undefined`) { for (const [request, file] of pass) { await expect(sourceRequest(request)).resolves.toBe(interpolateVariables(file)); } } if (typeof fail !== `undefined`) { for (const [request, message] of fail) { const actualMessage = typeof message === `string` ? message : message.message; await expect(sourceRequest(request)).rejects.toMatchObject({ externalException: { ...(typeof message === `object` ? message : {}), message: expect.stringContaining(interpolateVariables(actualMessage)), }, }); } } }); } describe(`"exports" field`, () => { test( `implicit "main" field`, makeTemporaryExportsEnv(`main-implicit`, {}, [ `index.js`, `index.mjs`, `file.js`, ], { pass: [ [`$PKG`, `index.js`], [`$PKG/file`, `file.js`], ], }), ); test( `dotted "main" field`, makeTemporaryExportsEnv(`main-dotted`, { main: `./file.js`, }, [ `index.js`, `index.mjs`, `file.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/index`, `index.js`], ], }), ); test( `dotless "main" field`, makeTemporaryExportsEnv(`main-dotless`, { main: `file.js`, }, [ `index.js`, `index.mjs`, `file.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/index`, `index.js`], ], }), ); test( `dot-slash "main" field`, makeTemporaryExportsEnv(`main-dot-slash`, { main: `./`, }, [ `index.js`, `index.mjs`, `file.js`, ], { pass: [ [`$PKG`, `index.js`], [`$PKG/file`, `file.js`], ], }), ); test( `string "exports" field`, makeTemporaryExportsEnv(`exports-string`, { exports: `./file.js`, }, [ `index.js`, `index.mjs`, `file.js`, ], { pass: [ [`$PKG`, `file.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], ], }), ); test( `"main" field and string "exports" field`, makeTemporaryExportsEnv(`main-exports-string`, { main: `main.js`, exports: `./file.js`, }, [ `index.js`, `index.mjs`, `main.js`, `file.js`, ], { pass: [ [`$PKG`, `file.js`], ], fail: [ [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/index`, `Missing "./index" export in "$PKG" package`], ], }), ); test( `top-level object conditional "exports" field`, makeTemporaryExportsEnv(`exports-top-level-object`, { exports: { import: `./import.mjs`, node: `./node.js`, require: `./require.js`, default: `./default.js`, }, }, [ `index.js`, `index.mjs`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `node.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `"main" field and top-level object conditional "exports" field`, makeTemporaryExportsEnv(`main-exports-top-level-object`, { main: `main.js`, exports: { import: `./import.mjs`, node: `./node.js`, require: `./require.js`, default: `./default.js`, }, }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `node.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `dot object conditional "exports" field`, makeTemporaryExportsEnv(`exports-dot-object`, { exports: { [`.`]: { import: `./import.mjs`, node: `./node.js`, require: `./require.js`, default: `./default.js`, }, }, }, [ `index.js`, `index.mjs`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `node.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `"main" field and dot object conditional "exports" field`, makeTemporaryExportsEnv(`main-exports-dot-object`, { main: `main.js`, exports: { [`.`]: { import: `./import.mjs`, node: `./node.js`, require: `./require.js`, default: `./default.js`, }, }, }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `node.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `dot object conditional "exports" field with nested conditions`, makeTemporaryExportsEnv(`exports-dot-object`, { exports: { [`.`]: { node: { import: `./import.mjs`, require: `./require.js`, }, default: `./default.js`, }, }, }, [ `index.js`, `index.mjs`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `require.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `"main" field and dot object conditional "exports" field with nested conditions`, makeTemporaryExportsEnv(`main-exports-dot-object`, { main: `main.js`, exports: { [`.`]: { node: { import: `./import.mjs`, require: `./require.js`, }, default: `./default.js`, }, }, }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `node.js`, `require.js`, `default.js`, ], { pass: [ [`$PKG`, `require.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/node`, `Missing "./node" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `top-level array fallback "exports" field`, makeTemporaryExportsEnv(`exports-top-level-object`, { exports: [ {import: `./import.mjs`}, `default.js`, ], }, [ `index.js`, `index.mjs`, `import.mjs`, `default.js`, ], { pass: [ [`$PKG`, `default.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `"main" field and top-level array fallback "exports" field`, makeTemporaryExportsEnv(`main-exports-top-level-object`, { main: `main.js`, exports: [ {import: `./import.mjs`}, `default.js`, ], }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `default.js`, ], { pass: [ [`$PKG`, `default.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `dot object array fallback "exports" field`, makeTemporaryExportsEnv(`exports-top-level-object`, { exports: { [`.`]: [ {import: `./import.mjs`}, `default.js`, ], }, }, [ `index.js`, `index.mjs`, `import.mjs`, `default.js`, ], { pass: [ [`$PKG`, `default.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `"main" field and dot object array fallback "exports" field`, makeTemporaryExportsEnv(`main-exports-top-level-object`, { main: `main.js`, exports: { [`.`]: [ {import: `./import.mjs`}, `default.js`, ], }, }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `default.js`, ], { pass: [ [`$PKG`, `default.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/import`, `Missing "./import" export in "$PKG" package`], [`$PKG/default`, `Missing "./default" export in "$PKG" package`], ], }), ); test( `object subpath "exports" field`, makeTemporaryExportsEnv(`exports-object-subpath`, { exports: { [`.`]: `file.js`, [`./submodule`]: `./lib/submodule`, }, }, [ `index.js`, `index.mjs`, `file.js`, `lib/submodule.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/submodule`, `lib/submodule.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], ], }), ); test( `"main" field object subpath "exports" field`, makeTemporaryExportsEnv(`main-exports-object-subpath`, { main: `main.js`, exports: { [`.`]: `file.js`, [`./submodule`]: `./lib/submodule`, }, }, [ `index.js`, `index.mjs`, `main.js`, `file.js`, `lib/submodule.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/submodule`, `lib/submodule.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], ], }), ); test( `object subpath patterns "exports" field`, makeTemporaryExportsEnv(`exports-object-subpath-patterns`, { exports: { [`.`]: `file.js`, [`./src/*`]: `./lib/*`, }, }, [ `index.js`, `index.mjs`, `file.js`, `lib/a.js`, `lib/b.js`, `lib/c.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/src/a`, `lib/a.js`], [`$PKG/src/b`, `lib/b.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], [`$PKG/src`, `Missing "./src" export in "$PKG" package`], [`$PKG/src/`, `Missing "./src/" export in "$PKG" package`], [`$PKG/lib/c`, `Missing "./lib/c" export in "$PKG" package`], [`$PKG/src/d`, { code: `MODULE_NOT_FOUND`, message: `Qualified path resolution failed`, pnpCode: `QUALIFIED_PATH_RESOLUTION_FAILED`, }], ], }), ); test( `"main" field and object subpath patterns "exports" field`, makeTemporaryExportsEnv(`main-exports-object-subpath-patterns`, { main: `main.js`, exports: { [`.`]: `file.js`, [`./src/*`]: `./lib/*`, }, }, [ `index.js`, `index.mjs`, `main.js`, `file.js`, `lib/a.js`, `lib/b.js`, `lib/c.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/src/a`, `lib/a.js`], [`$PKG/src/b`, `lib/b.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], [`$PKG/src`, `Missing "./src" export in "$PKG" package`], [`$PKG/src/`, `Missing "./src/" export in "$PKG" package`], [`$PKG/lib/c`, `Missing "./lib/c" export in "$PKG" package`], [`$PKG/src/d`, { code: `MODULE_NOT_FOUND`, message: `Qualified path resolution failed`, pnpCode: `QUALIFIED_PATH_RESOLUTION_FAILED`, }], ], }), ); // Deprecated by Node, will eventually be removed test( `object subpath folder mappings "exports" field`, makeTemporaryExportsEnv(`exports-object-subpath-folder-mappings`, { exports: { [`.`]: `file.js`, [`./src/`]: `./lib/`, }, }, [ `index.js`, `index.mjs`, `file.js`, `lib/index.js`, `lib/a.js`, `lib/b.js`, `lib/c.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/src/`, `lib/index.js`], [`$PKG/src/a`, `lib/a.js`], [`$PKG/src/b`, `lib/b.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], [`$PKG/src`, `Missing "./src" export in "$PKG" package`], [`$PKG/lib/c`, `Missing "./lib/c" export in "$PKG" package`], [`$PKG/src/d`, { code: `MODULE_NOT_FOUND`, message: `Qualified path resolution failed`, pnpCode: `QUALIFIED_PATH_RESOLUTION_FAILED`, }], ], }), ); // Deprecated by Node, will eventually be removed test( `"main" field and object subpath subpath folder mappings "exports" field`, makeTemporaryExportsEnv(`main-exports-object-subpath-folder-mappings`, { main: `main.js`, exports: { [`.`]: `file.js`, [`./src/`]: `./lib/`, }, }, [ `index.js`, `index.mjs`, `main.js`, `file.js`, `lib/index.js`, `lib/a.js`, `lib/b.js`, `lib/c.js`, ], { pass: [ [`$PKG`, `file.js`], [`$PKG/src/`, `lib/index.js`], [`$PKG/src/a`, `lib/a.js`], [`$PKG/src/b`, `lib/b.js`], ], fail: [ [`$PKG/index`, `Missing "./index" export in "$PKG" package`], [`$PKG/main`, `Missing "./main" export in "$PKG" package`], [`$PKG/inexistent`, `Missing "./inexistent" export in "$PKG" package`], [`$PKG/src`, `Missing "./src" export in "$PKG" package`], [`$PKG/lib/c`, `Missing "./lib/c" export in "$PKG" package`], [`$PKG/src/d`, { code: `MODULE_NOT_FOUND`, message: `Qualified path resolution failed`, pnpCode: `QUALIFIED_PATH_RESOLUTION_FAILED`, }], ], }), ); test( `only import top-level object conditional "exports" field`, makeTemporaryExportsEnv(`exports-top-level-object-only-import`, { exports: { node: { import: `./node-import.mjs`, }, import: `./import.mjs`, }, }, [ `index.js`, `index.mjs`, `import.mjs`, `node-import.mjs`, ], { fail: [ [`$PKG`, `No known conditions for "." entry in "$PKG" package`], ], }), ); test( `main field and only import top-level object conditional "exports" field`, makeTemporaryExportsEnv(`main-exports-top-level-object-only-import`, { main: `main.js`, exports: { node: { import: `./node-import.mjs`, }, import: `./import.mjs`, }, }, [ `index.js`, `index.mjs`, `main.js`, `import.mjs`, `node-import.mjs`, ], { fail: [ [`$PKG`, `No known conditions for "." entry in "$PKG" package`], ], }), ); test( `manifest not exported`, makeTemporaryExportsEnv(`manifest-not-exported`, { exports: `./file.js`, }, [ `index.js`, `index.mjs`, `file.js`, ], { fail: [ [`$PKG/package.json`, `Missing "./package.json" export in "$PKG" package`], ], }), ); test( `self-referencing with exports`, makeTemporaryEnv({ name: `pkg`, exports: { [`.`]: `./main.js`, [`./foo`]: `./bar.js`, }, }, async ({path, run, source}) => { await run(`install`); await xfs.writeFilePromise(`${path}/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${path}/bar.js` as PortablePath, ``); await expect(source(`require.resolve('pkg')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/main.js`)); await expect(source(`require.resolve('pkg/foo')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/bar.js`)); await expect(source(`require.resolve('pkg/bar')`)).rejects.toMatchObject({ externalException: { message: expect.stringContaining(`Missing "./bar" export in "pkg" package`), }, }); }), ); test( `link: with exports (inside the project)`, makeTemporaryEnv({}, async ({path, run, source}) => { await xfs.mkdirPromise(`${path}/linked` as PortablePath); await xfs.writeJsonPromise(`${path}/linked/package.json` as PortablePath, { name: `linked`, exports: { [`.`]: `./main.js`, [`./foo`]: `./bar.js`, }, }); await xfs.writeFilePromise(`${path}/linked/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${path}/linked/bar.js` as PortablePath, ``); await xfs.writeJsonPromise(`${path}/package.json` as PortablePath, { name: `pkg`, dependencies: { [`linked`]: `link:./linked`, }, exports: { [`.`]: `./main.js`, [`./foo`]: `./bar.js`, }, }); await xfs.writeFilePromise(`${path}/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${path}/bar.js` as PortablePath, ``); await run(`install`); await expect(source(`require.resolve('linked')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/linked/main.js`)); await expect(source(`require.resolve('linked/foo')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/linked/bar.js`)); }), ); test( `link: with exports (outside the project)`, makeTemporaryEnv({}, async ({path, run, source}) => { const tmp = await createTemporaryFolder(); await xfs.writeJsonPromise(`${tmp}/package.json` as PortablePath, { name: `linked`, exports: { [`.`]: `./main.js`, [`./foo`]: `./bar.js`, }, }); await xfs.writeFilePromise(`${tmp}/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${tmp}/bar.js` as PortablePath, ``); await xfs.writeJsonPromise(`${path}/package.json` as PortablePath, { name: `pkg`, dependencies: { [`linked`]: `link:${tmp}`, }, exports: { [`.`]: `./main.js`, [`./foo`]: `./bar.js`, }, }); await xfs.writeFilePromise(`${path}/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${path}/bar.js` as PortablePath, ``); await run(`install`); await expect(source(`require.resolve('linked')`)).resolves.toStrictEqual(npath.fromPortablePath(`${tmp}/main.js`)); await expect(source(`require.resolve('linked/foo')`)).resolves.toStrictEqual(npath.fromPortablePath(`${tmp}/bar.js`)); }), ); test( `pnpIgnorePatterns with exports (issuer ignored)`, makeTemporaryEnv( {}, { pnpIgnorePatterns: `foo/**`, }, async ({path, run, source}) => { await xfs.writeJsonPromise(`${path}/package.json` as PortablePath, { name: `pkg`, exports: { [`.`]: `./main.js`, }, }); await run(`install`); await xfs.writeFilePromise(`${path}/main.js` as PortablePath, ``); await xfs.mkdirpPromise(`${path}/node_modules/dep` as PortablePath); await xfs.writeJsonPromise(`${path}/node_modules/dep/package.json` as PortablePath, { name: `dep`, exports: { [`.`]: `./main.js`, }, }); await xfs.writeFilePromise(`${path}/node_modules/dep/main.js` as PortablePath, ``); await xfs.mkdirPromise(`${path}/foo` as PortablePath); await xfs.writeFilePromise(`${path}/foo/node-resolution.js` as PortablePath, `module.exports = require.resolve('dep');\n`); await expect(source(`require('./foo/node-resolution')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/node_modules/dep/main.js`)); }, ), ); // TODO: write a better, self-contained test test( `pnpIgnorePatterns with exports (subpath ignored)`, async () => { expect(require.resolve(`@yarnpkg/monorepo/.yarn/sdks/typescript/lib/tsserver.js`)).toStrictEqual(npath.join(__dirname, `../../../../.yarn/sdks/typescript/lib/tsserver.js`)); }, ); test( `pnpapi with exports`, makeTemporaryEnv({ name: `pkg`, exports: { [`.`]: `./main.js`, // require.resolve(`pnpapi`) shouldn't be remappable [`pnpapi`]: `./pnpapi.js`, [`.pnp.cjs`]: `./pnpapi.js`, }, }, async ({path, run, source}) => { await run(`install`); await xfs.writeFilePromise(`${path}/main.js` as PortablePath, ``); await xfs.writeFilePromise(`${path}/pnpapi.js` as PortablePath, `module.exports = 'pnpapi.js';`); // require goes through Module._load which doesn't call resolveRequest if the request is `pnpapi` await expect(source(`require('pnpapi')`)).resolves.toHaveProperty(`VERSIONS`); // require.resolve goes through Module._resolveFilename which calls resolveRequest await expect(source(`require.resolve('pnpapi')`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/.pnp.cjs`)); await expect(source(`require('pnpapi').resolveToUnqualified('pnpapi', null)`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/.pnp.cjs`)); await expect(source(`require('pnpapi').resolveRequest('pnpapi', null)`)).resolves.toStrictEqual(npath.fromPortablePath(`${path}/.pnp.cjs`)); }), ); });
the_stack
import PluginSDK from "PluginSDK"; import AppDispatcher from "#SRC/js/events/AppDispatcher"; import Config from "#SRC/js/config/Config"; import CosmosPackagesStore from "#SRC/js/stores/CosmosPackagesStore"; import GetSetBaseStore from "#SRC/js/stores/GetSetBaseStore"; import { REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR, REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, REQUEST_MARATHON_DEPLOYMENTS_ERROR, REQUEST_MARATHON_DEPLOYMENTS_SUCCESS, REQUEST_MARATHON_GROUP_CREATE_ERROR, REQUEST_MARATHON_GROUP_CREATE_SUCCESS, REQUEST_MARATHON_GROUP_DELETE_ERROR, REQUEST_MARATHON_GROUP_DELETE_SUCCESS, REQUEST_MARATHON_GROUP_EDIT_ERROR, REQUEST_MARATHON_GROUP_EDIT_SUCCESS, REQUEST_MARATHON_GROUPS_ERROR, REQUEST_MARATHON_GROUPS_SUCCESS, REQUEST_MARATHON_INSTANCE_INFO_ERROR, REQUEST_MARATHON_INSTANCE_INFO_SUCCESS, REQUEST_MARATHON_POD_INSTANCE_KILL_ERROR, REQUEST_MARATHON_POD_INSTANCE_KILL_SUCCESS, REQUEST_MARATHON_QUEUE_ERROR, REQUEST_MARATHON_QUEUE_SUCCESS, REQUEST_MARATHON_SERVICE_CREATE_ERROR, REQUEST_MARATHON_SERVICE_CREATE_SUCCESS, REQUEST_MARATHON_SERVICE_DELETE_ERROR, REQUEST_MARATHON_SERVICE_DELETE_SUCCESS, REQUEST_MARATHON_SERVICE_EDIT_ERROR, REQUEST_MARATHON_SERVICE_EDIT_SUCCESS, REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR, REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS, REQUEST_MARATHON_SERVICE_RESTART_ERROR, REQUEST_MARATHON_SERVICE_RESTART_SUCCESS, REQUEST_MARATHON_SERVICE_VERSION_ERROR, REQUEST_MARATHON_SERVICE_VERSION_SUCCESS, REQUEST_MARATHON_SERVICE_VERSIONS_ERROR, REQUEST_MARATHON_SERVICE_VERSIONS_SUCCESS, REQUEST_MARATHON_TASK_KILL_ERROR, REQUEST_MARATHON_TASK_KILL_SUCCESS, } from "../constants/ActionTypes"; import DeploymentsList from "../structs/DeploymentsList"; import HealthStatus from "../constants/HealthStatus"; import MarathonActions from "../events/MarathonActions"; import { MARATHON_APPS_CHANGE, MARATHON_APPS_ERROR, MARATHON_DEPLOYMENT_ROLLBACK_ERROR, MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, MARATHON_DEPLOYMENTS_CHANGE, MARATHON_DEPLOYMENTS_ERROR, MARATHON_GROUP_CREATE_ERROR, MARATHON_GROUP_CREATE_SUCCESS, MARATHON_GROUP_DELETE_ERROR, MARATHON_GROUP_DELETE_SUCCESS, MARATHON_GROUP_EDIT_ERROR, MARATHON_GROUP_EDIT_SUCCESS, MARATHON_GROUPS_CHANGE, MARATHON_GROUPS_ERROR, MARATHON_INSTANCE_INFO_ERROR, MARATHON_INSTANCE_INFO_SUCCESS, MARATHON_POD_INSTANCE_KILL_SUCCESS, MARATHON_POD_INSTANCE_KILL_ERROR, MARATHON_QUEUE_CHANGE, MARATHON_QUEUE_ERROR, MARATHON_SERVICE_CREATE_ERROR, MARATHON_SERVICE_CREATE_SUCCESS, MARATHON_SERVICE_DELETE_ERROR, MARATHON_SERVICE_DELETE_SUCCESS, MARATHON_SERVICE_EDIT_ERROR, MARATHON_SERVICE_EDIT_SUCCESS, MARATHON_SERVICE_RESET_DELAY_ERROR, MARATHON_SERVICE_RESET_DELAY_SUCCESS, MARATHON_SERVICE_RESTART_ERROR, MARATHON_SERVICE_RESTART_SUCCESS, MARATHON_SERVICE_VERSION_CHANGE, MARATHON_SERVICE_VERSION_ERROR, MARATHON_SERVICE_VERSIONS_CHANGE, MARATHON_SERVICE_VERSIONS_ERROR, MARATHON_TASK_KILL_ERROR, MARATHON_TASK_KILL_SUCCESS, } from "../constants/EventTypes"; import Framework from "../structs/Framework"; import Application from "../structs/Application"; import ServiceImages from "../constants/ServiceImages"; import ServiceTree from "../structs/ServiceTree"; import ServiceValidatorUtil from "../utils/ServiceValidatorUtil"; let requestInterval: NodeJS.Timeout | null = null; let shouldEmbedLastUnusedOffers = false; function startPolling() { if (requestInterval == null) { poll(); requestInterval = window.setInterval(poll, Config.getRefreshRate()); } } function stopPolling() { if (requestInterval != null) { window.clearInterval(requestInterval); requestInterval = null; } } function poll() { MarathonActions.fetchGroups(); MarathonActions.fetchQueue( shouldEmbedLastUnusedOffers ? { params: "?embed=lastUnusedOffers" } : {} ); MarathonActions.fetchDeployments(); } class MarathonStore extends GetSetBaseStore<{ apps: Record<string, unknown>; deployments: unknown; groups: unknown; info: unknown; }> { storeID = "marathon"; createGroup = MarathonActions.createGroup; deleteGroup = MarathonActions.deleteGroup; editGroup = MarathonActions.editGroup; createService = MarathonActions.createService; deleteService = MarathonActions.deleteService; editService = MarathonActions.editService; resetDelayedService = MarathonActions.resetDelayedService; restartService = MarathonActions.restartService; fetchQueue = MarathonActions.fetchQueue; fetchServiceVersion = MarathonActions.fetchServiceVersion; fetchServiceVersions = MarathonActions.fetchServiceVersions; fetchMarathonInstanceInfo = MarathonActions.fetchMarathonInstanceInfo; killPodInstances = MarathonActions.killPodInstances; killTasks = MarathonActions.killTasks; constructor() { super(); this.getSet_data = { apps: {}, deployments: new DeploymentsList(), groups: new ServiceTree(), info: {}, }; PluginSDK.addStoreConfig({ store: this, storeID: this.storeID, events: { appsSuccess: MARATHON_APPS_CHANGE, appsError: MARATHON_APPS_ERROR, deploymentsSuccess: MARATHON_DEPLOYMENTS_CHANGE, deploymentsError: MARATHON_DEPLOYMENTS_ERROR, deploymentRollbackSuccess: MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, deploymentRollbackError: MARATHON_DEPLOYMENT_ROLLBACK_ERROR, instanceInfoSuccess: MARATHON_INSTANCE_INFO_SUCCESS, instanceInfoError: MARATHON_INSTANCE_INFO_ERROR, groupCreateSuccess: MARATHON_GROUP_CREATE_SUCCESS, groupCreateError: MARATHON_GROUP_CREATE_ERROR, groupDeleteSuccess: MARATHON_GROUP_DELETE_SUCCESS, groupDeleteError: MARATHON_GROUP_DELETE_ERROR, groupEditSuccess: MARATHON_GROUP_EDIT_SUCCESS, groupEditError: MARATHON_GROUP_EDIT_ERROR, groupsSuccess: MARATHON_GROUPS_CHANGE, groupsError: MARATHON_GROUPS_ERROR, podInstanceKillSuccess: MARATHON_POD_INSTANCE_KILL_SUCCESS, podInstanceKillError: MARATHON_POD_INSTANCE_KILL_ERROR, serviceCreateError: MARATHON_SERVICE_CREATE_ERROR, serviceCreateSuccess: MARATHON_SERVICE_CREATE_SUCCESS, serviceDeleteError: MARATHON_SERVICE_DELETE_ERROR, serviceDeleteSuccess: MARATHON_SERVICE_DELETE_SUCCESS, serviceEditError: MARATHON_SERVICE_EDIT_ERROR, serviceEditSuccess: MARATHON_SERVICE_EDIT_SUCCESS, serviceResetDelayError: MARATHON_SERVICE_RESET_DELAY_ERROR, serviceResetDelaySuccess: MARATHON_SERVICE_RESET_DELAY_SUCCESS, serviceRestartError: MARATHON_SERVICE_RESTART_ERROR, serviceRestartSuccess: MARATHON_SERVICE_RESTART_SUCCESS, taskKillSuccess: MARATHON_TASK_KILL_SUCCESS, taskKillError: MARATHON_TASK_KILL_ERROR, }, unmountWhen: () => false, }); AppDispatcher.register((payload) => { const action = payload.action; switch (action.type) { case REQUEST_MARATHON_INSTANCE_INFO_ERROR: this.emit(MARATHON_INSTANCE_INFO_ERROR, action.data); break; case REQUEST_MARATHON_INSTANCE_INFO_SUCCESS: this.processMarathonInfoRequest(action.data); break; case REQUEST_MARATHON_GROUP_CREATE_ERROR: this.emit(MARATHON_GROUP_CREATE_ERROR, action.data); break; case REQUEST_MARATHON_GROUP_CREATE_SUCCESS: this.emit(MARATHON_GROUP_CREATE_SUCCESS); break; case REQUEST_MARATHON_GROUP_DELETE_ERROR: this.emit(MARATHON_GROUP_DELETE_ERROR, action.data); break; case REQUEST_MARATHON_GROUP_DELETE_SUCCESS: this.emit(MARATHON_GROUP_DELETE_SUCCESS); break; case REQUEST_MARATHON_GROUP_EDIT_ERROR: this.emit(MARATHON_GROUP_EDIT_ERROR, action.data); break; case REQUEST_MARATHON_GROUP_EDIT_SUCCESS: this.emit(MARATHON_GROUP_EDIT_SUCCESS); break; case REQUEST_MARATHON_SERVICE_CREATE_ERROR: this.emit(MARATHON_SERVICE_CREATE_ERROR, action.data); break; case REQUEST_MARATHON_SERVICE_CREATE_SUCCESS: this.emit(MARATHON_SERVICE_CREATE_SUCCESS); break; case REQUEST_MARATHON_SERVICE_DELETE_ERROR: this.emit(MARATHON_SERVICE_DELETE_ERROR, action.data); break; case REQUEST_MARATHON_SERVICE_DELETE_SUCCESS: this.emit(MARATHON_SERVICE_DELETE_SUCCESS); break; case REQUEST_MARATHON_SERVICE_EDIT_ERROR: this.emit(MARATHON_SERVICE_EDIT_ERROR, action.data); break; case REQUEST_MARATHON_SERVICE_EDIT_SUCCESS: this.emit(MARATHON_SERVICE_EDIT_SUCCESS); break; case REQUEST_MARATHON_SERVICE_RESTART_ERROR: this.emit(MARATHON_SERVICE_RESTART_ERROR, action.data); break; case REQUEST_MARATHON_SERVICE_RESTART_SUCCESS: this.emit(MARATHON_SERVICE_RESTART_SUCCESS); break; case REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR: this.emit(MARATHON_SERVICE_RESET_DELAY_ERROR, action.data); break; case REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS: this.emit(MARATHON_SERVICE_RESET_DELAY_SUCCESS); break; case REQUEST_MARATHON_GROUPS_SUCCESS: this.injectGroupsWithPackageImages(action.data); this.processMarathonGroups(action.data); break; case REQUEST_MARATHON_DEPLOYMENTS_SUCCESS: this.processMarathonDeployments(action.data); break; case REQUEST_MARATHON_GROUPS_ERROR: this.processMarathonGroupsError(); break; case REQUEST_MARATHON_DEPLOYMENTS_ERROR: this.processMarathonDeploymentsError(); break; case REQUEST_MARATHON_QUEUE_SUCCESS: this.processMarathonQueue(action.data); break; case REQUEST_MARATHON_QUEUE_ERROR: this.processMarathonQueueError(); break; case REQUEST_MARATHON_SERVICE_VERSION_SUCCESS: this.processMarathonServiceVersion(action.data); break; case REQUEST_MARATHON_SERVICE_VERSION_ERROR: this.processMarathonServiceVersionError(); break; case REQUEST_MARATHON_SERVICE_VERSIONS_SUCCESS: this.processMarathonServiceVersions(action.data); break; case REQUEST_MARATHON_SERVICE_VERSIONS_ERROR: this.processMarathonServiceVersionsError(); break; case REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS: this.processMarathonDeploymentRollback(action.data); break; case REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR: this.processMarathonDeploymentRollbackError(action.data); break; case REQUEST_MARATHON_TASK_KILL_SUCCESS: this.emit(MARATHON_TASK_KILL_SUCCESS); break; case REQUEST_MARATHON_TASK_KILL_ERROR: this.emit(MARATHON_TASK_KILL_ERROR, action.data); break; case REQUEST_MARATHON_POD_INSTANCE_KILL_SUCCESS: this.emit(MARATHON_POD_INSTANCE_KILL_SUCCESS); break; case REQUEST_MARATHON_POD_INSTANCE_KILL_ERROR: this.emit(MARATHON_POD_INSTANCE_KILL_ERROR, action.data); break; } return true; }); } addChangeListener(eventName, callback) { this.on(eventName, callback); if (this.shouldPoll()) { startPolling(); } } removeChangeListener(eventName, callback) { this.removeListener(eventName, callback); if (!this.shouldPoll()) { stopPolling(); } } shouldPoll() { return ( this.listenerCount(MARATHON_GROUPS_CHANGE) > 0 || this.listenerCount(MARATHON_QUEUE_CHANGE) > 0 || this.listenerCount(MARATHON_DEPLOYMENTS_CHANGE) > 0 || this.listenerCount(MARATHON_APPS_CHANGE) > 0 ); } hasProcessedApps() { return Object.keys(this.get("apps")).length > 0; } getFrameworkHealth(app) { if (app.healthChecks == null || app.healthChecks.length === 0) { return HealthStatus.NA; } let health = HealthStatus.IDLE; if (app.tasksUnhealthy > 0) { health = HealthStatus.UNHEALTHY; } else if (app.tasksRunning > 0 && app.tasksHealthy === app.tasksRunning) { health = HealthStatus.HEALTHY; } return health; } getInstanceInfo() { return this.get("info"); } getServiceImages(name) { const appName = name.toLowerCase(); let appImages = null; const marathonApps = this.get("apps"); if (marathonApps[appName]) { appImages = marathonApps[appName].images; } return appImages; } getServiceInstalledTime(name: string) { const appName = name.toLowerCase(); let appInstalledTime = null; const marathonApps = this.get("apps"); if (marathonApps[appName]) { appInstalledTime = marathonApps[appName].snapshot.version; } return appInstalledTime; } getServiceVersion(name) { const appName = name.toLowerCase(); const marathonApps = this.get("apps"); if (marathonApps[appName]) { return this.getVersion(marathonApps[appName].snapshot); } return null; } getVersion(app) { if ( app == null || app.labels == null || app.labels.DCOS_PACKAGE_VERSION == null ) { return null; } return app.labels.DCOS_PACKAGE_VERSION; } injectGroupsWithPackageImages(data) { data.items.forEach((item) => { if (item.items && Array.isArray(item.items)) { this.injectGroupsWithPackageImages(item); } else if ( (ServiceValidatorUtil.isFrameworkResponse(item) || ServiceValidatorUtil.isApplicationResponse(item)) && item.labels && item.labels.DCOS_PACKAGE_NAME ) { item.images = CosmosPackagesStore.getPackageImages()[ item.labels.DCOS_PACKAGE_NAME ]; } }); } processMarathonInfoRequest(info) { this.set({ info }); this.emit(MARATHON_INSTANCE_INFO_SUCCESS); } processMarathonGroups(data) { const groups = new ServiceTree(data); const apps = groups.reduceItems((map, item) => { if (item instanceof Framework) { map[item.getFrameworkName().toLowerCase()] = { health: item.getHealth(), images: item.getImages(), snapshot: item.get(), }; } if (item instanceof Application) { map[item.getName().toLowerCase()] = { health: item.getHealth(), images: item.getImages(), snapshot: item.get(), }; } return map; }, {}); const numberOfApps = Object.keys(apps).length; // Specific health check for Marathon // We are setting the 'marathon' key here, since we can safely assume, // it to be 'marathon' (we control it). // This means that no other framework should be named 'marathon'. apps.marathon = { health: this.getFrameworkHealth({ // Make sure health check has a result healthChecks: [{}], // Marathon is healthy if this request returned apps tasksHealthy: numberOfApps, tasksRunning: numberOfApps, }), images: ServiceImages.MARATHON_IMAGES, }; this.set({ apps }); this.set({ groups }); this.emit(MARATHON_APPS_CHANGE, apps); this.emit(MARATHON_GROUPS_CHANGE, groups); } processMarathonGroupsError() { this.emit(MARATHON_APPS_ERROR); this.emit(MARATHON_GROUPS_ERROR); } processMarathonDeployments(data) { if (Array.isArray(data)) { const deployments = new DeploymentsList({ items: data }); this.set({ deployments }); this.emit(MARATHON_DEPLOYMENTS_CHANGE, deployments); } else { this.processMarathonDeploymentsError(); } } processMarathonDeploymentsError() { this.emit(MARATHON_DEPLOYMENTS_ERROR); } processMarathonDeploymentRollback(data) { const id = data.originalDeploymentID; if (id != null) { const deployments = this.get("deployments").filterItems( (deployment) => deployment.getId() !== id ); this.set({ deployments }); this.emit(MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS, data); this.emit(MARATHON_DEPLOYMENTS_CHANGE); } } processMarathonDeploymentRollbackError(data) { this.emit(MARATHON_DEPLOYMENT_ROLLBACK_ERROR, data); } processMarathonQueue(data) { if (data.queue != null) { this.emit(MARATHON_QUEUE_CHANGE, data.queue); } } processMarathonQueueError() { this.emit(MARATHON_QUEUE_ERROR); } processMarathonServiceVersions(service) { let { serviceID, versions } = service; versions = versions.reduce((map, version) => map.set(version), new Map()); this.emit(MARATHON_SERVICE_VERSIONS_CHANGE, { serviceID, versions }); } processMarathonServiceVersionsError() { this.emit(MARATHON_SERVICE_VERSIONS_ERROR); } processMarathonServiceVersion(service) { const { serviceID, version, versionID } = service; // TODO (orlandohohmeier): Convert version into typed version struct this.emit(MARATHON_SERVICE_VERSION_CHANGE, { serviceID, versionID, version, }); } processMarathonServiceVersionError() { this.emit(MARATHON_SERVICE_VERSION_ERROR); } setShouldEmbedLastUnusedOffers(value) { shouldEmbedLastUnusedOffers = value; // Restart polling to immediately use the updated embed params. stopPolling(); startPolling(); } } export default new MarathonStore();
the_stack
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import JqxDockingLayout, { IDockingLayoutProps } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxdockinglayout'; import JqxTree from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtree'; class App extends React.PureComponent<{}, IDockingLayoutProps> { constructor(props: {}) { super(props); const layout: IDockingLayoutProps['layout'] = [ { items: [{ alignment: 'left', items: [{ contentContainer: 'ToolboxPanel', title: 'Toolbox', type: 'layoutPanel' }, { contentContainer: 'HelpPanel', title: 'Help', type: 'layoutPanel' }], type: 'autoHideGroup', unpinnedWidth: 200, width: 80 }, { items: [{ height: 400, items: [{ contentContainer: 'Document1Panel', title: 'Document 1', type: 'documentPanel', }, { contentContainer: 'Document2Panel', title: 'Document 2', type: 'documentPanel' }], minHeight: 200, type: 'documentGroup' }, { height: 200, items: [{ contentContainer: 'ErrorListPanel', title: 'Error List', type: 'layoutPanel' }], pinnedHeight: 30, type: 'tabbedGroup' }], orientation: 'vertical', type: 'layoutGroup', width: 500 }, { items: [ { contentContainer: 'SolutionExplorerPanel', initContent: () => { // initialize a jqxTree inside the Solution Explorer Panel const source = [{ expanded: true, icon: 'https://www.jqwidgets.com/react/images/earth.png', items: [ { expanded: true, icon: 'https://www.jqwidgets.com/react/images/folder.png', items: [{ icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqx.base.css' }, { icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqx.energyblue.css' }, { icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqx.orange.css' }], label: 'css' }, { icon: 'https://www.jqwidgets.com/react/images/folder.png', items: [{ icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqxcore.js' }, { icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqxdata.js' }, { icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'jqxgrid.js' }], label: 'scripts', }, { icon: 'https://www.jqwidgets.com/react/images/nav1.png', label: 'index.htm' }], label: 'Project', }]; ReactDOM.render(<JqxTree width={'100%'} height={'99%'} source={source} />, document.querySelector('#treeContainer')); }, title: 'Solution Explorer', type: 'layoutPanel' }, { contentContainer: 'PropertiesPanel', title: 'Properties', type: 'layoutPanel' }], minWidth: 200, type: 'tabbedGroup', width: 220 }], orientation: 'horizontal', type: 'layoutGroup' }, { height: 300, items: [{ contentContainer: 'OutputPanel', selected: true, title: 'Output', type: 'layoutPanel' }], position: { x: 350, y: 250 }, type: 'floatGroup', width: 500 } ]; this.state = { layout } } public render() { return ( // @ts-ignore <JqxDockingLayout theme={'material-purple'} width={'100%'} height={600} layout={this.state.layout} > {/* The panel content divs can have a flat structure */} {/* autoHideGroup */} <div data-container={'ToolboxPanel'}> List of tools </div> <div data-container={'HelpPanel'}> Help topics </div> {/* documentGroup */} <div data-container={'Document1Panel'}> Document 1 content </div> <div data-container={'Document2Panel'}> Document 2 content </div> {/* bottom tabbedGroup */} <div data-container={'ErrorListPanel'}> List of errors </div> {/* right tabbedGroup */} <div data-container={'SolutionExplorerPanel'}> <div id="treeContainer" style={{ border: 'none', width: '99%', height: '100%' }} /> </div> <div data-container={'PropertiesPanel'}> List of properties </div> {/* floatGroup */} <div data-container={'OutputPanel'}> <div style={{ fontFamily: 'Consolas' }}> <p> Themes installation complete. </p> <p> List of installed stylesheet files. Include at least one stylesheet Theme file and the images folder: </p> <ul> <li> styles/jqx.base.css: Stylesheet for the base Theme. The jqx.base.css file should be always included in your project. </li> <li>styles/jqx.arctic.css: Stylesheet for the Arctic Theme</li> <li>styles/jqx.web.css: Stylesheet for the Web Theme</li> <li>styles/jqx.bootstrap.css: Stylesheet for the Bootstrap Theme</li> <li>styles/jqx.classic.css: Stylesheet for the Classic Theme</li> <li>styles/jqx.darkblue.css: Stylesheet for the DarkBlue Theme</li> <li>styles/jqx.energyblue.css: Stylesheet for the EnergyBlue Theme</li> <li>styles/jqx.shinyblack.css: Stylesheet for the ShinyBlack Theme</li> <li>styles/jqx.office.css: Stylesheet for the Office Theme</li> <li>styles/jqx.metro.css: Stylesheet for the Metro Theme</li> <li>styles/jqx.metrodark.css: Stylesheet for the Metro Dark Theme</li> <li>styles/jqx.orange.css: Stylesheet for the Orange Theme</li> <li>styles/jqx.summer.css: Stylesheet for the Summer Theme</li> <li>styles/jqx.black.css: Stylesheet for the Black Theme</li> <li>styles/jqx.fresh.css: Stylesheet for the Fresh Theme</li> <li>styles/jqx.highcontrast.css: Stylesheet for the HighContrast Theme</li> <li>styles/jqx.blackberry.css: Stylesheet for the Blackberry Theme</li> <li>styles/jqx.android.css: Stylesheet for the Android Theme</li> <li>styles/jqx.mobile.css: Stylesheet for the Mobile Theme</li> <li>styles/jqx.windowsphone.css: Stylesheet for the Windows Phone Theme</li> <li>styles/jqx.ui-darkness.css: Stylesheet for the UI Darkness Theme</li> <li>styles/jqx.ui-lightness.css: Stylesheet for the UI Lightness Theme</li> <li>styles/jqx.ui-le-frog.css: Stylesheet for the UI Le Frog Theme</li> <li>styles/jqx.ui-overcast.css: Stylesheet for the UI Overcast Theme</li> <li>styles/jqx.ui-redmond.css: Stylesheet for the UI Redmond Theme</li> <li>styles/jqx.ui-smoothness.css: Stylesheet for the UI Smoothness Theme</li> <li>styles/jqx.ui-start.css: Stylesheet for the UI Start Theme</li> <li>styles/jqx.ui-sunny.css: Stylesheet for the UI Sunny Theme</li> <li>styles/images: contains images referenced in the stylesheet files</li> </ul> </div> </div> </JqxDockingLayout> ); } } export default App;
the_stack
import { mat3, mat4 } from 'gl-matrix'; import OrthographicCamera from '../cameras/OrthographicCamera'; import PerspectiveCamera from '../cameras/PerspectiveCamera'; import Geometry from '../geometry/Geometry'; import Lights from '../lights/Lights'; import Color from '../math/Color'; import { basicFragmentShaderEs100, basicFragmentShaderEs300 } from '../shaders/Basic.glsl'; import { lambertFragmentShaderEs100, lambertFragmentShaderEs300 } from '../shaders/Lambert.glsl'; import { phongFragmentShaderEs100, phongFragmentShaderEs300 } from '../shaders/Phong.glsl'; import { vertexShaderEs100, vertexShaderEs300 } from '../shaders/Vertex.glsl'; import ShaderParser from '../utils/ShaderParser'; import { capabilities } from './Capabilities'; import * as CONSTANTS from './Constants'; import * as GL from './GL'; import Program from './Program'; import UniformBuffers from './UniformBuffers'; let gl: WebGL2RenderingContext | WebGLRenderingContext; const normalMatrix: mat3 = mat3.create(); const inversedModelViewMatrix: mat4 = mat4.create(); interface Options { name?: string; type?: string; uniforms?: any; fov?: number; hookVertexPre?: string; hookVertexMain?: string; hookVertexEnd?: string; hookFragmentPre?: string; hookFragmentMain?: string; hookFragmentEnd?: string; vertexShader?: string; fragmentShader?: string; drawType?: number; ambientLight?: Lights; directionalLights?: Lights; pointLights?: Lights; culling?: number; } export default class Material { public name: string; public type: string; public uniforms: any; public fov: number; public hookVertexPre: string; public hookVertexMain: string; public hookVertexEnd: string; public hookFragmentPre: string; public hookFragmentMain: string; public hookFragmentEnd: string; public vertexShader: string; public fragmentShader: string; public drawType: number; public ambientLight: Lights; public directionalLights: Lights; public pointLights: Lights; public culling: number; public blending: boolean; public blendFunc: number[]; public program: Program; public customUniforms: object; constructor(options: Options = {}) { const vertexShader = GL.webgl2 ? vertexShaderEs300 : vertexShaderEs100; let fragmentShader; switch (options.type || '') { case CONSTANTS.MATERIAL_LAMBERT: { fragmentShader = GL.webgl2 ? lambertFragmentShaderEs300 : lambertFragmentShaderEs100; break; } case CONSTANTS.MATERIAL_PHONG: { fragmentShader = GL.webgl2 ? phongFragmentShaderEs300 : phongFragmentShaderEs100; break; } default: { fragmentShader = GL.webgl2 ? basicFragmentShaderEs300 : basicFragmentShaderEs100; } } gl = GL.get(); this.name = ''; this.type = CONSTANTS.MATERIAL_BASIC; this.uniforms = {}; this.hookVertexPre = ''; this.hookVertexMain = ''; this.hookVertexEnd = ''; this.hookFragmentPre = ''; this.hookFragmentMain = ''; this.hookFragmentEnd = ''; this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.drawType = CONSTANTS.DRAW_TRIANGLES; this.directionalLights = undefined; this.pointLights = undefined; this.culling = CONSTANTS.CULL_NONE; this.blending = false; this.blendFunc = [gl.SRC_ALPHA, gl.ONE]; Object.assign(this, options); this.program = new Program(); } public create(geometry: Geometry, transformFeedbackVaryings?: string[]) { gl = GL.get(); this.vertexShader = this._processShader( this.vertexShader, 'vertex', geometry ); this.fragmentShader = this._processShader( this.fragmentShader, 'fragment', geometry ); this.program.link( this.vertexShader, this.fragmentShader, transformFeedbackVaryings ); // User defined uniforms this.customUniforms = this.uniforms || {}; // Uniforms for ProjectionView uniform block if (GL.webgl2) { this.program.setUniformBlockLocation( 'ProjectionView', UniformBuffers.projectionView.buffer, CONSTANTS.UNIFORM_PROJECTION_VIEW_LOCATION ); } if (this.ambientLight) { if (GL.webgl2) { // Setup uniform block for point lights this.program.setUniformBlockLocation( 'AmbientLight', this.ambientLight.uniformBuffer.buffer, CONSTANTS.UNIFORM_AMBIENT_LIGHT_LOCATION ); } else { // Generate uniforms for point lights this.ambientLight.get().forEach((ambientLight, i) => { Object.keys(ambientLight.uniforms).forEach(ambientLightUniform => { const uniform = ambientLight.uniforms[ambientLightUniform]; this.customUniforms[ `uAmbientLight.${ambientLightUniform}` ] = uniform; }); }); } } if (this.directionalLights) { if (GL.webgl2) { // Setup uniform block for directional lights this.program.setUniformBlockLocation( 'DirectionalLights', this.directionalLights.uniformBuffer.buffer, CONSTANTS.UNIFORM_DIRECTIONAL_LIGHTS_LOCATION ); } else { // Generate uniforms for directional lights this.directionalLights.get().forEach((directionalLight, i) => { Object.keys( directionalLight.uniforms ).forEach(directionalLightUniform => { const uniform = directionalLight.uniforms[directionalLightUniform]; this.customUniforms[ `uDirectionalLights[${i}].${directionalLightUniform}` ] = uniform; }); }); } } if (this.pointLights) { if (GL.webgl2) { // Setup uniform block for point lights this.program.setUniformBlockLocation( 'PointLights', this.pointLights.uniformBuffer.buffer, CONSTANTS.UNIFORM_POINT_LIGHTS_LOCATION ); } else { // Generate uniforms for point lights this.pointLights.get().forEach((pointLight, i) => { Object.keys(pointLight.uniforms).forEach(pointLightUniform => { const uniform = pointLight.uniforms[pointLightUniform]; this.customUniforms[ `uPointLights[${i}].${pointLightUniform}` ] = uniform; }); }); } } // Generate texture indices const textureIndices = [ gl.TEXTURE0, gl.TEXTURE1, gl.TEXTURE2, gl.TEXTURE3, gl.TEXTURE4, gl.TEXTURE5 ]; Object.keys(this.uniforms).forEach((uniformName, i) => { switch (this.uniforms[uniformName].type) { case 't': case 'tc': case 't3d': { this.uniforms[uniformName].textureIndex = i; this.uniforms[uniformName].activeTexture = textureIndices[i]; break; } default: } }); // Add Camera position uniform for point lights if it doesn"t exist if (this.uniforms.uCameraPosition === undefined && this.pointLights) { this.uniforms.uCameraPosition = { type: '3f', value: [0, 0, 0] }; } // Only for webgl1 const projectionViewUniforms = GL.webgl2 ? {} : { uProjectionMatrix: { location: null, type: '4fv', value: mat4.create() } }; // Default uniforms this.uniforms = { uDiffuse: { location: null, type: '3f', value: new Color().v }, uModelMatrix: { location: null, type: '4fv', value: mat4.create() }, uModelViewMatrix: { location: null, type: '4fv', value: mat4.create() }, uNormalMatrix: { location: null, type: '4fv', value: mat4.create() }, ...this.customUniforms, ...projectionViewUniforms }; Object.keys(this.uniforms).forEach(uniformName => { this.program.setUniformLocation(this.uniforms, uniformName); }); } public _processShader(shader: string, type: string, geometry: Geometry) { gl = GL.get(); let defines = ''; const precision = `precision ${capabilities.precision} float;`; function addDefine(define) { defines += `#define ${define} \n`; } if (geometry.bufferUvs) { addDefine('uv'); } if (geometry.bufferColors) { addDefine('vertexColors'); } if (geometry.bufferNormals) { addDefine('normals'); } if (this.ambientLight) { addDefine('ambientLight'); } if (this.directionalLights) { addDefine('directionalLights'); } if (this.pointLights) { addDefine('pointLights'); } shader = shader.replace(/#HOOK_PRECISION/g, precision); shader = shader.replace(/#HOOK_DEFINES/g, defines); shader = shader.replace(/#HOOK_VERTEX_PRE/g, this.hookVertexPre); shader = shader.replace(/#HOOK_VERTEX_MAIN/g, this.hookVertexMain); shader = shader.replace(/#HOOK_VERTEX_END/g, this.hookVertexEnd); shader = shader.replace(/#HOOK_FRAGMENT_PRE/g, this.hookFragmentPre); shader = shader.replace(/#HOOK_FRAGMENT_MAIN/g, this.hookFragmentMain); shader = shader.replace(/#HOOK_FRAGMENT_END/g, this.hookFragmentEnd); if (this.pointLights) { shader = shader.replace( /#HOOK_POINT_LIGHTS/g, String(this.pointLights.length) ); } if (this.directionalLights) { shader = shader.replace( /#HOOK_DIRECTIONAL_LIGHTS/g, String(this.directionalLights.length) ); } return ShaderParser(shader, type); } public setUniforms( projectionMatrix: mat4, modelViewMatrix: mat4, modelMatrix: mat4, camera?: PerspectiveCamera | OrthographicCamera ) { gl = GL.get(); // Update the other uniforms Object.keys(this.customUniforms).forEach(uniformName => { const uniform = this.uniforms[uniformName]; switch (uniform.type) { case 't': { gl.uniform1i(uniform.location, uniform.textureIndex); gl.activeTexture(uniform.activeTexture); gl.bindTexture(gl.TEXTURE_2D, uniform.value); break; } case 'tc': { gl.uniform1i(uniform.location, uniform.textureIndex); gl.activeTexture(uniform.activeTexture); gl.bindTexture(gl.TEXTURE_CUBE_MAP, uniform.value); break; } case 't3d': { if (gl instanceof WebGL2RenderingContext) { gl.uniform1i(uniform.location, uniform.textureIndex); gl.activeTexture(uniform.activeTexture); gl.bindTexture(gl.TEXTURE_3D, uniform.value); } break; } case 'i': { gl.uniform1i(uniform.location, uniform.value); break; } case 'f': { gl.uniform1f(uniform.location, uniform.value); break; } case '2f': { gl.uniform2f(uniform.location, uniform.value[0], uniform.value[1]); break; } case '3f': { gl.uniform3f( uniform.location, uniform.value[0], uniform.value[1], uniform.value[2] ); break; } case '4f': { gl.uniform4f( uniform.location, uniform.value[0], uniform.value[1], uniform.value[2], uniform.value[3] ); break; } case '1iv': { gl.uniform1iv(uniform.location, uniform.value); break; } case '2iv': { gl.uniform2iv(uniform.location, uniform.value); break; } case '1fv': { gl.uniform1fv(uniform.location, uniform.value); break; } case '2fv': { gl.uniform2fv(uniform.location, uniform.value); break; } case '3fv': { gl.uniform3fv(uniform.location, uniform.value); break; } case '4fv': { gl.uniform4fv(uniform.location, uniform.value); break; } case 'Matrix3fv': { gl.uniformMatrix3fv(uniform.location, false, uniform.value); break; } case 'Matrix4fv': { gl.uniformMatrix4fv(uniform.location, false, uniform.value); break; } default: } }); if (!GL.webgl2) { gl.uniformMatrix4fv( this.uniforms.uProjectionMatrix.location, false, projectionMatrix ); } gl.uniformMatrix4fv( this.uniforms.uModelViewMatrix.location, false, modelViewMatrix ); gl.uniformMatrix4fv( this.uniforms.uModelMatrix.location, false, modelMatrix ); mat4.identity(inversedModelViewMatrix); mat4.invert(inversedModelViewMatrix, modelMatrix); mat3.identity(normalMatrix); mat3.fromMat4(normalMatrix, inversedModelViewMatrix); mat3.transpose(normalMatrix, normalMatrix); gl.uniformMatrix3fv( this.uniforms.uNormalMatrix.location, false, normalMatrix ); // uDiffuse gl.uniform3f( this.uniforms.uDiffuse.location, this.uniforms.uDiffuse.value[0], this.uniforms.uDiffuse.value[1], this.uniforms.uDiffuse.value[2] ); // Camera if (camera && this.uniforms.uCameraPosition) { gl.uniform3f( this.uniforms.uCameraPosition.location, camera.position.v[0], camera.position.v[1], camera.position.v[2] ); } } public dispose() { // Dispose textures Object.keys(this.customUniforms).forEach(uniformName => { const uniform = this.uniforms[uniformName]; switch (uniform.type) { case 't': case 'tc': { gl.deleteTexture(uniform.value); break; } default: } }); this.program.dispose(); } }
the_stack
import {Converter} from "../src/Converter"; import csv from "../src"; var assert = require("assert"); var fs = require("fs"); var sandbox = require("sinon").sandbox.create(); var file = __dirname + "/data/testData"; var trailCommaData = __dirname + "/data/trailingComma"; describe("CSV Converter", function () { afterEach(function () { sandbox.restore(); }); it("should create new instance of csv", function () { var obj = new Converter(); assert(obj); }); it("should read from a stream", function (done) { var obj = new Converter(); var stream = fs.createReadStream(file); obj.then(function (obj) { assert.equal(obj.length, 2); done(); }); stream.pipe(obj); }); it("should call onNext once a row is parsed.", function (done) { var obj = new Converter(); var stream = fs.createReadStream(file); var called = false; obj.subscribe(function (resultRow) { assert(resultRow); called = true; }); obj.on("done", function () { assert(called); done(); }); stream.pipe(obj); }); it("should emit end_parsed message once it is finished.", function (done) { var obj = new Converter(); obj.then(function (result) { assert(result); assert(result.length === 2); assert(result[0].date); assert(result[0].employee); assert(result[0].employee.name); assert(result[0].employee.age); assert(result[0].employee.number); assert(result[0].employee.key.length === 2); assert(result[0].address.length === 2); done(); }); fs.createReadStream(file).pipe(obj); }); it("should handle traling comma gracefully", function (done) { var stream = fs.createReadStream(trailCommaData); var obj = new Converter(); obj.then(function (result) { assert(result); assert(result.length > 0); done(); }); stream.pipe(obj); }); it("should handle comma in column which is surrounded by qoutes", function (done) { var testData = __dirname + "/data/dataWithComma"; var rs = fs.createReadStream(testData); var obj = new Converter({ "quote": "#" }); obj.then(function (result) { assert(result[0].col1 === "\"Mini. Sectt"); assert.equal(result[3].col2, "125001,fenvkdsf"); // console.log(result); done(); }); rs.pipe(obj); }); it("should be able to convert a csv to column array data", function (done) { var columArrData = __dirname + "/data/columnArray"; var rs = fs.createReadStream(columArrData); var result:any = {}; var csvConverter = new Converter(); //end_parsed will be emitted once parsing finished csvConverter.then(function () { assert(result.TIMESTAMP.length === 5); done(); }); //record_parsed will be emitted each time a row has been parsed. csvConverter.subscribe(function (resultRow, rowIndex) { for (var key in resultRow) { if (resultRow.hasOwnProperty(key)) { if (!result[key] || !(result[key] instanceof Array)) { result[key] = []; } result[key][rowIndex] = resultRow[key]; } } }); rs.pipe(csvConverter); }); it("should be able to convert csv string directly", function (done) { var testData = __dirname + "/data/testData"; var data = fs.readFileSync(testData).toString(); var csvConverter = new Converter(); //end_parsed will be emitted once parsing finished csvConverter.then(function (jsonObj) { assert.equal(jsonObj.length, 2); }); csvConverter.fromString(data).then(function (jsonObj) { assert(jsonObj.length === 2); done(); }); }); it("should be able to convert csv string with error", function (done) { var testData = __dirname + "/data/dataWithUnclosedQuotes"; var data = fs.readFileSync(testData).toString(); var csvConverter = new Converter(); csvConverter.fromString(data).then(undefined, function (err) { assert(err); assert.equal(err.err, "unclosed_quote"); done(); }); }); it("should be able to convert csv string without callback provided", function (done) { var testData = __dirname + "/data/testData"; var data = fs.readFileSync(testData).toString(); var csvConverter = new Converter(); //end_parsed will be emitted once parsing finished csvConverter.then(function (jsonObj) { assert(jsonObj.length === 2); done(); }); csvConverter.fromString(data); }); it("should be able to handle columns with double quotes", function (done) { var testData = __dirname + "/data/dataWithQoutes"; var data = fs.readFileSync(testData).toString(); var csvConverter = new Converter(); csvConverter.fromString(data).then(function (jsonObj) { assert(jsonObj[0].TIMESTAMP === '13954264"22', JSON.stringify(jsonObj[0].TIMESTAMP)); assert(jsonObj[1].TIMESTAMP === 'abc, def, ccc', JSON.stringify(jsonObj[1].TIMESTAMP)); done(); }); }); it("should be able to handle columns with two double quotes", function (done) { var testData = __dirname + "/data/twodoublequotes"; var data = fs.readFileSync(testData).toString(); var csvConverter = new Converter(); csvConverter.fromString(data).then(function (jsonObj) { assert.equal(jsonObj[0].title, "\""); assert.equal(jsonObj[0].data, "xyabcde"); assert.equal(jsonObj[0].uuid, "fejal\"eifa"); assert.equal(jsonObj[0].fieldA, "bnej\"\"falkfe"); assert.equal(jsonObj[0].fieldB, "\"eisjfes\""); done(); }); }); it("should handle empty csv file", function (done) { var testData = __dirname + "/data/emptyFile"; var rs = fs.createReadStream(testData); var csvConverter = new Converter(); csvConverter.then(function (jsonObj) { assert(jsonObj.length === 0); done(); }); rs.pipe(csvConverter); }); it("should parse large csv file", function (done) { var testData = __dirname + "/data/large-csv-sample.csv"; var rs = fs.createReadStream(testData); var csvConverter = new Converter(); var count = 0; csvConverter.subscribe(function () { //console.log(arguments); count++; }); csvConverter.then(function () { assert(count === 5290); done(); }); rs.pipe(csvConverter); }); it("should parse data and covert to specific types", function (done) { var testData = __dirname + "/data/dataWithType"; var rs = fs.createReadStream(testData); var csvConverter = new Converter({ checkType: true, colParser: { "column6": "string", "column7": "string" } }); csvConverter.subscribe(function (d) { assert(typeof d.column1 === "number"); assert(typeof d.column2 === "string"); assert.equal(d["colume4"], "someinvaliddate"); assert(d.column5.hello === "world"); assert(d.column6 === '{"hello":"world"}'); assert(d.column7 === "1234"); assert(d.column8 === "abcd"); assert(d.column9 === true); assert(d.column10[0] === 23); assert(d.column10[1] === 31); assert(d.column11[0].hello === "world"); assert(d["name#!"] === false); }); csvConverter.on("done", function () { done(); }); rs.pipe(csvConverter); }); it("should turn off field type check", function (done) { var testData = __dirname + "/data/dataWithType"; var rs = fs.createReadStream(testData); var csvConverter = new Converter({ checkType: false }); csvConverter.subscribe(function (d) { assert(typeof d.column1 === "string"); assert(typeof d.column2 === "string"); assert(d["column3"] === "2012-01-01"); assert(d["colume4"] === "someinvaliddate"); assert(d.column5 === '{"hello":"world"}'); assert.equal(d["column6"], '{"hello":"world"}'); assert(d["column7"] === "1234"); assert(d["column8"] === "abcd"); assert(d.column9 === "true"); assert(d.column10[0] === "23"); assert(d.column10[1] === "31"); assert(d["name#!"] === 'false'); }); csvConverter.then(function () { done(); }); rs.pipe(csvConverter); }); it("should emit data event correctly", function (done) { var testData = __dirname + "/data/large-csv-sample.csv"; var csvConverter = new Converter({ }); var count = 0; csvConverter.on("data", function (d) { count++; }); csvConverter.on("end", function () { assert.equal(count, 5290); done(); }); var rs = fs.createReadStream(testData); rs.pipe(csvConverter); }); it("should process column with linebreaks", function (done) { var testData = __dirname + "/data/lineBreak"; var rs = fs.createReadStream(testData); var csvConverter = new Converter({ checkType: true }); csvConverter.subscribe(function (d) { assert(d.Period === 13); assert(d["Apparent age"] === "Unknown"); done(); }); rs.pipe(csvConverter); }); it("be able to ignore empty columns", function (done) { var testData = __dirname + "/data/dataIgnoreEmpty"; var rs = fs.createReadStream(testData); var st = rs.pipe(csv({ ignoreEmpty: true })); st.then(function (res) { var j = res[0]; assert(res.length === 3); assert(j.col2.length === 2); assert(j.col2[1] === "d3"); assert(j.col4.col3 === undefined); assert(j.col4.col5 === "world"); assert(res[1].col1 === "d2"); assert(res[2].col1 === "d4"); done(); }); }); it("should allow no header", function (done) { var testData = __dirname + "/data/noheadercsv"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter({ noheader: true })); st.then(function (res) { var j = res[0]; assert(res.length === 5); assert(j.field1 === "CC102-PDMI-001"); assert(j.field2 === "eClass_5.1.3"); done(); }); }); it("should allow customised header", function (done) { var testData = __dirname + "/data/noheadercsv"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter({ noheader: true, headers: ["a", "b"] })); st.then(function (res) { var j = res[0]; assert(res.length === 5); assert(j.a === "CC102-PDMI-001"); assert(j.b === "eClass_5.1.3"); assert(j.field3 === "10/3/2014"); done(); }); }); it("should allow customised header to override existing header", function (done) { var testData = __dirname + "/data/complexJSONCSV"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter({ headers: [] })); st.then(function (res) { var j = res[0]; assert(res.length === 2); assert(j.field1 === "Food Factory"); assert(j.field2 === "Oscar"); done(); }); }); it("should handle when there is an empty string", function (done) { var testData = __dirname + "/data/dataWithEmptyString"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter({ noheader: true, headers: ["a", "b", "c"], checkType: true })); st.then(function (res) { var j = res[0]; // assert(res.length===2); assert(j.a === "green"); assert(j.b === 40); assert.equal(j.c, ""); done(); }); }); it("should detect eol correctly when first chunk is smaller than header row length", function (done) { var testData = __dirname + "/data/dataNoTrimCRLF"; var rs = fs.createReadStream(testData, { highWaterMark: 3 }); var st = rs.pipe(new Converter({ trim: false })); st.then(function (res) { var j = res[0]; assert(res.length === 2); assert(j.name === "joe"); assert(j.age === "20"); assert.equal(res[1].name, "sam"); assert.equal(res[1].age, "30"); done(); }); }); it("should detect eol correctly when first chunk ends in middle of CRLF line break", function (done) { var testData = __dirname + "/data/dataNoTrimCRLF"; var rs = fs.createReadStream(testData, { highWaterMark: 9 }); var st = rs.pipe(new Converter({ trim: false })); st.then(function (res) { var j = res[0]; assert(res.length === 2); assert(j.name === "joe"); assert(j.age === "20"); assert.equal(res[1].name, "sam"); assert.equal(res[1].age, "30"); done(); }); }); it("should emit eol event when line ending is detected as CRLF", function (done) { var testData = __dirname + "/data/dataNoTrimCRLF"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter()); var eolCallback = sandbox.spy(function (eol) { assert.equal(eol, "\r\n"); }); st.on("eol", eolCallback); st.then(function () { assert.equal(eolCallback.callCount, 1, 'should emit eol event once'); done(); }) }); it("should emit eol event when line ending is detected as LF", function (done) { var testData = __dirname + "/data/columnArray"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter()); var eolCallback = sandbox.spy(function (eol) { assert.equal(eol, "\n"); }); st.on("eol", eolCallback); st.then(function () { assert.equal(eolCallback.callCount, 1, 'should emit eol event once'); done(); }) }); it("should remove the Byte Order Mark (BOM) from input", function (done) { var testData = __dirname + "/data/dataNoTrimBOM"; var rs = fs.createReadStream(testData); var st = rs.pipe(new Converter({ trim: false })); st.then( function (res) { var j = res[0]; assert(res.length===2); assert(j.name === "joe"); assert(j.age === "20"); done(); }); }); });
the_stack
import {Watcher, RawValue, DiffConsumer} from "./watcher"; import {ID, Block, FunctionConstraint, printBlock} from "../runtime/runtime"; import {Program, LinearFlow, ReferenceContext, Reference, Record, Insert, Remove, Value, Fn, Not, Choose, Union, Aggregate, WatchFlow, LinearFlowFunction, CommitFlow} from "../runtime/dsl2"; import {SumAggregate} from "../runtime/stdlib"; import * as Runtime from "../runtime/runtime"; import "setimmediate"; export interface CompilationContext { variables: {[id:string]: {[id:string]: Reference}}, } export class CompilerWatcher extends Watcher { blocksToCompile:{[blockID:string]: boolean} = {}; blocksToRemove:{[blockID:string]: boolean} = {}; blocks:{[blockID:string]: Block} = {}; items:{[id:string]: any} = {}; watcherFunctions:{[name:string]: DiffConsumer} = {}; programToInjectInto = this.program; //------------------------------------------------------------------ // Compile queue //------------------------------------------------------------------ queued = false; queue(blockID:string, isAdd = true) { if(isAdd) this.blocksToCompile[blockID] = true; this.blocksToRemove[blockID] = true; if(!this.queued) { this.queued = true; setImmediate(this.runQueue) } } runQueue = () => { let adds = []; let removes = []; for(let ID in this.blocksToRemove) { if(!this.blocks[ID]) continue; removes.push(this.blocks[ID]); delete this.blocks[ID]; } for(let ID in this.blocksToCompile) { if(!this.items[ID]) continue; let neue = this.compileBlock(ID); if(neue) { adds.push(neue); this.blocks[ID] = neue; } } this.programToInjectInto.blockChangeTransaction(adds, removes); this.queued = false; this.blocksToCompile = {}; this.blocksToRemove = {}; } //------------------------------------------------------------------ // Program to inject into //------------------------------------------------------------------ injectInto(prog:Program) { this.programToInjectInto = prog; } //------------------------------------------------------------------ // Watch functions //------------------------------------------------------------------ registerWatcherFunction(name:string, consumer:DiffConsumer) { this.watcherFunctions[name] = consumer; } //------------------------------------------------------------------ // Compiler //------------------------------------------------------------------ inContext(flow:LinearFlow, func: () => void) { ReferenceContext.push(flow.context); func(); ReferenceContext.pop(); } compileValue = (compile:CompilationContext, context:ReferenceContext, value:RawValue|undefined):Value|undefined => { if(value === undefined) return undefined; let {items} = this; if(items[value] && items[value].type === "variable") { let found; let cur:ReferenceContext|undefined = context; while(!found && cur) { found = compile.variables[cur.ID] && compile.variables[cur.ID][value]; cur = cur.parent; } if(!found) { if(!compile.variables[context.ID]) { compile.variables[context.ID] = {}; } found = compile.variables[context.ID][value] = new Reference(context); } return found; } return value; } compileFlow(compile:CompilationContext, flow:LinearFlow, constraints: any[]) { let {inContext, items, compileValue} = this; let {context} = flow; let subBlocks:any[] = []; for(let constraintID of constraints) { let constraint = items[constraintID]; if(!constraint) continue; if(constraint.type === "record") { inContext(flow, () => { let attrs:any = {}; for(let [attribute, value] of constraint.attributes) { let safeValue = compileValue(compile, context, value); let found = attrs[attribute]; if(!found) { found = attrs[attribute] = []; } found.push(safeValue); } let recordVar = compileValue(compile, context, constraint.record) as Reference; let record = new Record(flow.context, [], attrs, recordVar); recordVar.__owner = record; }) } if(constraint.type === "output") { inContext(flow, () => { let attrs:any = {}; for(let [attribute, value] of constraint.attributes) { let safeValue = compileValue(compile, context, value); let found = attrs[attribute]; if(!found) { found = attrs[attribute] = []; } found.push(safeValue); } let outputType = Insert; let outputOp = "add"; if(constraint.outputType === "remove") { outputType = Remove; outputOp = "remove"; } let outputVar = compileValue(compile, context, constraint.record) as Reference; let output; if(constraint.attributes.length > 0) { output = new outputType(flow.context, [], attrs); context.equality(output.reference(), outputVar); } else { output = new outputType(flow.context, [], attrs, outputVar); } let record = output.reference() as any; for(let [attribute, value] of constraint.nonIdentityAttribute) { record[outputOp](compileValue(compile, context, attribute), compileValue(compile, context, value)); } }) } if(constraint.type === "removeRecord") { inContext(flow, () => { let outputVar = compileValue(compile, context, constraint.record) as Reference; let output; if(!outputVar.__owner) { throw new Error("Trying to fully remove a record that doesn't exist"); } outputVar.remove(); }) } if(constraint.type === "lookup") { inContext(flow, () => { let lookup = flow.lookup(compileValue(compile, context, constraint.record) as Value); context.equality(lookup.attribute, compileValue(compile, context, constraint.attribute) as Value); context.equality(lookup.value, compileValue(compile, context, constraint.value) as Value); }) } if(constraint.type === "expression") { inContext(flow, () => { let args = constraint.args.map((v:RawValue) => compileValue(compile, context, v)); let returns = constraint.returns.map((v:RawValue) => compileValue(compile, context, v))[0]; let fn = new Fn(flow.context, constraint.op, args, returns); }) } if(constraint.type === "aggregate") { inContext(flow, () => { let projection:Reference[] = []; let group:Reference[] = []; let args:Value[] = []; for(let arg in constraint.namedArgs) { let values = constraint.namedArgs[arg].map((v:RawValue) => compileValue(compile, context, v)); if(arg === "for" || arg === "given") { projection = values; } else if(arg === "per") { group = values; } else if(arg === "direction" || arg === "value") { args = args.concat(values); } } let aggOp:any = SumAggregate; if(constraint.op === "gather/sort") { aggOp = Runtime.SortNode; } else if(constraint.op === "gather/count" && args.length === 0) { args.push(1); } let returns = constraint.returns.map((v:RawValue) => compileValue(compile, context, v))[0]; let agg = new Aggregate(flow.context, aggOp, projection, group, args, returns); }) } if(constraint.type === "equality") { inContext(flow, () => { context.equality(compileValue(compile, context, constraint.left) as Value, compileValue(compile, context, constraint.right) as Value); }) } if(constraint.type === "not" || constraint.type === "choose" || constraint.type === "union") { subBlocks.push(constraint); } } for(let constraint of subBlocks) { if(constraint.type === "not") { inContext(flow, () => { let not = new Not((a:any) => [], flow); this.compileFlow(compile, not, constraint.constraints); }); } if(constraint.type === "choose" || constraint.type == "union") { let builder = constraint.type == "choose" ? Choose : Union; let branchFuncs:LinearFlowFunction[] = []; for(let branchId of constraint.branches) { let branch = items[branchId]; branchFuncs.push((self) => { return branch.outputs.map((v:RawValue) => { return compileValue(compile, self.context, v) as Value; }) }); } inContext(flow, () => { let outputs = constraint.outputs.map((v:RawValue) => { return compileValue(compile, context, v) as Value; }) let choose = new builder(flow.context, branchFuncs, flow, outputs); let branchIx = 0; for(let branchId of constraint.branches) { let branch = items[branchId]; let compiled = choose.branches[branchIx]; inContext(compiled, () => { this.compileFlow(compile, compiled, branch.constraints); choose.setBranchInputs(branchIx, compiled.context.getInputReferences()); }) branchIx++; } }); } } } compileBlock(blockID:string) { let {inContext, items, compileValue} = this; let item = items[blockID]; let {name, constraints, type} = item; let compile:CompilationContext = {variables: {}}; let flow:LinearFlow; if(type === "commit") { flow = new CommitFlow((a) => []); } else if(type === "watch") { flow = new WatchFlow((a) => []); } else if(type === "bind") { flow = new LinearFlow((a) => []); } else { return; } this.compileFlow(compile, flow, constraints); let block = (this.programToInjectInto as any)[`_${type}`](name, flow); if(type === "watch" && item.watcher) { let func = this.watcherFunctions[item.watcher]; if(!func) { console.error("No such watcher function registered: " + item.watcher); } else { this.programToInjectInto.asDiffs(func); } } // if(typeof process === "undefined" && console.groupCollapsed) { // console.groupCollapsed("Compiled: " + block.name); // console.log(block, flow); // console.log(printBlock(block)); // console.groupEnd(); // } return block; } //------------------------------------------------------------------ // Compile item extraction via watch blocks //------------------------------------------------------------------ setup() { let {program:me} = this; me.bind("show errors", ({find, record}) => { let err = find("eve/compiler/error"); return [ record("ui/column", {err, class: "eve-compiler-error"}).add("children", [ record("ui/row", {err, class: "eve-compiler-error-message-container"}).add("children", [ record("ui/column", {err, class: "eve-compiler-line-info", sort:0}).add("children", [ record("ui/text", {err, text: `Line`, sort: 0}), record("ui/text", {err, class: "eve-compiler-error-message-line", text:err.start.line, sort: 1}), ]), record("ui/column", {err, class: "eve-compiler-error-content", sort:1}).add("children", [ record("ui/text", {err, class: "eve-compiler-error-message", text: err.message, sort: 0}), record("ui/text", {err, class: "eve-compiler-error-sample", text: err.sample, sort:1}) ]), ]), ]) ] }); me.watch("get blocks", ({find, record}) => { let block = find("eve/compiler/rule"); let {constraint, name, type} = block; return [ record({block, constraint, name, type}) ] }) me.asObjects<{block:string, name:string, constraint:string, type:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, name, constraint, type} = adds[key]; let found = items[block]; if(!found) { found = items[block] = {type, name, constraints: []}; } found.name = name; if(found.constraints.indexOf(constraint) === -1) { found.constraints.push(constraint); } this.queue(block); } for(let key in removes) { let {block, name, constraint} = removes[key]; let found = items[block]; if(!found) { continue; } let ix = found.constraints.indexOf(constraint) if(ix > -1) { found.constraints.splice(ix, 1); } if(found.constraints.length === 0) { delete items[block]; } this.queue(block); } }) me.watch("get nots", ({find, record}) => { let not = find("eve/compiler/not"); let block = find("eve/compiler/block", {constraint: not}); return [ record({block, not, constraint:not.constraint}) ] }) me.asObjects<{block:string, not:string, constraint:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, not, constraint} = adds[key]; let found = items[not]; if(!found) { found = items[not] = {type: "not", constraints: []}; } if(found.constraints.indexOf(constraint) === -1) { found.constraints.push(constraint); } this.queue(block); } for(let key in removes) { let {block, not, constraint} = removes[key]; let found = items[not]; if(!found) { continue; } let ix = found.constraints.indexOf(constraint) if(ix > -1) { found.constraints.splice(ix, 1); } if(found.constraints.length === 0) { delete items[not]; } this.queue(block); } }) me.watch("get choose branches", ({find, record, choose}) => { let item = find("eve/compiler/branch-set"); let [itemType] = choose(() => { item.tag == "eve/compiler/choose"; return ["choose"]; }, () => { item.tag == "eve/compiler/union"; return ["union"]; }) let block = find("eve/compiler/rule", {constraint: item}); return [ record({block, item, itemType, branch:item.branch}) ] }) me.asObjects<{block:string, item:string, itemType:string, branch:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, item, branch, itemType} = adds[key]; let found = items[item]; if(!found) { found = items[item] = {type: itemType, branches: [], outputs: []}; } if(!items[branch]) { items[branch] = {type: "branch", constraints: [], outputs: []}; } if(found.branches.indexOf(branch) === -1) { found.branches.push(branch); } this.queue(block); } for(let key in removes) { let {block, item, itemType, branch} = removes[key]; let found = items[item]; if(!found) { continue; } let ix = found.branches.indexOf(branch) if(ix > -1) { found.branches.splice(ix, 1); } if(found.branches.length === 0) { delete items[item]; } this.queue(block); } }) me.watch("get choose outputs", ({find, record}) => { let choose = find("eve/compiler/branch-set"); let block = find("eve/compiler/block", {constraint: choose}); let {value, index} = choose.output; return [ record({block, choose, value, index}) ] }) me.asObjects<{block:string, choose:string, value:RawValue, index:number}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, choose, value, index} = adds[key]; let found = items[choose]; if(!found) { console.error("adding output for a branch that doesn't exist") return; } found.outputs[index - 1] = value; this.queue(block); } for(let key in removes) { let {block, choose, value, index} = removes[key]; let found = items[choose]; if(!found) { continue; } let cur = found.outputs[index]; if(cur === value) { found.outputs[index - 1] = undefined; } this.queue(block); } }) me.watch("get choose branch constraints", ({find, record}) => { let choose = find("eve/compiler/branch-set"); let block = find("eve/compiler/block", {constraint: choose}); let {branch} = choose return [ record({block, branch, constraint:branch.constraint}) ] }) me.asObjects<{block:string, constraint:string, branch:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, constraint, branch} = adds[key]; let found = items[branch]; if(!found) { console.error("adding constraint for a branch that doesn't exist") return; } if(found.constraints.indexOf(constraint) === -1) { found.constraints.push(constraint); } this.queue(block); } for(let key in removes) { let {block, constraint, branch} = removes[key]; let found = items[branch]; if(!found) { continue; } let ix = found.constraints.indexOf(constraint) if(ix > -1) { found.constraints.splice(ix, 1); } if(found.constraints.length === 0) { delete items[branch]; } this.queue(block); } }) me.watch("get choose branch outputs", ({find, record}) => { let choose = find("eve/compiler/branch-set"); let block = find("eve/compiler/block", {constraint: choose}); let branch = choose.branch let {value, index} = branch.output return [ record({block, branch, value, index}) ] }) me.asObjects<{block:string, branch:string, value:RawValue, index:number}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, branch, value, index} = adds[key]; let found = items[branch]; if(!found) { console.error("adding output for a branch that doesn't exist") return; } found.outputs[index - 1] = value; this.queue(block); } for(let key in removes) { let {block, branch, value, index} = removes[key]; let found = items[branch]; if(!found) { continue; } let cur = found.outputs[index]; if(cur === value) { found.outputs[index - 1] = undefined; } this.queue(block); } }) me.watch("get watcher property", ({find, record}) => { let block = find("eve/compiler/rule"); let {constraint, name, type, watcher} = block; return [ record({block, watcher}) ] }) me.asObjects<{block:string, watcher:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, watcher} = adds[key]; let found = items[block]; found.watcher = watcher; this.queue(block); } for(let key in removes) { let {block, watcher} = removes[key]; let found = items[block]; if(!found) { continue; } found.watcher = undefined; this.queue(block); } }) me.watch("get variables", ({find, record}) => { let variable = find("eve/compiler/var"); return [ record({variable}) ] }) me.asObjects<{variable:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {variable} = adds[key]; items[variable] = {type: "variable"}; } }) me.watch("get equalities", ({find, record}) => { let eq = find("eve/compiler/equality"); return [ record({eq, left:eq.left, right:eq.right}) ] }) me.asObjects<{eq:string, left:RawValue, right:RawValue}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {eq, left, right} = adds[key]; items[eq] = {type: "equality", left, right}; } for(let key in removes) { let {eq} = removes[key]; items[eq] = undefined; } }) me.watch("get lookups", ({find, record}) => { let lookup = find("eve/compiler/lookup"); let block = find("eve/compiler/block", {constraint: lookup}); let {record:rec, attribute, value} = lookup; return [ record({block, id:lookup, record:rec, attribute, value}) ] }) me.asObjects<{block:string, id:string, record:string, attribute:string, value:RawValue}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, record, attribute, value} = adds[key]; items[id] = {type: "lookup", record: record, attribute, value}; this.queue(block); } for(let key in removes) { let {block, id, record, attribute, value} = removes[key]; delete items[id]; this.queue(block); } }) me.watch("get expressions", ({find, record, choose}) => { let expr = find("eve/compiler/expression"); let [type] = choose(() => { expr.tag == "eve/compiler/aggregate"; return ["aggregate"]; }, () => { return ["expression"]; }) let block = find("eve/compiler/block", {constraint: expr}); return [ record({block, id:expr, op:expr.op, type}) ] }) me.asObjects<{block:string, id:string, op:string, type:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, op, type} = adds[key]; let found = items[id]; if(!found) { found = items[id] = {type, op, args: [], returns: [], namedArgs: {}}; } found.op = op; this.queue(block); } for(let key in removes) { let {block, id, op} = removes[key]; let found = items[id]; if(!found) { continue; } delete items[id]; this.queue(block); } }) me.watch("get expression args", ({find, record}) => { let expr = find("eve/compiler/expression"); let block = find("eve/compiler/block", {constraint: expr}); let {arg} = expr; return [ record({block, id:expr, index:arg.index, value:arg.value}) ] }) me.asObjects<{block:string, id:string, index:number, value:RawValue}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, index, value} = adds[key]; let found = items[id]; if(!found) { throw new Error("args for a non existent expression"); } found.args[index - 1] = value; this.queue(block); } for(let key in removes) { let {block, id, index, value} = removes[key]; let found = items[id]; if(!found) { continue; } if(found.args[index - 1] == value) { found.args[index - 1] = undefined; } this.queue(block); } }) me.watch("get expression named args", ({find, record, not}) => { let expr = find("eve/compiler/expression"); not(() => { expr.tag == "eve/compiler/aggregate"; }) let block = find("eve/compiler/block", {constraint: expr}); let {arg} = expr; return [ record({block, id:expr, name:arg.name, value:arg.value, index:arg.index}) ] }) me.asObjects<{block:string, id:string, name:string, value:RawValue, index:number}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, name, value, index} = adds[key]; let found = items[id]; if(!found) { throw new Error("args for a non existent expression"); } let {argNames, returnNames} = FunctionConstraint.fetchInfo(found.op) let argIx = argNames.indexOf(name); let retIx = returnNames.indexOf(name); if(argIx > -1) { found.args[argIx] = value; } else if(retIx > -1) { found.returns[retIx] = value; } else { console.error(`Unknown arg for expression: ${found.op}[${name}]`); } this.queue(block); } for(let key in removes) { let {block, id, name, value} = removes[key]; let found = items[id]; if(!found) { continue; } let {argNames, returnNames} = FunctionConstraint.fetchInfo(found.op) let argIx = argNames.indexOf(name); let retIx = returnNames.indexOf(name); if(argIx > -1) { found.args[argIx] = undefined; } else if(retIx > -1) { found.returns[retIx] = undefined; } else { console.error(`Unknown arg for expression: ${found.op}[${name}]`); } this.queue(block); } }) me.watch("get aggregate named args", ({find, record, not}) => { let expr = find("eve/compiler/aggregate"); let block = find("eve/compiler/block", {constraint: expr}); let {arg} = expr; return [ record({block, id:expr, name:arg.name, value:arg.value, index:arg.index}) ] }) me.asObjects<{block:string, id:string, name:string, value:RawValue, index:number}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, name, value, index} = adds[key]; let found = items[id]; if(!found) { throw new Error("args for a non existent expression"); } let args = found.namedArgs[name] || []; args[index - 1] = value; found.namedArgs[name] = args; this.queue(block); } for(let key in removes) { let {block, id, name, value} = removes[key]; let found = items[id]; if(!found) { continue; } let args = found.namedArgs[name]; if(args) { let ix = args.indexOf(value); args.splice(ix, 1); } this.queue(block); } }) me.watch("get expression returns", ({find, record}) => { let expr = find("eve/compiler/expression"); let block = find("eve/compiler/block", {constraint: expr}); let {return:ret} = expr; return [ record({block, id:expr, index:ret.index, value:ret.value}) ] }) me.asObjects<{block:string, id:string, index:number, value:RawValue}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, index, value} = adds[key]; let found = items[id]; if(!found) { throw new Error("returns for a non existent expression"); } found.returns[index - 1] = value; this.queue(block); } for(let key in removes) { let {block, id, index, value} = removes[key]; let found = items[id]; if(!found) { continue; } if(found.returns[index - 1] == value) { found.returns[index - 1] = undefined; } this.queue(block); } }) me.watch("get records", ({find, record}) => { let compilerRecord = find("eve/compiler/record"); let block = find("eve/compiler/block", {constraint: compilerRecord}); let {record:id, attribute} = compilerRecord; return [ record({block, id:compilerRecord, record:id, attribute:attribute.attribute, value:attribute.value}) ] }) me.asObjects<{block:string, id:string, record:string, attribute:string, value:RawValue}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, record, attribute, value} = adds[key]; let found = items[id]; if(!found) { found = items[id] = {type: "record", attributes: [], record: record}; } found.attributes.push([attribute, value]); this.queue(block); } for(let key in removes) { let {block, id, record, attribute, value} = removes[key]; let found = items[id]; if(!found) { continue; } found.attributes = found.attributes.filter(([a, v]:RawValue[]) => a !== attribute || v !== value); if(found.attributes.length === 0) { delete items[id]; } this.queue(block); } }) me.watch("get outputs", ({find, record, choose}) => { let compilerRecord = find("eve/compiler/output"); let block = find("eve/compiler/block", {constraint: compilerRecord}); let {record:id, attribute} = compilerRecord; let [attributeType] = choose(() => { attribute.tag == "eve/compiler/attribute/non-identity"; return "non-identity"; }, () => { return "identity"; }); let [outputType] = choose(() => { compilerRecord.tag == "eve/compiler/remove"; return "remove"; }, () => { return "add"; }); return [ record({block, id:compilerRecord, record:id, attribute:attribute.attribute, value:attribute.value, attributeType, outputType}) ] }) me.asObjects<{block:string, id:string, record:string, attribute:string, value:RawValue, attributeType:string, outputType:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, record, attribute, value, attributeType, outputType} = adds[key]; let found = items[id]; if(!found) { found = items[id] = {type: "output", attributes: [], nonIdentityAttribute:[], record: record, outputType}; } if(attributeType === "identity") { found.attributes.push([attribute, value]); } else { found.nonIdentityAttribute.push([attribute, value]); } this.queue(block); } for(let key in removes) { let {block, id, record, attribute, value} = removes[key]; let found = items[id]; if(!found) { continue; } found.attributes = found.attributes.filter(([a, v]:RawValue[]) => a !== attribute || v !== value); found.nonIdentityAttribute = found.nonIdentityAttribute.filter(([a, v]:RawValue[]) => a !== attribute || v !== value); if(found.attributes.length === 0) { delete items[id]; } this.queue(block); } }) me.watch("get valueless outputs", ({find, record, choose, not}) => { let compilerRecord = find("eve/compiler/output"); let block = find("eve/compiler/block", {constraint: compilerRecord}); let {attribute} = compilerRecord; not(() => attribute.value) return [ record({block, id:compilerRecord, record:compilerRecord.record, attribute:attribute.attribute}) ] }) me.asObjects<{block:string, id:string, record:string, attribute:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, record, attribute} = adds[key]; let found = items[id]; if(!found) { found = items[id] = {type: "output", attributes: [], nonIdentityAttribute:[], record: record, outputType:"remove"}; } found.nonIdentityAttribute.push([attribute, undefined]); this.queue(block); } for(let key in removes) { let {block, id, attribute} = removes[key]; let found = items[id]; if(!found) { continue; } found.nonIdentityAttribute = found.nonIdentityAttribute.filter(([a, v]:RawValue[]) => a !== attribute || v !== undefined); if(found.nonIdentityAttribute.length === 0) { delete items[id]; } this.queue(block); } }) me.watch("get full remove", ({find, record, choose, not}) => { let compilerRecord = find("eve/compiler/remove"); let block = find("eve/compiler/block", {constraint: compilerRecord}); not(() => compilerRecord.attribute); return [ record({block, id:compilerRecord, record:compilerRecord.record}) ] }) me.asObjects<{block:string, id:string, record:string}>(({adds, removes}) => { let {items} = this; for(let key in adds) { let {block, id, record} = adds[key]; let found = items[id]; if(!found) { found = items[id] = {type: "removeRecord", record: record}; } this.queue(block); } for(let key in removes) { let {block, id} = removes[key]; let found = items[id]; if(!found) { continue; } delete items[id]; this.queue(block); } }) } } Watcher.register("compiler", CompilerWatcher);
the_stack
import { Bitmap16, DIBitmap, PatternBitmap16 } from "./Bitmap"; import { Blob } from "./Blob"; import { Helper } from "./Helper"; import { Obj, PointS } from "./Primitives"; export class ColorRef { public r: number; public g: number; public b: number; constructor(reader: Blob, r?: number, g?: number, b?: number) { if (reader != null) { this.r = reader.readUint8(); this.g = reader.readUint8(); this.b = reader.readUint8(); reader.skip(1); } else { this.r = r; this.g = g; this.b = b; } } public clone(): ColorRef { return new ColorRef(null, this.r, this.g, this.b); } public toHex(): string { const rgb = (this.r << 16) | (this.g << 8) | this.b; return (0x1000000 + rgb).toString(16).slice(1); } public toString(): string { return "{r: " + this.r + ", g: " + this.g + ", b: " + this.b + "}"; } } export class Font extends Obj { public height: number; public width: number; public escapement: number; public orientation: number; public weight: number; public italic: number; public underline: number; public strikeout: number; public charset: number; public outprecision: number; public clipprecision: number; public quality: number; public pitch: number; public family: number; public facename: string; constructor(reader: Blob, copy: Font | number) { super("font"); if (reader != null) { this.height = reader.readInt16(); this.width = reader.readInt16(); this.escapement = reader.readInt16(); this.orientation = reader.readInt16(); this.weight = reader.readInt16(); this.italic = reader.readUint8(); this.underline = reader.readUint8(); this.strikeout = reader.readUint8(); this.charset = reader.readUint8(); this.outprecision = reader.readUint8(); this.clipprecision = reader.readUint8(); this.quality = reader.readUint8(); const pitchAndFamily = reader.readUint8(); this.pitch = pitchAndFamily & 0xf; // TODO: double check this.family = (pitchAndFamily >> 6) & 0x3; // TODO: double check const dataLength = copy as number; const start = reader.pos; this.facename = reader.readNullTermString(Math.min(dataLength - (reader.pos - start), 32)); } else if (copy != null) { copy = copy as Font; this.height = copy.height; this.width = copy.width; this.escapement = copy.escapement; this.orientation = copy.orientation; this.weight = copy.weight; this.italic = copy.italic; this.underline = copy.underline; this.strikeout = copy.strikeout; this.charset = copy.charset; this.outprecision = copy.outprecision; this.clipprecision = copy.clipprecision; this.quality = copy.quality; this.pitch = copy.pitch; this.family = copy.family; this.facename = copy.facename; } else { // TODO: Values for a default font? this.height = -80; this.width = 0; this.escapement = 0; this.orientation = 0; this.weight = 400; this.italic = 0; this.underline = 0; this.strikeout = 0; this.charset = 0; this.outprecision = 0; this.clipprecision = 0; this.quality = 0; this.pitch = 0; this.family = 0; this.facename = "Helvetica"; } } public clone(): Font { return new Font(null, this); } public toString(): string { return JSON.stringify(this); } } export class Brush extends Obj { public style: number; public color: ColorRef; public pattern: Bitmap16; public colorusage: number; public dibpatternpt: DIBitmap; public hatchstyle: number; constructor(reader: Blob, copy: Brush | number, forceDibPattern?: boolean | PatternBitmap16) { super("brush"); if (reader != null) { const dataLength = copy as number; const start = reader.pos; if (forceDibPattern === true || forceDibPattern === false) { this.style = reader.readUint16(); if (forceDibPattern && this.style !== Helper.GDI.BrushStyle.BS_PATTERN) { this.style = Helper.GDI.BrushStyle.BS_DIBPATTERNPT; } switch (this.style) { case Helper.GDI.BrushStyle.BS_SOLID: this.color = new ColorRef(reader); break; case Helper.GDI.BrushStyle.BS_PATTERN: reader.skip(forceDibPattern ? 2 : 6); this.pattern = new Bitmap16(reader, dataLength - (reader.pos - start)); break; case Helper.GDI.BrushStyle.BS_DIBPATTERNPT: this.colorusage = forceDibPattern ? reader.readUint16() : reader.readUint32(); if (!forceDibPattern) { reader.skip(2); } this.dibpatternpt = new DIBitmap(reader, dataLength - (reader.pos - start)); break; case Helper.GDI.BrushStyle.BS_HATCHED: this.color = new ColorRef(reader); this.hatchstyle = reader.readUint16(); break; } } else if (forceDibPattern instanceof PatternBitmap16) { this.style = Helper.GDI.BrushStyle.BS_PATTERN; this.pattern = forceDibPattern; } } else if (copy != null) { copy = copy as Brush; this.style = copy.style; switch (this.style) { case Helper.GDI.BrushStyle.BS_SOLID: this.color = copy.color.clone(); break; case Helper.GDI.BrushStyle.BS_PATTERN: this.pattern = copy.pattern.clone(); break; case Helper.GDI.BrushStyle.BS_DIBPATTERNPT: this.colorusage = copy.colorusage; this.dibpatternpt = copy.dibpatternpt; break; case Helper.GDI.BrushStyle.BS_HATCHED: this.color = copy.color.clone(); this.hatchstyle = copy.hatchstyle; break; } } } public clone(): Brush { return new Brush(null, this); } public toString(): string { let ret = "{style: " + this.style; switch (this.style) { case Helper.GDI.BrushStyle.BS_SOLID: ret += ", color: " + this.color.toString(); break; case Helper.GDI.BrushStyle.BS_DIBPATTERNPT: ret += ", colorusage: " + this.colorusage; break; case Helper.GDI.BrushStyle.BS_HATCHED: ret += ", color: " + this.color.toString() + ", hatchstyle: " + this.hatchstyle; break; } return ret + "}"; } } export class Pen extends Obj { public style: number; public width: PointS; public color: ColorRef; public linecap: number; public join: number; constructor(reader: Blob, style?: number, width?: PointS, color?: ColorRef, linecap?: number, join?: number) { super("pen"); if (reader != null) { style = reader.readUint16(); this.style = style & 0xFF; this.width = new PointS(reader); this.color = new ColorRef(reader); this.linecap = (style & (Helper.GDI.PenStyle.PS_ENDCAP_SQUARE | Helper.GDI.PenStyle.PS_ENDCAP_FLAT)); this.join = (style & (Helper.GDI.PenStyle.PS_JOIN_BEVEL | Helper.GDI.PenStyle.PS_JOIN_MITER)); } else { this.style = style; this.width = width; this.color = color; this.linecap = linecap; this.join = join; } } public clone(): Pen { return new Pen(null, this.style, this.width.clone(), this.color.clone(), this.linecap, this.join); } public toString(): string { return "{style: " + this.style + ", width: " + this.width.toString() + ", color: " + this.color.toString() + ", linecap: " + this.linecap + ", join: " + this.join + "}"; } } export class PaletteEntry { public flag: number; public b: number; public g: number; public r: number; constructor(reader: Blob, copy?: PaletteEntry) { if (reader != null) { this.flag = reader.readUint8(); this.b = reader.readUint8(); this.g = reader.readUint8(); this.r = reader.readUint8(); } else { this.flag = copy.flag; this.b = copy.b; this.g = copy.g; this.r = copy.r; } } public clone(): PaletteEntry { return new PaletteEntry(null, this); } } export class Palette extends Obj { public start: number; public entries: PaletteEntry[]; constructor(reader: Blob, copy?: Palette) { super("palette"); if (reader != null) { this.start = reader.readUint16(); let cnt = reader.readUint16(); this.entries = []; while (cnt > 0) { this.entries.push(new PaletteEntry(reader)); cnt--; } } else { this.start = copy.start; this.entries = []; const len = copy.entries.length; for (let i = 0; i < len; i++) { this.entries.push(copy.entries[i]); } } } public clone(): Palette { return new Palette(null, this); } public toString(): string { return "{ #entries: " + this.entries.length + "}"; // TODO } }
the_stack
import react = require('react'); import react_dom = require('react-dom'); import style = require('ts-style'); import agile_keychain_crypto = require('../lib/agile_keychain_crypto'); import button = require('./controls/button'); import colors = require('./controls/colors'); import { div } from './base/dom_factory'; import env = require('../lib/base/env'); import fonts = require('./controls/fonts'); import item_builder = require('../lib/item_builder'); import item_icons = require('./item_icons'); import item_field = require('./item_field'); import item_list = require('./item_list_view'); import item_store = require('../lib/item_store'); import keycodes = require('./base/keycodes'); import menu = require('./controls/menu'); import browser_access = require('./browser_access'); import reactutil = require('./base/reactutil'); import shortcut = require('./base/shortcut'); import style_util = require('./base/style_util'); import toolbar = require('./toolbar'); import url_util = require('../lib/base/url_util'); var DIVIDER_BORDER_STYLE = '1px solid ' + colors.MATERIAL_COLOR_DIVIDER; var DETAILS_VIEW_Z_LAYER = 2; var theme = style.create( { toolbarSpacer: { flexGrow: '1', }, content: { flexGrow: 1, }, coreFields: { paddingTop: 5, paddingBottom: 5, }, section: { title: { fontSize: fonts.caption.size, fontWeight: fonts.caption.weight, color: colors.MATERIAL_TEXT_SECONDARY, height: 48, display: 'flex', flexDirection: 'column', justifyContent: 'center', // add negative margin below title to get // even spacing between divider line separating // this from the previous section and the label // of the first field in this section marginBottom: -12, }, divider: { width: '100%', borderBottom: DIVIDER_BORDER_STYLE, }, }, divider: { width: '100%', borderBottom: DIVIDER_BORDER_STYLE, marginTop: 12, marginBottom: 12, }, itemActionBar: { paddingLeft: 10, paddingRight: 10, paddingTop: 10, paddingBottom: 5, marginBottom: 10, }, container: { backgroundColor: 'white', position: 'absolute', transition: style_util.transitionOn({ left: 0.3, top: 0.3, width: 0.3, height: 0.3, }), zIndex: DETAILS_VIEW_Z_LAYER, display: 'flex', flexDirection: 'column', // disable the focus ring around the // edge of the details view when focused ':focus': { outline: 0, }, }, header: { backgroundColor: 'transparent', flexShrink: 0, boxShadow: 'none', // padding chosen to match icon padding in item list // for item list -> details view transition paddingLeft: 16, transition: style_util.transitionOn({ all: 0.2, color: 0.01, }), toolbar: { position: 'absolute', left: 0, top: 0, right: 0, height: 40, display: 'flex', flexDirection: 'row', alignItems: 'center', }, iconAndDetails: { display: 'flex', flexDirection: 'row', details: { marginLeft: 16, display: 'flex', flexDirection: 'column', position: 'relative', flexGrow: 1, // style for the container of the title and account fields // at the start of the entry transition for the details // view itemList: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, transition: style_util.transitionOn({ opacity: 0.2 }), opacity: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', }, // style for the container of the title and account // fields in the details view detailsView: { position: 'relative', right: 0, top: 0, bottom: 0, color: 'white', transition: style_util.transitionOn({ opacity: 0.2 }), opacity: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', }, }, }, entered: { backgroundColor: colors.MATERIAL_COLOR_PRIMARY, paddingTop: 40, paddingBottom: 15, boxShadow: 'rgba(0, 0, 0, 0.26) 0px 2px 5px 0px', }, title: { fontSize: fonts.headline.size, }, account: { fontSize: fonts.itemSecondary.size, }, }, }, __filename ); export enum ItemEditMode { AddItem, EditItem, } export interface DetailsViewProps extends react.Props<void> { entryRect?: reactutil.Rect; viewportRect: reactutil.Rect; animateEntry: boolean; item: item_store.Item; iconProvider: item_icons.IconProvider; clipboard: browser_access.ClipboardAccess; editMode: ItemEditMode; focus: boolean; currentUrl: string; onGoBack: () => any; onSave: (updates: item_store.ItemAndContent) => any; autofill: () => void; } interface AddingFieldState { section: item_store.ItemSection; pos: { left: number; top: number; }; } interface DetailsViewState { itemContent?: item_store.ItemContent; editedItem?: item_store.ItemAndContent; isEditing?: boolean; didEditItem?: boolean; transition?: reactutil.TransitionState; autofocusField?: | item_store.ItemField | item_store.ItemUrl | item_store.ItemSection; addingField?: AddingFieldState; editingFieldLabel?: item_store.ItemField; } export class DetailsView extends react.Component< DetailsViewProps, DetailsViewState > { private shortcuts: shortcut.Shortcut[]; private transitionHandler: reactutil.TransitionEndListener; private mounted: boolean; constructor(props: DetailsViewProps) { super(props); var isEditing = this.props.editMode === ItemEditMode.AddItem; var transitionState: reactutil.TransitionState; if (this.props.animateEntry) { transitionState = reactutil.TransitionState.WillEnter; } else { transitionState = reactutil.TransitionState.Entered; } this.state = { isEditing: isEditing, didEditItem: isEditing, transition: transitionState, }; } componentWillReceiveProps(nextProps: DetailsViewProps) { if (!nextProps.item) { return; } if (!this.props.item || this.props.item != nextProps.item) { // forget previous item content when switching items this.setState({ itemContent: null, editedItem: null, // start in 'view details' mode initially unless // adding a new item isEditing: nextProps.editMode == ItemEditMode.AddItem, didEditItem: false, }); this.fetchContent(nextProps.item); } } componentWillMount() { this.fetchContent(this.props.item); } componentDidUpdate(prevProps: DetailsViewProps) { if (!prevProps.focus && this.props.focus) { const el = react_dom.findDOMNode(this) as HTMLElement; el.focus(); } } componentDidMount() { this.mounted = true; let root = <HTMLElement>react_dom.findDOMNode(this); root.focus(); this.shortcuts = [ new shortcut.Shortcut(root, keycodes.Backspace, () => { this.exit(); }), new shortcut.Shortcut(root, keycodes.a, () => { this.props.autofill(); }), ]; if (this.state.transition !== reactutil.TransitionState.Entered) { setTimeout(() => { this.setState({ transition: reactutil.TransitionState.Entered, }); }, 10); } this.transitionHandler = new reactutil.TransitionEndListener( this, 'top', () => { if ( this.state.transition === reactutil.TransitionState.Leaving ) { this.props.onGoBack(); } } ); } componentWillUnmount() { this.mounted = false; this.shortcuts.forEach(shortcut => { shortcut.remove(); }); this.shortcuts = []; this.transitionHandler.remove(); } private fetchContent(item: item_store.Item) { item.getContent().then(content => { if (!this.mounted) { return; } this.setState({ itemContent: content }); this.resetEdits({ item: item, content: content }); }); } private resetEdits(base: item_store.ItemAndContent) { var editedItem = item_store.cloneItem(base, base.item.uuid); this.setState({ editedItem: editedItem }); } private renderSections( item: item_store.ItemAndContent, onSave: () => void, editing: boolean ) { var sections: react.ReactElement<{}>[] = []; item.content.sections.forEach((section, sectionIndex) => { var fields: react.ReactElement<{}>[] = []; section.fields.forEach((field, fieldIndex) => { var autofocus = this.state.autofocusField === field; var labelChangeHandler: (newValue: string) => boolean; if (field === this.state.editingFieldLabel) { labelChangeHandler = newValue => { field.title = newValue; onSave(); return true; }; } fields.push( item_field.ItemFieldF({ key: section.name + '.' + field.name, label: field.title, value: field.value, type: field.kind == item_store.FieldType.Password ? item_field.FieldType.Password : item_field.FieldType.Text, clipboard: this.props.clipboard, onChange: newValue => { field.value = newValue; onSave(); return true; }, onDelete: () => { section.fields.splice(fieldIndex, 1); onSave(); }, onChangeLabel: labelChangeHandler, readOnly: !editing, focused: autofocus, }) ); }); if (sectionIndex > 0) { sections.push(div(style.mixin(theme.section.divider))); } if (section.title || editing) { if (editing) { var autofocus = this.state.autofocusField === section; sections.push( item_field.ItemFieldF({ key: section.name + '.title', label: 'Section Title', deleteLabel: 'Delete Section', value: section.title, type: item_field.FieldType.Text, clipboard: this.props.clipboard, onChange: newValue => { section.title = newValue; onSave(); return true; }, onDelete: () => { item.content.sections.splice(sectionIndex, 1); onSave(); }, readOnly: false, focused: autofocus, }) ); } else { sections.push( div(style.mixin(theme.section.title), section.title) ); } } sections.push(div({}, fields)); if (editing) { var addButtonRef = sectionIndex + '.addField'; sections.push( button.ButtonF({ style: button.Style.Rectangular, value: 'Add Field', color: colors.MATERIAL_COLOR_PRIMARY, ref: addButtonRef, onClick: e => { var buttonRect = (<HTMLElement>react_dom.findDOMNode( this.refs[addButtonRef] )).getBoundingClientRect(); this.setState({ addingField: { pos: { top: buttonRect.top, left: buttonRect.left, }, section: section, }, }); }, }) ); } }); if (editing) { sections.push( button.ButtonF({ style: button.Style.Rectangular, value: 'Add Section', color: colors.MATERIAL_COLOR_PRIMARY, onClick: () => { let newSection: item_store.ItemSection = { name: agile_keychain_crypto.newUUID(), title: 'New Section', fields: [], }; item.content.sections.push(newSection); this.setState({ autofocusField: newSection }); this.onChangeItem(); }, }) ); } return sections; } private renderWebsites( item: item_store.ItemAndContent, onSave: () => void, editing: boolean ) { var websites: react.ReactElement<{}>[] = []; item.content.urls.forEach((url, urlIndex) => { var autofocus = this.state.autofocusField === url; websites.push( item_field.ItemFieldF({ key: urlIndex, label: url.label, value: url.url, type: item_field.FieldType.Url, clipboard: this.props.clipboard, onChange: newValue => { url.url = newValue; onSave(); return true; }, onDelete: () => { item.content.urls.splice(urlIndex, 1); onSave(); }, readOnly: !editing, focused: autofocus, }) ); }); if (editing) { websites.push( button.ButtonF({ value: 'Add Website', style: button.Style.Rectangular, color: colors.MATERIAL_COLOR_PRIMARY, onClick: e => { var newUrl = { label: 'website', url: this.props.currentUrl, }; this.state.editedItem.content.urls.push(newUrl); this.setState({ autofocusField: newUrl }); onSave(); }, }) ); } return websites; } private renderCoreFields( item: item_store.ItemAndContent, onSave: () => void, editing: boolean ) { let coreFields: react.ReactElement<{}>[] = []; let accountField = item_store.ContentUtil.accountField(item.content); let passwordField = item_store.ContentUtil.passwordField(item.content); if (accountField) { coreFields.push( item_field.ItemFieldF({ key: 'account', label: 'Account', value: accountField ? accountField.value : '', type: item_field.FieldType.Text, clipboard: this.props.clipboard, onChange: newValue => { if (accountField) { accountField.value = newValue; } else { item.content.formFields.push( item_builder.Builder.createLoginField(newValue) ); } onSave(); return true; }, readOnly: !editing, }) ); } if (passwordField) { coreFields.push( item_field.ItemFieldF({ key: 'password', label: 'Password', value: passwordField ? passwordField.value : '', type: item_field.FieldType.Password, clipboard: this.props.clipboard, onChange: newValue => { if (passwordField) { passwordField.value = newValue; } else { item.content.formFields.push( item_builder.Builder.createPasswordField( newValue ) ); } onSave(); return true; }, readOnly: !editing, }) ); } return coreFields; } private renderMenus() { var addField = (type: item_store.FieldType) => { let field: item_store.ItemField = { name: agile_keychain_crypto.newUUID(), kind: type, value: '', title: 'New Field', }; this.setState({ autofocusField: field, editingFieldLabel: field, }); this.state.addingField.section.fields.push(field); this.onChangeItem(); }; var fieldTypes = [ { label: 'Text', onClick: () => { addField(item_store.FieldType.Text); }, }, { label: 'Password', onClick: () => { addField(item_store.FieldType.Password); }, }, ]; var newFieldMenu: react.ReactElement<menu.MenuProps>; if (this.state.addingField) { newFieldMenu = menu.MenuF({ items: fieldTypes, sourceRect: { top: this.state.addingField.pos.top, left: this.state.addingField.pos.left, right: this.state.addingField.pos.left, bottom: this.state.addingField.pos.top, }, viewportRect: this.props.viewportRect, onDismiss: () => { this.setState({ addingField: null }); }, zIndex: 1, }); } return reactutil.TransitionGroupF({}, newFieldMenu); } private renderToolbar() { var toolbarControls: react.ReactElement<any>[] = []; if ( this.props.editMode == ItemEditMode.EditItem && !this.state.isEditing ) { toolbarControls.push( toolbar.createButton({ value: 'Back', iconUrl: 'dist/icons/icons.svg#arrow-back', onClick: () => { this.exit(); }, key: 'back', }) ); } else { toolbarControls.push( toolbar.createButton({ value: 'Cancel', iconUrl: 'dist/icons/icons.svg#clear', onClick: () => { if (this.props.editMode == ItemEditMode.EditItem) { this.resetEdits({ item: this.props.item, content: this.state.itemContent, }); this.setState({ isEditing: false, didEditItem: false, }); } else { this.exit(); } }, key: 'cancel', }) ); } toolbarControls.push(div(style.mixin(theme.toolbarSpacer))); var editOrSave: react.ReactElement<button.ButtonProps>; if (this.state.isEditing) { editOrSave = toolbar.createButton({ value: 'Save', iconUrl: 'dist/icons/icons.svg#done', onClick: () => { if (this.state.didEditItem) { this.props.onSave(this.state.editedItem); } this.setState({ isEditing: false, didEditItem: false, editingFieldLabel: null, }); // go back to main item list after adding a new item if (this.props.editMode == ItemEditMode.AddItem) { this.props.onGoBack(); } }, key: 'save', }); } else { editOrSave = toolbar.createButton({ value: 'Edit', iconUrl: 'dist/icons/icons.svg#edit', onClick: () => { this.setState({ isEditing: true }); }, key: 'edit', }); } toolbarControls.push( div( style.mixin([ item_list.theme.toolbar.iconGroup, { position: 'relative', width: 45, overflow: 'hidden', }, ]), editOrSave ) ); return div(style.mixin(theme.header.toolbar), toolbarControls); } private onChangeItem() { var updatedItem = this.state.editedItem; updatedItem.item.updateOverviewFromContent(updatedItem.content); this.setState({ editedItem: updatedItem, didEditItem: true, }); } private renderFields(editing: boolean) { var detailsContent: react.ReactElement<any>; var updatedItem = this.state.editedItem; if (updatedItem) { var onChangeItem = () => { this.onChangeItem(); }; var titleField: react.ReactElement<any>; if (editing) { titleField = item_field.ItemFieldF({ label: 'Title', value: updatedItem.item.title, type: item_field.FieldType.Text, clipboard: this.props.clipboard, onChange: newValue => { updatedItem.item.title = newValue; onChangeItem(); return true; }, readOnly: false, }); } var coreFields = this.renderCoreFields( updatedItem, onChangeItem, editing ); var sections = this.renderSections( updatedItem, onChangeItem, editing ); var websites = this.renderWebsites( updatedItem, onChangeItem, editing ); var contentKey = 'content'; if (editing) { contentKey += '-editing'; } var sectionDivider: react.ReactElement<{}>; if (websites.length > 0 && sections.length > 0) { sectionDivider = div(style.mixin(theme.divider)); } var itemActionDivider: react.ReactElement<{}>; var itemActions: react.ReactElement<{}>[] = []; if (editing && this.props.editMode === ItemEditMode.EditItem) { var isTrashed = updatedItem.item.trashed; itemActions.push( button.ButtonF({ style: button.Style.Rectangular, color: isTrashed ? colors.MATERIAL_COLOR_PRIMARY : colors.MATERIAL_RED_P500, value: isTrashed ? 'Restore from Trash' : 'Move to Trash', onClick: () => { updatedItem.item.trashed = !isTrashed; onChangeItem(); }, }) ); } if (itemActions.length > 0) { itemActionDivider = div(style.mixin(theme.divider)); } detailsContent = div( style.mixin(theme.content, { key: contentKey }), titleField, div(style.mixin(theme.coreFields), coreFields), div({}, websites), sectionDivider, div({}, sections), itemActionDivider, div({}, itemActions) ); } return detailsContent; } private exit() { this.setState({ transition: reactutil.TransitionState.Leaving }); } render() { var viewStyles: any[] = []; viewStyles.push(theme.container); // expand the details view starting from the rect // for the selected item if (this.state.transition !== reactutil.TransitionState.Entered) { if (this.props.entryRect) { viewStyles.push({ left: this.props.entryRect.left, width: this.props.entryRect.right - this.props.entryRect.left, top: this.props.entryRect.top, height: this.props.entryRect.bottom - this.props.entryRect.top, }); } else { viewStyles.push({ left: 0, width: '100%', top: 100, height: 0, }); } } else { viewStyles.push({ left: 0, width: '100%', top: 0, height: '100%', }); } var headerStyles: any[] = []; headerStyles.push(theme.header); if (this.state.transition === reactutil.TransitionState.Entered) { headerStyles.push(theme.header.entered); } var headerTheme = theme.header; var itemListDetailsStyle: any[] = [ headerTheme.iconAndDetails.details.itemList, ]; var detailsViewDetailsStyle: any[] = [ headerTheme.iconAndDetails.details.detailsView, ]; var contentStyles: reactutil.ExtendedCSSProperties[] = [ { paddingTop: 16, // vertically align left edge of details text with item // title // // <16px> [Icon (48px)] <16px> [Item Title] // paddingLeft: 80, opacity: 0, transition: style_util.transitionOn({ opacity: 0.5 }), overflowY: 'auto', flexGrow: 1, }, ]; if (this.state.transition === reactutil.TransitionState.Entered) { itemListDetailsStyle.push({ opacity: 0 }); detailsViewDetailsStyle.push({ opacity: 1 }); contentStyles.push({ opacity: 1 }); } var autofillButton: react.ReactElement<{}>; var autofillSupported = env.isChromeExtension(); if (!this.state.isEditing && autofillSupported) { autofillButton = div( style.mixin({ position: 'absolute', right: 16, bottom: 16, }), button.ButtonF({ style: button.Style.FloatingAction, backgroundColor: colors.MATERIAL_COLOR_PRIMARY, color: colors.MATERIAL_COLOR_HEADER, rippleColor: 'white', onClick: () => this.props.autofill(), value: 'Autofill', iconUrl: 'dist/icons/icons.svg#input', }) ); } var updatedItem: item_store.Item; if (this.state.editedItem) { updatedItem = this.state.editedItem.item; } else { updatedItem = this.props.item; } return div( style.mixin(viewStyles, { tabIndex: 0 }), div( style.mixin(headerStyles), this.renderToolbar(), this.renderMenus(), div( style.mixin(headerTheme.iconAndDetails), item_icons.IconControlF({ location: updatedItem.primaryLocation(), iconProvider: this.props.iconProvider, isFocused: true, onClick: () => { var url = url_util.normalize( updatedItem.primaryLocation() ); var siteWindow = window.open(url, '_blank'); siteWindow.focus(); }, title: `Open ${updatedItem.primaryLocation()} in a new tab`, }), div( style.mixin(headerTheme.iconAndDetails.details), // item title and account at start of entry transition div( style.mixin(itemListDetailsStyle), div( style.mixin(item_list.theme.item.details.title), updatedItem.title ), div( style.mixin( item_list.theme.item.details.account ), updatedItem.account ) ), // item title and account at end of entry transition div( style.mixin(detailsViewDetailsStyle), div( style.mixin(theme.header.title), updatedItem.title ), div( style.mixin(theme.header.account), updatedItem.account ) ) ) ) ), div( style.mixin(contentStyles), autofillButton, this.renderFields(this.state.isEditing) ) ); } } export var DetailsViewF = react.createFactory(DetailsView);
the_stack
import * as vscode from "vscode"; import * as utils from "./utils"; import * as path from 'path'; import { Constants } from "./constants"; import { LeoIntegration } from "./leoIntegration"; import { BodyTimeInfo } from "./types"; /** * * Body panes implementation as a file system using "leo" as a scheme identifier * Saving and renaming prevents flickering and prevents undos to 'traverse through' different gnx */ export class LeoBodyProvider implements vscode.FileSystemProvider { // * Flag normally false public preventSaveToLeo: boolean = false; private _errorRefreshFlag: boolean = false; // * Last file read data with the readFile method private _lastGnx: string = ""; // gnx of last file read private _lastBodyData: string = ""; // body content of last file read private _lastBodyLength: number = 0; // length of last file read // * List of currently opened body panes gnx (from 'watch' & 'dispose' methods) private _watchedBodiesGnx: string[] = []; // * List of gnx that should be available (from more.selectNode and fs.delete) private _openedBodiesGnx: string[] = []; private _openedBodiesInfo: { [key: string]: BodyTimeInfo } = {}; // * List of all possible vNodes gnx in the currently opened leo file (since last refresh/tree operation) private _possibleGnxList: string[] = []; // Maybe deprecated private _lastBodyTimeGnx: string = ""; // * An event to signal that a resource has been changed // * It should fire for resources that are being [watched](#FileSystemProvider.watch) by clients of this provider private _onDidChangeFileEmitter = new vscode.EventEmitter<vscode.FileChangeEvent[]>(); readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this._onDidChangeFileEmitter.event; private _bufferedEvents: vscode.FileChangeEvent[] = []; private _fireSoonHandle?: NodeJS.Timer; constructor(private _leoIntegration: LeoIntegration) { } /** * * Sets selected node body's modified time for this gnx virtual file * @param p_uri URI of file for which to set made-up modified time */ public setBodyTime(p_uri: vscode.Uri): void { const w_gnx = utils.leoUriToStr(p_uri); this._lastBodyTimeGnx = w_gnx; if (!this._openedBodiesGnx.includes(w_gnx)) { this._openedBodiesGnx.push(w_gnx); } const w_now = new Date().getTime(); this._openedBodiesInfo[w_gnx] = { ctime: w_now, mtime: w_now }; } /** * * Refresh the body pane for a particular gnx by telling vscode that the file from the Leo file provider has changed * @param p_gnx Gnx of body associated with this virtual file, mostly Leo's selected node */ public fireRefreshFile(p_gnx: string): void { if (!this._openedBodiesGnx.includes(p_gnx)) { console.error("ASKED TO REFRESH NOT EVEN IN SELECTED BODY: ", p_gnx); this._openedBodiesGnx.push(p_gnx); } const w_now = new Date().getTime(); this._openedBodiesInfo[p_gnx] = { ctime: w_now, mtime: w_now }; this._onDidChangeFileEmitter.fire([{ type: vscode.FileChangeType.Changed, uri: utils.strToLeoUri(p_gnx) } as vscode.FileChangeEvent]); } /** * Maybe deprecated * * Refreshes the '_possibleGnxList' list of all unique gnx from Leo * @returns a promise that resolves to the fresh gnx string array */ public refreshPossibleGnxList(): Thenable<string[]> { // * Get updated list of possible gnx return this._leoIntegration.sendAction( Constants.LEOBRIDGE.GET_ALL_GNX ).then((p_result) => { this._possibleGnxList = p_result.gnx || []; return Promise.resolve(this._possibleGnxList); }); } public watch(p_resource: vscode.Uri): vscode.Disposable { const w_gnx = utils.leoUriToStr(p_resource); if (!this._watchedBodiesGnx.includes(w_gnx)) { this._watchedBodiesGnx.push(w_gnx); // add gnx } else { } return new vscode.Disposable(() => { const w_position = this._watchedBodiesGnx.indexOf(w_gnx); // find and remove it if (w_position > -1) { this._watchedBodiesGnx.splice(w_position, 1); } }); } public stat(p_uri: vscode.Uri): vscode.FileStat | Thenable<vscode.FileStat> { // TODO : Fix/Check extraneous stat(...) call(s) if (this._leoIntegration.leoStates.fileOpenedReady) { const w_gnx = utils.leoUriToStr(p_uri); if (p_uri.fsPath.length === 1) { // p_uri.fsPath === '/' || p_uri.fsPath === '\\' return { type: vscode.FileType.Directory, ctime: 0, mtime: 0, size: 0 }; } else if (w_gnx === this._lastGnx && this._openedBodiesGnx.includes(this._lastGnx)) { return { type: vscode.FileType.File, ctime: this._openedBodiesInfo[this._lastGnx].ctime, mtime: this._openedBodiesInfo[this._lastGnx].mtime, size: this._lastBodyLength }; } else if (this._openedBodiesGnx.includes(w_gnx)) { return this._leoIntegration.sendAction( Constants.LEOBRIDGE.GET_BODY_LENGTH, JSON.stringify({ "gnx": w_gnx }) ).then((p_result) => { return Promise.resolve( { type: vscode.FileType.File, ctime: this._openedBodiesInfo[w_gnx].ctime, mtime: this._openedBodiesInfo[w_gnx].mtime, size: p_result.len ? p_result.len : 0 } ); }); } } // throw vscode.FileSystemError.FileNotFound(); // (Instead of FileNotFound) should be caught by _onActiveEditorChanged or _changedVisibleTextEditors return { type: vscode.FileType.File, ctime: 0, mtime: 0, size: 0 }; } public readFile(p_uri: vscode.Uri): Thenable<Uint8Array> { if (this._leoIntegration.leoStates.fileOpenedReady) { if (p_uri.fsPath.length === 1) { // p_uri.fsPath === '/' || p_uri.fsPath === '\\' throw vscode.FileSystemError.FileIsADirectory(); } else { const w_gnx = utils.leoUriToStr(p_uri); // if (!this._possibleGnxList.includes(w_gnx)) { if (!this._openedBodiesGnx.includes(w_gnx)) { console.error("readFile: ERROR File not in _openedBodiesGnx! readFile missing refreshes?"); // throw vscode.FileSystemError.FileNotFound(); // (Instead of FileNotFound) should be caught by _onActiveEditorChanged or _changedVisibleTextEditors if (!this._errorRefreshFlag) { this._tryFullRefresh(); } return Promise.resolve(Buffer.from("")); } else { return this._leoIntegration.sendAction( Constants.LEOBRIDGE.GET_BODY, JSON.stringify({ "gnx": w_gnx }) ).then((p_result) => { if (p_result.body) { this._errorRefreshFlag = false; // got body so reset possible flag! this._lastGnx = w_gnx; this._lastBodyData = p_result.body; const w_buffer: Uint8Array = Buffer.from(p_result.body); this._lastBodyLength = w_buffer.byteLength; return Promise.resolve(w_buffer); } else if (p_result.body === "") { this._lastGnx = w_gnx; this._lastBodyLength = 0; this._lastBodyData = ""; return Promise.resolve(Buffer.from("")); } else { if (!this._errorRefreshFlag) { this._tryFullRefresh(); } if (this._lastGnx === w_gnx) { // was last gnx of closed file about to be switched to new document selected console.log('Passed in not found: ' + w_gnx); return Promise.resolve(Buffer.from(this._lastBodyData)); } console.error("ERROR => readFile of unknown GNX"); // is possibleGnxList updated correctly? // throw vscode.FileSystemError.FileNotFound(); // (Instead of FileNotFound) should be caught by _onActiveEditorChanged or _changedVisibleTextEditors return Promise.resolve(Buffer.from("")); } }); } } } else { throw vscode.FileSystemError.FileNotFound(); } } public readDirectory(p_uri: vscode.Uri): Thenable<[string, vscode.FileType][]> { if (p_uri.fsPath.length === 1) { // p_uri.fsPath === '/' || p_uri.fsPath === '\\' const w_directory: [string, vscode.FileType][] = []; w_directory.push([this._lastBodyTimeGnx, vscode.FileType.File]); return Promise.resolve(w_directory); } else { throw vscode.FileSystemError.FileNotFound(); } } public createDirectory(p_uri: vscode.Uri): void { console.warn('Called createDirectory with ', p_uri.fsPath); // should not happen throw vscode.FileSystemError.NoPermissions(); } public writeFile(p_uri: vscode.Uri, p_content: Uint8Array, p_options: { create: boolean, overwrite: boolean }): void { if (!this.preventSaveToLeo) { this._leoIntegration.triggerBodySave(true); // Might have been a vscode 'save' via the menu } else { this.preventSaveToLeo = false; } const w_gnx = utils.leoUriToStr(p_uri); if (!this._openedBodiesGnx.includes(w_gnx)) { console.error("Leointeg: Tried to save body other than selected node's body", w_gnx); this._openedBodiesGnx.push(w_gnx); } const w_now = new Date().getTime(); this._openedBodiesInfo[w_gnx] = { ctime: w_now, mtime: w_now }; this._fireSoon({ type: vscode.FileChangeType.Changed, uri: p_uri }); } public rename(p_oldUri: vscode.Uri, p_newUri: vscode.Uri, p_options: { overwrite: boolean }): void { console.warn('Called rename on ', p_oldUri.fsPath, p_newUri.fsPath); // should not happen this._fireSoon( { type: vscode.FileChangeType.Deleted, uri: p_oldUri }, { type: vscode.FileChangeType.Created, uri: p_newUri } ); } public delete(p_uri: vscode.Uri): void { // console.log("delete", p_uri.fsPath); const w_gnx = utils.leoUriToStr(p_uri); if (this._openedBodiesGnx.includes(w_gnx)) { this._openedBodiesGnx.splice(this._openedBodiesGnx.indexOf(w_gnx), 1); delete this._openedBodiesInfo[w_gnx]; } else { // console.log("not deleted"); } // dirname is just a slash "/" let w_dirname = p_uri.with({ path: path.posix.dirname(p_uri.path) }); this._fireSoon( { type: vscode.FileChangeType.Changed, uri: w_dirname }, { uri: p_uri, type: vscode.FileChangeType.Deleted } ); } public copy(p_uri: vscode.Uri): void { console.warn('Called copy on ', p_uri.fsPath); // should not happen throw vscode.FileSystemError.NoPermissions(); } private _tryFullRefresh(): void { this._errorRefreshFlag = true; this._leoIntegration.sendAction(Constants.LEOBRIDGE.DO_NOTHING) .then((p_package) => { // refresh and reveal selection const w_node = this._leoIntegration.apToLeoNode(p_package.node!); this._leoIntegration.lastSelectedNode = w_node; this._leoIntegration.showOutline(); // ! maybe overkill this._leoIntegration.launchRefresh( { tree: true, body: true, states: true, buttons: true, documents: true }, false, p_package.node ); }); } private _fireSoon(...p_events: vscode.FileChangeEvent[]): void { this._bufferedEvents.push(...p_events); if (this._fireSoonHandle) { clearTimeout(this._fireSoonHandle); } this._fireSoonHandle = setTimeout(() => { this._onDidChangeFileEmitter.fire(this._bufferedEvents); this._bufferedEvents.length = 0; // clearing events array }, 5); } }
the_stack
import mapboxgl from "mapbox-gl"; import * as fogMap from "./FogMap"; import * as deckgl from "./Deckgl"; import { CANVAS_SIZE_OFFSET, FogCanvas } from "./FogCanvas"; import { HistoryManager } from "./HistoryManager"; const FOW_TILE_ZOOM = 9; const FOW_BLOCK_ZOOM = FOW_TILE_ZOOM + fogMap.TILE_WIDTH_OFFSET; type TileKey = string; function tileToKey(tile: deckgl.Tile): TileKey { return `${tile.x}-${tile.y}-${tile.z}`; } // NOTE: this does not handle wraparound function isBboxOverlap(a: deckgl.Bbox, b: deckgl.Bbox) { return ( a.north >= b.south && b.north >= a.south && a.east >= b.west && b.east >= a.west ); } export class MapRenderer { private static instance = new MapRenderer(); private map: mapboxgl.Map | null; private deckgl: deckgl.Deckgl | null; public fogMap: fogMap.FogMap; public historyManager: HistoryManager; private loadedFogCanvases: { [key: string]: FogCanvas }; private eraserMode: boolean; private eraserArea: [mapboxgl.LngLat, mapboxgl.GeoJSONSource] | null; private onChange: (() => void) | null; private constructor() { this.map = null; this.deckgl = null; this.fogMap = fogMap.FogMap.empty; this.loadedFogCanvases = {}; this.eraserMode = false; this.eraserArea = null; this.historyManager = new HistoryManager(this.fogMap); this.onChange = null; } static get(): MapRenderer { return MapRenderer.instance; } registerMap( map: mapboxgl.Map, deckglContainer: HTMLCanvasElement, onChange: () => void ): void { this.map = map; this.deckgl = new deckgl.Deckgl( map, deckglContainer, this.onLoadFogCanvas.bind(this), this.onUnloadFogCanvas.bind(this) ); this.map.on("mousedown", this.handleMouseClick.bind(this)); this.map.on("mouseup", this.handleMouseRelease.bind(this)); this.map.on("mousemove", this.handleMouseMove.bind(this)); this.setEraserMod(this.eraserMode); this.onChange = onChange; this.onChange(); } unregisterMap(_map: mapboxgl.Map): void { // TODO } redrawArea(area: deckgl.Bbox | null): void { Object.values(this.loadedFogCanvases).forEach((fogCanvas) => { if (area === null || isBboxOverlap(fogCanvas.tile.bbox, area)) { this.drawFogCanvas(fogCanvas); } }); this.deckgl?.updateOnce(); } private applyFogMapUpdate( newMap: fogMap.FogMap, areaChanged: deckgl.Bbox | null ) { this.fogMap = newMap; this.redrawArea(areaChanged); if (this.onChange) { this.onChange(); } } private updateFogMap( newMap: fogMap.FogMap, areaChanged: deckgl.Bbox | null ): void { if (this.fogMap !== newMap) { this.historyManager.append(newMap, areaChanged); this.applyFogMapUpdate(newMap, areaChanged); } } undo(): void { this.historyManager.undo(this.applyFogMapUpdate.bind(this)); } redo(): void { this.historyManager.redo(this.applyFogMapUpdate.bind(this)); } addFoGFiles(files: [string, ArrayBuffer][]): void { const newMap = this.fogMap.addFiles(files); // NOTE: areaChanged = null means all area this.updateFogMap(newMap, null); } handleMouseClick(e: mapboxgl.MapMouseEvent): void { if (this.eraserMode) { console.log( `A click event has occurred on a visible portion of the poi-label layer at ${e.lngLat}` ); if (!this.eraserArea) { this.map?.addSource("eraser", { type: "geojson", data: { type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates: [[]], }, }, }); this.map?.addLayer({ id: "eraser", type: "fill", source: "eraser", layout: {}, paint: { "fill-color": "#969696", "fill-opacity": 0.5, }, }); this.map?.addLayer({ id: "eraser-outline", type: "line", source: "eraser", layout: {}, paint: { "line-color": "#969696", "line-width": 1, }, }); const eraserSource = this.map?.getSource( "eraser" ) as mapboxgl.GeoJSONSource | null; if (eraserSource) { const startPoint = new mapboxgl.LngLat(e.lngLat.lng, e.lngLat.lat); this.eraserArea = [startPoint, eraserSource]; } } } } handleMouseMove(e: mapboxgl.MapMouseEvent): void { if (this.eraserMode && this.eraserArea) { const [startPoint, eraserSource] = this.eraserArea; const west = Math.min(e.lngLat.lng, startPoint.lng); const north = Math.max(e.lngLat.lat, startPoint.lat); const east = Math.max(e.lngLat.lng, startPoint.lng); const south = Math.min(e.lngLat.lat, startPoint.lat); eraserSource.setData({ type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates: [ [ [east, north], [west, north], [west, south], [east, south], [east, north], ], ], }, }); } } handleMouseRelease(e: mapboxgl.MapMouseEvent): void { if (this.eraserMode && this.eraserArea) { const startPoint = this.eraserArea[0]; const west = Math.min(e.lngLat.lng, startPoint.lng); const north = Math.max(e.lngLat.lat, startPoint.lat); const east = Math.max(e.lngLat.lng, startPoint.lng); const south = Math.min(e.lngLat.lat, startPoint.lat); this.map?.removeLayer("eraser"); this.map?.removeLayer("eraser-outline"); this.map?.removeSource("eraser"); const bbox = new deckgl.Bbox(west, south, east, north); console.log(`clearing the bbox ${west} ${north} ${east} ${south}`); const newMap = this.fogMap.clearBbox(bbox); this.updateFogMap(newMap, bbox); this.eraserArea = null; } } setEraserMod(isActivated: boolean): void { this.eraserMode = isActivated; const mapboxCanvas = this.map?.getCanvasContainer(); if (!mapboxCanvas) { return; } if (this.eraserMode) { mapboxCanvas.style.cursor = "cell"; this.map?.dragPan.disable(); } else { mapboxCanvas.style.cursor = ""; this.map?.dragPan.enable(); if (this.eraserArea) { this.map?.removeLayer("eraser"); this.map?.removeLayer("eraser-outline"); this.map?.removeSource("eraser"); this.eraserArea = null; } } } static renderTileOnCanvas( fogCanvas: FogCanvas, fowTile: fogMap.Tile, tileSizeOffset: number, dx: number, dy: number ): void { const CANVAS_FOW_BLOCK_SIZE_OFFSET = tileSizeOffset - fogMap.TILE_WIDTH_OFFSET; // ctx.strokeRect(dx,dy,1<<tileSizeOffset, 1<<tileSizeOffset); const overscanOffset = Math.max(CANVAS_FOW_BLOCK_SIZE_OFFSET, 0); const underscanOffset = Math.max(-CANVAS_FOW_BLOCK_SIZE_OFFSET, 0); Object.values(fowTile.blocks).forEach((block) => { const blockDx = dx + ((block.x >> underscanOffset) << overscanOffset); const blockDy = dy + ((block.y >> underscanOffset) << overscanOffset); MapRenderer.renderBlockOnCanvas( fogCanvas, block, CANVAS_FOW_BLOCK_SIZE_OFFSET, blockDx, blockDy ); }); } static renderBlockOnCanvas( fogCanvas: FogCanvas, fowBlock: fogMap.Block, blockSizeOffset: number, dx: number, dy: number ): void { if (blockSizeOffset <= 0) { fogCanvas.RedrawContext().clearRect(dx, dy, 1, 1); } else { const CANVAS_FOW_PIXEL_SIZE_OFFSET = blockSizeOffset - fogMap.BITMAP_WIDTH_OFFSET; for (let x = 0; x < fogMap.BITMAP_WIDTH; x++) { for (let y = 0; y < fogMap.BITMAP_WIDTH; y++) { if (fowBlock.isVisited(x, y)) { // for each pixel of block, we may draw multiple pixel of image const overscanOffset = Math.max(CANVAS_FOW_PIXEL_SIZE_OFFSET, 0); const underscanOffset = Math.max(-CANVAS_FOW_PIXEL_SIZE_OFFSET, 0); fogCanvas .RedrawContext() .clearRect( dx + ((x >> underscanOffset) << overscanOffset), dy + ((y >> underscanOffset) << overscanOffset), 1 << overscanOffset, 1 << overscanOffset ); } } } } } private drawFogCanvas(fogCanvas: FogCanvas) { const tile = fogCanvas.tile; fogCanvas.beginRedraw(); if (Object.values(this.fogMap.tiles).length === 0) { fogCanvas.endRedraw(); return; } if (tile.z <= FOW_TILE_ZOOM) { // render multiple fow tiles const CANVAS_NUM_FOW_TILE_OFFSET = FOW_TILE_ZOOM - tile.z; const fowTileXMin = tile.x << CANVAS_NUM_FOW_TILE_OFFSET; const fowTileXMax = (tile.x + 1) << CANVAS_NUM_FOW_TILE_OFFSET; const fowTileYMin = tile.y << CANVAS_NUM_FOW_TILE_OFFSET; const fowTileYMax = (tile.y + 1) << CANVAS_NUM_FOW_TILE_OFFSET; for (let fowTileX = fowTileXMin; fowTileX < fowTileXMax; fowTileX++) { for (let fowTileY = fowTileYMin; fowTileY < fowTileYMax; fowTileY++) { const fowTile = this.fogMap.tiles[fogMap.FogMap.makeKeyXY(fowTileX, fowTileY)]; if (fowTile) { // TODO: what if this < 0? const CANVAS_FOW_TILE_SIZE_OFFSET = CANVAS_SIZE_OFFSET - CANVAS_NUM_FOW_TILE_OFFSET; MapRenderer.renderTileOnCanvas( fogCanvas, fowTile, CANVAS_FOW_TILE_SIZE_OFFSET, (fowTileX - fowTileXMin) << CANVAS_FOW_TILE_SIZE_OFFSET, (fowTileY - fowTileYMin) << CANVAS_FOW_TILE_SIZE_OFFSET ); } } } } else { const TILE_OVER_OFFSET = tile.z - FOW_TILE_ZOOM; const fowTileX = tile.x >> TILE_OVER_OFFSET; const fowTileY = tile.y >> TILE_OVER_OFFSET; const subTileMask = (1 << TILE_OVER_OFFSET) - 1; const CANVAS_NUM_FOW_BLOCK_OFFSET = fogMap.TILE_WIDTH_OFFSET - TILE_OVER_OFFSET; if (tile.z > FOW_BLOCK_ZOOM) { // sub-block rendering const fowBlockX = (tile.x & subTileMask) >> -CANVAS_NUM_FOW_BLOCK_OFFSET; const fowBlockY = (tile.y & subTileMask) >> -CANVAS_NUM_FOW_BLOCK_OFFSET; const subBlockMask = (1 << (TILE_OVER_OFFSET - fogMap.TILE_WIDTH_OFFSET)) - 1; const CANVAS_NUM_FOW_PIXEL_OFFSET = CANVAS_NUM_FOW_BLOCK_OFFSET + fogMap.BITMAP_WIDTH_OFFSET; const fowBlockPixelXMin = (tile.x & subBlockMask) << CANVAS_NUM_FOW_PIXEL_OFFSET; const fowBlockPixelXMax = ((tile.x & subBlockMask) + 1) << CANVAS_NUM_FOW_PIXEL_OFFSET; const fowBlockPixelYMin = (tile.y & subBlockMask) << CANVAS_NUM_FOW_PIXEL_OFFSET; const fowBlockPixelYMax = ((tile.y & subBlockMask) + 1) << CANVAS_NUM_FOW_PIXEL_OFFSET; const block = this.fogMap.tiles[fogMap.FogMap.makeKeyXY(fowTileX, fowTileY)] ?.blocks[fogMap.FogMap.makeKeyXY(fowBlockX, fowBlockY)]; if (block) { for ( let fowPixelX = fowBlockPixelXMin; fowPixelX < fowBlockPixelXMax; fowPixelX++ ) { for ( let fowPixelY = fowBlockPixelYMin; fowPixelY < fowBlockPixelYMax; fowPixelY++ ) { const CANVAS_FOW_PIXEL_SIZE_OFFSET = CANVAS_SIZE_OFFSET - CANVAS_NUM_FOW_PIXEL_OFFSET; if (block.isVisited(fowPixelX, fowPixelY)) { const x = (fowPixelX - fowBlockPixelXMin) << CANVAS_FOW_PIXEL_SIZE_OFFSET; const y = (fowPixelY - fowBlockPixelYMin) << CANVAS_FOW_PIXEL_SIZE_OFFSET; fogCanvas .RedrawContext() .clearRect( x, y, 1 << CANVAS_FOW_PIXEL_SIZE_OFFSET, 1 << CANVAS_FOW_PIXEL_SIZE_OFFSET ); } } } } } else { // sub-tile rendering const fowBlockXMin = (tile.x & subTileMask) << CANVAS_NUM_FOW_BLOCK_OFFSET; const fowBlockXMax = ((tile.x & subTileMask) + 1) << CANVAS_NUM_FOW_BLOCK_OFFSET; const fowBlockYMin = (tile.y & subTileMask) << CANVAS_NUM_FOW_BLOCK_OFFSET; const fowBlockYMax = ((tile.y & subTileMask) + 1) << CANVAS_NUM_FOW_BLOCK_OFFSET; const CANVAS_FOW_BLOCK_SIZE_OFFSET = CANVAS_SIZE_OFFSET - CANVAS_NUM_FOW_BLOCK_OFFSET; const blocks = this.fogMap.tiles[fogMap.FogMap.makeKeyXY(fowTileX, fowTileY)] ?.blocks; if (blocks) { Object.values(blocks).forEach((block) => { if ( block.x >= fowBlockXMin && block.x < fowBlockXMax && block.y >= fowBlockYMin && block.y < fowBlockYMax ) { const dx = (block.x - fowBlockXMin) << CANVAS_FOW_BLOCK_SIZE_OFFSET; const dy = (block.y - fowBlockYMin) << CANVAS_FOW_BLOCK_SIZE_OFFSET; MapRenderer.renderBlockOnCanvas( fogCanvas, block, CANVAS_FOW_BLOCK_SIZE_OFFSET, dx, dy ); } }); } } } fogCanvas.endRedraw(); } private onLoadFogCanvas(tile: deckgl.Tile) { const fogCanvas = new FogCanvas(tile); this.drawFogCanvas(fogCanvas); this.loadedFogCanvases[tileToKey(tile)] = fogCanvas; return fogCanvas; } private onUnloadFogCanvas(tile: deckgl.Tile) { delete this.loadedFogCanvases[tileToKey(tile)]; } }
the_stack
import moment = require("moment"); import { BasicClient } from "../BasicClient"; import { ClientOptions } from "../ClientOptions"; import * as jwt from "../Jwt"; import { Level2Point } from "../Level2Point"; import { Level2Snapshot } from "../Level2Snapshots"; import { Level3Point } from "../Level3Point"; import { Level3Snapshot } from "../Level3Snapshot"; import { Level3Update } from "../Level3Update"; import { NotImplementedFn } from "../NotImplementedFn"; import { Trade } from "../Trade"; export type ErisXClientOptions = ClientOptions & { apiKey?: string; apiSecret?: string; l2depth?: number; }; /** * ErisX has limited market data and presently only supports trades and * level3 order books. It requires authenticating with a token to view * the market data, which is performed on initial connection. ErisX also * requires a unique "correlationId" for each request sent to the server. * Requests are limited to 40 per second. */ export class ErisXClient extends BasicClient { public apiKey: string; public apiSecret: string; public l2depth: number; protected _messageId: number; constructor({ wssPath = "wss://trade-api.erisx.com/", watcherMs = 600000, apiKey, apiSecret, l2depth = 20, }: ErisXClientOptions = {}) { super(wssPath, "ErisX", undefined, watcherMs); this.apiKey = apiKey; this.apiSecret = apiSecret; this.hasTrades = true; this.hasLevel2Snapshots = true; this.hasLevel3Updates = true; this.l2depth = l2depth; this._messageId = 0; } public fetchSecurities() { this._wss.send( JSON.stringify({ correlation: "SecurityList", type: "SecurityList", securityGroup: "ALL", }), ); } protected _onConnected() { this._sendAuthentication(); } protected _sendAuthentication() { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "AuthenticationRequest", token: this._createToken(), }), ); } protected _nextId() { return (++this._messageId).toString(); } protected _createToken() { const payload = { iat: Date.now(), sub: this.apiKey, }; return jwt.hs256(payload, this.apiSecret); } protected _sendSubTrades(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "MarketDataSubscribe", symbol: remote_id, tradeOnly: true, }), ); } protected _sendUnsubTrades(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "MarketDataUnsubscribe", symbol: remote_id, tradeOnly: true, }), ); } protected _sendSubLevel2Snapshots(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "TopOfBookMarketDataSubscribe", symbol: remote_id, topOfBookDepth: this.l2depth, }), ); } protected _sendUnsubLevel2Snapshots(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "TopOfBookMarketDataUnsubscribe", symbol: remote_id, topOfBookDepth: this.l2depth, }), ); } protected _sendSubLevel3Updates(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "MarketDataSubscribe", symbol: remote_id, }), ); } protected _sendUnsubLevel3Snapshots(remote_id) { this._wss.send( JSON.stringify({ correlation: this._nextId(), type: "MarketDataUnsubscribe", symbol: remote_id, }), ); } protected _sendSubTicker = NotImplementedFn; protected _sendSubCandles = NotImplementedFn; protected _sendUnsubCandles = NotImplementedFn; protected _sendUnsubTicker = NotImplementedFn; protected _sendSubLevel2Updates = NotImplementedFn; protected _sendUnsubLevel2Updates = NotImplementedFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedFn; protected _onMessage(raw) { const msg: any = JSON.parse(raw); // authentication if (msg.type === "AuthenticationResult") { if (msg.success) { super._onConnected(); } else { this.emit("error", new Error("Authentication failed")); } return; } // logout if (msg.type === "Logout") { this.emit("error", new Error("Session has been logged out")); return; } // unsolicited if (msg.type === "OFFLINE") { this.emit("error", new Error("Exchange is offline")); return; } // status if (msg.type === "INFO_MESSAGE") { return; } // securities if (msg.type === "SecuritiesResponse") { this.emit("markets", msg.securities); return; } // trade if (msg.type === "MarketDataIncrementalRefreshTrade") { const market = this._tradeSubs.get(msg.symbol); if (!market) return; const trades = this._constructTrades(msg, market); for (const trade of trades) { this.emit("trade", trade, market); } return; } // l2 snapshot if (msg.type === "TopOfBookMarketData") { const market = this._level2SnapshotSubs.get(msg.symbol); if (!market) return; const snapshot = this._constructLevel2Snapshot(msg, market); this.emit("l2snapshot", snapshot, market); return; } // l3 if (msg.type === "MarketDataIncrementalRefresh") { const market = this._level3UpdateSubs.get(msg.symbol); if (!market) return; // snapshot if (msg.endFlag === null) { const snapshot = this._constructLevel3Snapshot(msg, market); this.emit("l3snapshot", snapshot, market); } // update else { const update = this._constructLevel3Update(msg, market); this.emit("l3update", update, market); } return; } } /** { "correlation": "15978410832102", "type": "MarketDataIncrementalRefreshTrade", "symbol": "LTC/USD", "sendingTime": "20200819-12:44:50.896", "trades": [{ "updateAction": "NEW", "price": 64.2, "currency": "LTC", "tickerType": "PAID", "transactTime": "20200819-12:44:50.872994129", "size": 2.0, "symbol": "LTC/USD", "numberOfOrders": 1 }], "endFlag": "END_OF_TRADE" } */ protected _constructTrades(msg, market) { return msg.trades.map(p => this._constructTrade(p, market)); } /** { "updateAction": "NEW", "price": 64.2, "currency": "LTC", "tickerType": "PAID", "transactTime": "20200819-12:44:50.872994129", "size": 2.0, "symbol": "LTC/USD", "numberOfOrders": 1 } */ protected _constructTrade(msg, market) { const timestamp = moment.utc(msg.transactTime, "YYYYMMDD-hh:mm:ss.SSSSSSSSS"); const unix = timestamp.valueOf(); const tradeId = msg.transactTime.replace(/[-:.]/g, ""); const amount = msg.size.toFixed(8); const price = msg.price.toFixed(8); return new Trade({ exchange: this.name, base: market.base, quote: market.quote, tradeId, unix, price, amount, raw: msg, }); } /** { "correlation": "15978412650812", "type": "TopOfBookMarketData", "bids": [ { "action": "NEW", "count": 1, "totalVolume": 1.0, "price": 413.2, "lastUpdate": "20200819-12:47:49.975" }, { "action": "UPDATE", "count": 2, "totalVolume": 2.00, "price": 412.9, "lastUpdate": "20200819-12:47:39.984" } ], "offers": [ { "action": "NO CHANGE", "count": 1, "totalVolume": 1.00, "price": 413.3, "lastUpdate": "20200819-12:47:40.166" }, { "action": "NO CHANGE", "count": 1, "totalVolume": 1.56, "price": 413.4, "lastUpdate": "20200819-12:47:20.196" } ], "symbol": "ETH/USD" } */ protected _constructLevel2Snapshot(msg, market) { const map = p => new Level2Point( p.price.toFixed(8), p.totalVolume.toFixed(8), p.count, undefined, moment.utc(p.lastUpdate, "YYYYMMDD-hh:mm:ss.SSSSSSSSS").valueOf(), ); const bids = msg.bids.map(map); const asks = msg.offers.map(map); return new Level2Snapshot({ exchange: this.name, base: market.base, quote: market.quote, asks, bids, }); } /** { "correlation": "4", "type": "MarketDataIncrementalRefresh", "symbol": "BTC/USD", "sendingTime": "20201007-17:37:40.588", "bids": [ { "id": "1000000fd05b8", "updateAction": "NEW", "price": 10632.2, "amount": 1.6, "symbol": "BTC/USD" }, { "id": "1000000fd05a0", "updateAction": "NEW", "price": 10629.4, "amount": 1.6, "symbol": "BTC/USD" }, { "id": "1000000fc7402", "updateAction": "NEW", "price": 10623.4, "amount": 0.99, "symbol": "BTC/USD" } ], "offers": [ { "id": "1000000fd0522", "updateAction": "NEW", "price": 10633.5, "amount": 1.6, "symbol": "BTC/USD" }, { "id": "1000000fd05b7", "updateAction": "NEW", "price": 10637, "amount": 1.6, "symbol": "BTC/USD" }, { "id": "1000000fc7403", "updateAction": "NEW", "price": 10638.4, "amount": 0.99, "symbol": "BTC/USD" } ], "transactTime": "20201007-17:37:40.587917127", "endFlag": null } */ protected _constructLevel3Snapshot(msg, market) { const timestampMs = moment.utc(msg.transactTime, "YYYYMMDD-hh:mm:ss.SSSSSSSSS").valueOf(); const asks = msg.offers.map( p => new Level3Point(p.id, p.price.toFixed(8), p.amount.toFixed(8), { type: p.updateAction, }), ); const bids = msg.bids.map( p => new Level3Point(p.id, p.price.toFixed(8), p.amount.toFixed(8), { type: p.updateAction, }), ); return new Level3Snapshot({ exchange: this.name, base: market.base, quote: market.quote, timestampMs, asks, bids, }); } /** { "correlation": "4", "type": "MarketDataIncrementalRefresh", "symbol": "BTC/USD", "sendingTime": "20201007-17:37:42.931", "bids": [ { "id": "1000000fc7402", "updateAction": "NEW", "price": 10625, "amount": 0.99, "symbol": "BTC/USD" } ], "offers": [], "transactTime": "20201007-17:37:42.930970367", "endFlag": "END_OF_EVENT" } */ protected _constructLevel3Update(msg, market) { const timestampMs = moment.utc(msg.transactTime, "YYYYMMDD-hh:mm:ss.SSSSSSSSS").valueOf(); const asks = msg.bids.map( p => new Level3Point(p.id, p.price.toFixed(8), p.amount.toFixed(8), { type: p.updateAction, }), ); const bids = msg.offers.map( p => new Level3Point(p.id, p.price.toFixed(8), p.amount.toFixed(8), { type: p.updateAction, }), ); return new Level3Update({ exchange: this.name, base: market.base, quote: market.quote, timestampMs, asks, bids, }); } }
the_stack
import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; import * as echoModule from '../src'; import {PassThrough} from 'stream'; //@ts-ignore import {protobuf, LROperation, operationsProtos} from 'google-gax'; function generateSampleMessage<T extends object>(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message<T>, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject ) as T; } function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) { return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } function stubSimpleCallWithCallback<ResponseType>( response?: ResponseType, error?: Error ) { return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } function stubServerStreamingCall<ResponseType>( response?: ResponseType, error?: Error ) { const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); // write something to the stream to trigger transformStub and send the response back to the client setImmediate(() => { mockStream.write({}); }); setImmediate(() => { mockStream.end(); }); return sinon.stub().returns(mockStream); } function stubBidiStreamingCall<ResponseType>( response?: ResponseType, error?: Error ) { const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); return sinon.stub().returns(mockStream); } function stubClientStreamingCall<ResponseType>( response?: ResponseType, error?: Error ) { if (error) { return sinon.stub().callsArgWith(2, error); } const transformStub = sinon.stub(); const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } function stubLongRunningCall<ResponseType>( response?: ResponseType, callError?: Error, lroError?: Error ) { const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); const mockOperation = { promise: innerStub, }; return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); } function stubLongRunningCallWithCallback<ResponseType>( response?: ResponseType, callError?: Error, lroError?: Error ) { const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); const mockOperation = { promise: innerStub, }; return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); } function stubPageStreamingCall<ResponseType>( responses?: ResponseType[], error?: Error ) { const pagingStub = sinon.stub(); if (responses) { for (let i = 0; i < responses.length; ++i) { pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } } const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); // trigger as many responses as needed if (responses) { for (let i = 0; i < responses.length; ++i) { setImmediate(() => { mockStream.write({}); }); } setImmediate(() => { mockStream.end(); }); } else { setImmediate(() => { mockStream.write({}); }); setImmediate(() => { mockStream.end(); }); } return sinon.stub().returns(mockStream); } function stubAsyncIterationCall<ResponseType>( responses?: ResponseType[], error?: Error ) { let counter = 0; const asyncIterable = { [Symbol.asyncIterator]() { return { async next() { if (error) { return Promise.reject(error); } if (counter >= responses!.length) { return Promise.resolve({done: true, value: undefined}); } return Promise.resolve({done: false, value: responses![counter++]}); }, }; }, }; return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { it('has servicePath', () => { const servicePath = echoModule.v1beta1.EchoClient.servicePath; assert(servicePath); }); it('has apiEndpoint', () => { const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; assert(apiEndpoint); }); it('has port', () => { const port = echoModule.v1beta1.EchoClient.port; assert(port); assert(typeof port === 'number'); }); it('should create a client with no option', () => { const client = new echoModule.v1beta1.EchoClient(); assert(client); }); it('should create a client with gRPC fallback', () => { const client = new echoModule.v1beta1.EchoClient({ fallback: true, }); assert(client); }); it('has initialize method and supports deferred initialization', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); assert.strictEqual(client.echoStub, undefined); await client.initialize(); assert(client.echoStub); }); it('has close method', () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.close(); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); const result = await client.getProjectId(); assert.strictEqual(result, fakeProjectId); assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.auth.getProjectId = sinon .stub() .callsArgWith(0, null, fakeProjectId); const promise = new Promise((resolve, reject) => { client.getProjectId((err?: Error | null, projectId?: string | null) => { if (err) { reject(err); } else { resolve(projectId); } }); }); const result = await promise; assert.strictEqual(result, fakeProjectId); }); describe('echo', () => { it('invokes echo without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ); client.innerApiCalls.echo = stubSimpleCall(expectedResponse); const [response] = await client.echo(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.echo as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes echo without error using callback', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ); client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.echo( request, ( err?: Error | null, result?: protos.google.showcase.v1beta1.IEchoResponse | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.echo as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes echo with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); await assert.rejects(client.echo(request), expectedError); assert( (client.innerApiCalls.echo as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('block', () => { it('invokes block without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.BlockRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.BlockResponse() ); client.innerApiCalls.block = stubSimpleCall(expectedResponse); const [response] = await client.block(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.block as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes block without error using callback', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.BlockRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.BlockResponse() ); client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.block( request, ( err?: Error | null, result?: protos.google.showcase.v1beta1.IBlockResponse | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.block as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes block with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.BlockRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); await assert.rejects(client.block(request), expectedError); assert( (client.innerApiCalls.block as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('wait', () => { it('invokes wait without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.WaitRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); const [operation] = await client.wait(request); const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.wait as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes wait without error using callback', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.WaitRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.wait( request, ( err?: Error | null, result?: LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata > | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const operation = (await promise) as LROperation< protos.google.showcase.v1beta1.IWaitResponse, protos.google.showcase.v1beta1.IWaitMetadata >; const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.wait as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes wait with call error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.WaitRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); await assert.rejects(client.wait(request), expectedError); assert( (client.innerApiCalls.wait as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes wait with LRO error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.WaitRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.wait = stubLongRunningCall( undefined, undefined, expectedError ); const [operation] = await client.wait(request); await assert.rejects(operation.promise(), expectedError); assert( (client.innerApiCalls.wait as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes checkWaitProgress without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const expectedResponse = generateSampleMessage( new operationsProtos.google.longrunning.Operation() ); expectedResponse.name = 'test'; expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; client.operationsClient.getOperation = stubSimpleCall(expectedResponse); const decodedOperation = await client.checkWaitProgress( expectedResponse.name ); assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); assert(decodedOperation.metadata); assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); it('invokes checkWaitProgress with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.checkWaitProgress(''), expectedError); assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); }); describe('expand', () => { it('invokes expand without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.ExpandRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ); client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); const stream = client.expand(request); const promise = new Promise((resolve, reject) => { stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { resolve(response); } ); stream.on('error', (err: Error) => { reject(err); }); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.expand as SinonStub) .getCall(0) .calledWith(request, expectedOptions) ); }); it('invokes expand with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.ExpandRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.expand = stubServerStreamingCall( undefined, expectedError ); const stream = client.expand(request); const promise = new Promise((resolve, reject) => { stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { resolve(response); } ); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.innerApiCalls.expand as SinonStub) .getCall(0) .calledWith(request, expectedOptions) ); }); }); describe('chat', () => { it('invokes chat without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ); client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); const stream = client.chat(); const promise = new Promise((resolve, reject) => { stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { resolve(response); } ); stream.on('error', (err: Error) => { reject(err); }); stream.write(request); stream.end(); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.chat as SinonStub) .getCall(0) .calledWithExactly(undefined) ); assert.deepStrictEqual( ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) .args[0], request ); }); it('invokes chat with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedError = new Error('expected'); client.innerApiCalls.chat = stubBidiStreamingCall( undefined, expectedError ); const stream = client.chat(); const promise = new Promise((resolve, reject) => { stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { resolve(response); } ); stream.on('error', (err: Error) => { reject(err); }); stream.write(request); stream.end(); }); await assert.rejects(promise, expectedError); assert( (client.innerApiCalls.chat as SinonStub) .getCall(0) .calledWithExactly(undefined) ); assert.deepStrictEqual( ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) .args[0], request ); }); }); describe('collect', () => { it('invokes collect without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedResponse = generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ); client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); let stream: PassThrough; const promise = new Promise((resolve, reject) => { stream = client.collect( ( err?: Error | null, result?: protos.google.showcase.v1beta1.IEchoResponse | null ) => { if (err) { reject(err); } else { resolve(result); } } ) as unknown as PassThrough; stream.write(request); stream.end(); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.collect as SinonStub) .getCall(0) .calledWith(null, {} /*, callback defined above */) ); assert.deepStrictEqual( (stream!._transform as SinonStub).getCall(0).args[0], request ); }); it('invokes collect with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.EchoRequest() ); const expectedError = new Error('expected'); client.innerApiCalls.collect = stubClientStreamingCall( undefined, expectedError ); let stream: PassThrough; const promise = new Promise((resolve, reject) => { stream = client.collect( ( err?: Error | null, result?: protos.google.showcase.v1beta1.IEchoResponse | null ) => { if (err) { reject(err); } else { resolve(result); } } ) as unknown as PassThrough; stream.write(request); stream.end(); }); await assert.rejects(promise, expectedError); assert( (client.innerApiCalls.collect as SinonStub) .getCall(0) .calledWith(null, {} /*, callback defined above */) ); }); }); describe('pagedExpand', () => { it('invokes pagedExpand without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = [ generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), ]; client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); const [response] = await client.pagedExpand(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.pagedExpand as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes pagedExpand without error using callback', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedResponse = [ generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), ]; client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.pagedExpand( request, ( err?: Error | null, result?: protos.google.showcase.v1beta1.IEchoResponse[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.pagedExpand as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes pagedExpand with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedOptions = {otherArgs: {headers: {}}}; const expectedError = new Error('expected'); client.innerApiCalls.pagedExpand = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.pagedExpand(request), expectedError); assert( (client.innerApiCalls.pagedExpand as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes pagedExpandStream without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedResponse = [ generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), ]; client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); const stream = client.pagedExpandStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.pagedExpand.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.pagedExpand, request) ); }); it('invokes pagedExpandStream with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedError = new Error('expected'); client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( undefined, expectedError ); const stream = client.pagedExpandStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; stream.on( 'data', (response: protos.google.showcase.v1beta1.EchoResponse) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.pagedExpand.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.pagedExpand, request) ); }); it('uses async iteration with pagedExpand without error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedResponse = [ generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), generateSampleMessage( new protos.google.showcase.v1beta1.EchoResponse() ), ]; client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; const iterable = client.pagedExpandAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( 0 ).args[1], request ); }); it('uses async iteration with pagedExpand with error', async () => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.showcase.v1beta1.PagedExpandRequest() ); const expectedError = new Error('expected'); client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( undefined, expectedError ); const iterable = client.pagedExpandAsync(request); await assert.rejects(async () => { const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( 0 ).args[1], request ); }); }); describe('Path templates', () => { describe('blueprint', () => { const fakePath = '/rendered/path/blueprint'; const expectedParameters = { session: 'sessionValue', test: 'testValue', blueprint: 'blueprintValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.blueprintPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.blueprintPathTemplate.match = sinon .stub() .returns(expectedParameters); it('blueprintPath', () => { const result = client.blueprintPath( 'sessionValue', 'testValue', 'blueprintValue' ); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.blueprintPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchSessionFromBlueprintName', () => { const result = client.matchSessionFromBlueprintName(fakePath); assert.strictEqual(result, 'sessionValue'); assert( (client.pathTemplates.blueprintPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); it('matchTestFromBlueprintName', () => { const result = client.matchTestFromBlueprintName(fakePath); assert.strictEqual(result, 'testValue'); assert( (client.pathTemplates.blueprintPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); it('matchBlueprintFromBlueprintName', () => { const result = client.matchBlueprintFromBlueprintName(fakePath); assert.strictEqual(result, 'blueprintValue'); assert( (client.pathTemplates.blueprintPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('room', () => { const fakePath = '/rendered/path/room'; const expectedParameters = { room_id: 'roomIdValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.roomPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.roomPathTemplate.match = sinon .stub() .returns(expectedParameters); it('roomPath', () => { const result = client.roomPath('roomIdValue'); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.roomPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchRoomIdFromRoomName', () => { const result = client.matchRoomIdFromRoomName(fakePath); assert.strictEqual(result, 'roomIdValue'); assert( (client.pathTemplates.roomPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('roomIdBlurbId', () => { const fakePath = '/rendered/path/roomIdBlurbId'; const expectedParameters = { room_id: 'roomIdValue', blurb_id: 'blurbIdValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.roomIdBlurbIdPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.roomIdBlurbIdPathTemplate.match = sinon .stub() .returns(expectedParameters); it('roomIdBlurbIdPath', () => { const result = client.roomIdBlurbIdPath('roomIdValue', 'blurbIdValue'); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.roomIdBlurbIdPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchRoomIdFromRoomIdBlurbIdName', () => { const result = client.matchRoomIdFromRoomIdBlurbIdName(fakePath); assert.strictEqual(result, 'roomIdValue'); assert( (client.pathTemplates.roomIdBlurbIdPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); it('matchBlurbIdFromRoomIdBlurbIdName', () => { const result = client.matchBlurbIdFromRoomIdBlurbIdName(fakePath); assert.strictEqual(result, 'blurbIdValue'); assert( (client.pathTemplates.roomIdBlurbIdPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('session', () => { const fakePath = '/rendered/path/session'; const expectedParameters = { session: 'sessionValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.sessionPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.sessionPathTemplate.match = sinon .stub() .returns(expectedParameters); it('sessionPath', () => { const result = client.sessionPath('sessionValue'); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.sessionPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchSessionFromSessionName', () => { const result = client.matchSessionFromSessionName(fakePath); assert.strictEqual(result, 'sessionValue'); assert( (client.pathTemplates.sessionPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('test', () => { const fakePath = '/rendered/path/test'; const expectedParameters = { session: 'sessionValue', test: 'testValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.testPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.testPathTemplate.match = sinon .stub() .returns(expectedParameters); it('testPath', () => { const result = client.testPath('sessionValue', 'testValue'); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.testPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchSessionFromTestName', () => { const result = client.matchSessionFromTestName(fakePath); assert.strictEqual(result, 'sessionValue'); assert( (client.pathTemplates.testPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); it('matchTestFromTestName', () => { const result = client.matchTestFromTestName(fakePath); assert.strictEqual(result, 'testValue'); assert( (client.pathTemplates.testPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('user', () => { const fakePath = '/rendered/path/user'; const expectedParameters = { user_id: 'userIdValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.userPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.userPathTemplate.match = sinon .stub() .returns(expectedParameters); it('userPath', () => { const result = client.userPath('userIdValue'); assert.strictEqual(result, fakePath); assert( (client.pathTemplates.userPathTemplate.render as SinonStub) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchUserIdFromUserName', () => { const result = client.matchUserIdFromUserName(fakePath); assert.strictEqual(result, 'userIdValue'); assert( (client.pathTemplates.userPathTemplate.match as SinonStub) .getCall(-1) .calledWith(fakePath) ); }); }); describe('userIdProfileBlurbId', () => { const fakePath = '/rendered/path/userIdProfileBlurbId'; const expectedParameters = { user_id: 'userIdValue', blurb_id: 'blurbIdValue', }; const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); client.pathTemplates.userIdProfileBlurbIdPathTemplate.render = sinon .stub() .returns(fakePath); client.pathTemplates.userIdProfileBlurbIdPathTemplate.match = sinon .stub() .returns(expectedParameters); it('userIdProfileBlurbIdPath', () => { const result = client.userIdProfileBlurbIdPath( 'userIdValue', 'blurbIdValue' ); assert.strictEqual(result, fakePath); assert( ( client.pathTemplates.userIdProfileBlurbIdPathTemplate .render as SinonStub ) .getCall(-1) .calledWith(expectedParameters) ); }); it('matchUserIdFromUserIdProfileBlurbIdName', () => { const result = client.matchUserIdFromUserIdProfileBlurbIdName(fakePath); assert.strictEqual(result, 'userIdValue'); assert( ( client.pathTemplates.userIdProfileBlurbIdPathTemplate .match as SinonStub ) .getCall(-1) .calledWith(fakePath) ); }); it('matchBlurbIdFromUserIdProfileBlurbIdName', () => { const result = client.matchBlurbIdFromUserIdProfileBlurbIdName(fakePath); assert.strictEqual(result, 'blurbIdValue'); assert( ( client.pathTemplates.userIdProfileBlurbIdPathTemplate .match as SinonStub ) .getCall(-1) .calledWith(fakePath) ); }); }); }); });
the_stack
import { IAsyncEqualityComparer, IAsyncParallel, IComparer, IEqualityComparer, IGrouping, InferType, IOrderedAsyncEnumerable, IParallelEnumerable, OfType, SelectorKeyType} from "./" /** * Async Iterable type with methods from LINQ. */ export interface IAsyncEnumerable<TSource> extends IAsyncParallel<TSource> { /** * Converts an async iterable to a Parallel Enumerable. * @returns Parallel Enumerable of source */ asParallel(): IParallelEnumerable<TSource> /** * Concatenates two async sequences. * @param second The sequence to concatenate to the first sequence. * @returns An IAsyncEnumerable<T> that contains the concatenated elements of the two sequences. */ concatenate(second: IAsyncEnumerable<TSource>): IAsyncEnumerable<TSource> /** * Returns distinct elements from a sequence by using the default * or specified equality comparer to compare values. * @param comparer An IEqualityComparer<T> to compare values. Optional. Defaults to Strict Equality Comparison. * @returns An IAsyncEnumerable<T> that contains distinct elements from the source sequence. */ distinct(comparer?: IEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Returns distinct elements from a sequence by using the specified equality comparer to compare values. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns An IAsyncEnumerable<T> that contains distinct elements from the source sequence. */ distinctAsync(comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Performs a specified action on each element of the Iterable<TSource> * @param action The action to take an each element * @returns A new IAsyncEnumerable<T> that executes the action lazily as you iterate. */ each(action: (x: TSource) => void): IAsyncEnumerable<TSource> /** * Performs a specified action on each element of the Iterable<TSource> * @param action The async action to take an each element * @returns A new IAsyncEnumerable<T> that executes the action lazily as you iterate. */ eachAsync(action: (x: TSource) => Promise<void>): IAsyncEnumerable<TSource> /** * Produces the set difference of two sequences by using the comparer provided * or EqualityComparer to compare values. * @param second An IAsyncEnumerable<T> whose elements that also occur in the first sequence * will cause those elements to be removed from the returned sequence. * @param comparer An IEqualityComparer<T> to compare values. Optional. * @returns A sequence that contains the set difference of the elements of two sequences. */ except(second: IAsyncEnumerable<TSource>, comparer?: IEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Produces the set difference of two sequences by using the comparer provided to compare values. * @param second An IAsyncEnumerable<T> whose elements that also occur in the first sequence * will cause those elements to be removed from the returned sequence. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns A sequence that contains the set difference of the elements of two sequences. */ exceptAsync( second: IAsyncEnumerable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector A function to extract the key for each element. * @returns An IAsyncEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupBy<TKey extends SelectorKeyType>( keySelector: (x: TSource) => TKey): IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a key selector function. * The keys are compared by using a comparer and each group's elements are projected by using a specified function. * @param keySelector A function to extract the key for each element. * @param comparer An IAsyncEqualityComparer<T> to compare keys. */ groupBy<TKey>( keySelector: (x: TSource) => TKey, comparer: IEqualityComparer<TKey>): IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector A function to extract the key for each element. * @returns An IAsyncEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupByAsync<TKey extends SelectorKeyType>( keySelector: (x: TSource) => Promise<TKey> | TKey): IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector A function to extract the key for each element. * @param comparer An IEqualityComparer<T> or IAsyncEqualityComparer<T> to compare keys. * @returns An IAsyncEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupByAsync<TKey>( keySelector: (x: TSource) => Promise<TKey> | TKey, comparer: IEqualityComparer<TKey> | IAsyncEqualityComparer<TKey>): IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function and * projects the elements for each group by using a specified function. * @param keySelector A function to extract the key for each element. * @param elementSelector A function to map each source element to an element in an IGrouping<TKey,TElement>. * @param comparer An IEqualityComparer<T> to compare keys. * @returns An IAsyncEnumerable<IGrouping<TKey, TElement>> * where each IGrouping<TKey,TElement> object contains a collection of objects of type TElement and a key. */ groupByWithSel<TKey extends SelectorKeyType, TElement>( keySelector: (x: TSource) => TKey, elementSelector: (x: TSource) => TElement, comparer?: IEqualityComparer<TKey>): IAsyncEnumerable<IGrouping<TKey, TElement>> /** * Groups the elements of a sequence according to a key selector function. * The keys are compared by using a comparer and each group's elements are projected by using a specified function. * @param keySelector A function to extract the key for each element. * @param elementSelector A function to map each source element to an element in an IGrouping<TKey,TElement>. * @param comparer An IEqualityComparer<T> to compare keys. * @returns An IAsyncEnumerable<IGrouping<TKey,TElement>> * where each IGrouping<TKey,TElement> object contains a collection of objects of type TElement and a key. */ groupByWithSel<TKey, TElement>( keySelector: ((x: TSource) => TKey), elementSelector: (x: TSource) => TElement, comparer: IEqualityComparer<TKey>): IAsyncEnumerable<IGrouping<TKey, TElement>> /** * Produces the set intersection of two sequences by using the specified IEqualityComparer<T> to compare values. * If no comparer is selected, uses the StrictEqualityComparer. * @param second An Iterable<T> whose distinct elements that also appear in the first sequence will be returned. * @param comparer An IEqualityComparer<T> to compare values. Optional. * @returns An async sequence that contains the elements that form the set intersection of two sequences. */ intersect(second: IAsyncEnumerable<TSource>, comparer?: IEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Produces the set intersection of two sequences by using the specified * IAsyncEqualityComparer<T> to compare values. * @param second An Iterable<T> whose distinct elements that also appear in the first sequence will be returned. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns A sequence that contains the elements that form the set intersection of two sequences. */ intersectAsync( second: IAsyncEnumerable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Correlates the elements of two sequences based on matching keys. * A specified IEqualityComparer<T> is used to compare keys or the strict equality comparer. * @param inner The sequence to join to the first sequence. * @param outerKeySelector A function to extract the join key from each element of the first sequence. * @param innerKeySelector A function to extract the join key from each element of the second sequence. * @param resultSelector A function to create a result element from two matching elements. * @param comparer An IEqualityComparer<T> to hash and compare keys. Optional. * @returns An IAsyncEnumerable<T> that has elements of type TResult that * are obtained by performing an inner join on two sequences. */ joinByKey<TInner, TKey, TResult>( inner: IAsyncEnumerable<TInner>, outerKeySelector: (x: TSource) => TKey, innerKeySelector: (x: TInner) => TKey, resultSelector: (x: TSource, y: TInner) => TResult, comparer?: IEqualityComparer<TKey>): IAsyncEnumerable<TResult> /** * Applies a type filter to a source iteration * @param type Either value for typeof or a consturctor function * @returns Values that match the type string or are instance of type */ ofType<TType extends OfType>(type: TType): IAsyncEnumerable<InferType<TType>> /** * Sorts the elements of a sequence in ascending order by using a specified or default comparer. * @param keySelector A function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. Optional. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted according to a key. */ orderBy<TKey>( predicate: (x: TSource) => TKey, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Sorts the elements of a sequence in ascending order by using a specified comparer. * @param keySelector An async function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted according to a key. */ orderByAsync<TKey>( predicate: (x: TSource) => Promise<TKey>, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Sorts the elements of a sequence in descending order by using a specified or default comparer. * @param keySelector A function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. Optional. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted in descending order according to a key. */ orderByDescending<TKey>( predicate: (x: TSource) => TKey, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Sorts the elements of a sequence in descending order by using a specified comparer. * @param keySelector An async function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted in descending order according to a key. */ orderByDescendingAsync<TKey>( predicate: (x: TSource) => Promise<TKey>, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Inverts the order of the elements in a sequence. * @returns An async sequence whose elements correspond to those of the input sequence in reverse order. */ reverse(): IAsyncEnumerable<TSource> /** * Projects each element of a sequence into a new form. * @param selector A transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of * invoking the transform function on each element of source. */ select<TResult>(selector: (x: TSource, index: number) => TResult): IAsyncEnumerable<TResult> /** * Projects each element of a sequence into a new form. * @param selector A key of TSource. * @returns * An IAsyncEnumerable<T> whose elements are the result of getting the value from the key on each element of source. */ select<TKey extends keyof TSource>(key: TKey): IAsyncEnumerable<TSource[TKey]> /** * Projects each element of a sequence into a new form. * @param selector An async transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking * the transform function on each element of source. */ selectAsync<TResult>(selector: (x: TSource, index: number) => Promise<TResult>): IAsyncEnumerable<TResult> /** * Projects each element of a sequence into a new form. * @param key A key of the elements in the sequence * @returns An IAsyncEnumerable<T> whoe elements are the result of getting the value for key * on each element of source. */ selectAsync<TKey extends keyof TSource, TResult>( this: IAsyncEnumerable<{ [key: string]: Promise<TResult> }>, key: TKey): IAsyncEnumerable<TResult> /** * Projects each element of a sequence to an IAsyncEnumerable<T> * and flattens the resulting sequences into one sequence. * @param selector A transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking the * one-to-many transform function on each element of the input sequence. */ selectMany<TResult>(selector: (x: TSource, index: number) => Iterable<TResult>): IAsyncEnumerable<TResult> /** * Projects each element of a sequence to an IAsyncEnumerable<T> * and flattens the resulting sequences into one sequence. * @param selector A string key of TSource. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking the * parameter the key is tried to on each element of the input sequence. */ selectMany<TBindedSource extends { [key: string]: Iterable<TOut>}, TOut>( this: IAsyncEnumerable<TBindedSource>, selector: keyof TBindedSource): IAsyncEnumerable<TOut> /** * Projects each element of a sequence to an IAsyncEnumerable<T> * and flattens the resulting sequences into one sequence. * @param selector A transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking the * one-to-many transform function on each element of the input sequence. */ selectManyAsync<TResult>( selector: (x: TSource, index: number) => Promise<Iterable<TResult>>): IAsyncEnumerable<TResult> /** * Determines whether or not two sequences are equal * @param second second iterable * @param comparer Compare function to use, by default is @see {StrictEqualityComparer} * @returns Whether or not the two iterations are equal */ sequenceEquals(second: AsyncIterable<TSource>, comparer?: IEqualityComparer<TSource>): Promise<boolean> /** * Compares two sequences to see if they are equal using an async comparer function. * @param second Second Sequence * @param comparer Async Comparer * @returns Whether or not the two iterations are equal */ sequenceEqualsAsync(second: AsyncIterable<TSource>, comparer: IAsyncEqualityComparer<TSource>): Promise<boolean> /** * Bypasses a specified number of elements in a sequence and then returns the remaining elements. * @param count The number of elements to skip before returning the remaining elements. * @returns An IAsyncEnumerable<T> that contains the elements * that occur after the specified index in the input sequence. */ skip(count: number): IAsyncEnumerable<TSource> /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains the elements from the input sequence starting at the first element * in the linear series that does not pass the test specified by predicate. */ skipWhile(predicate: (x: TSource, index: number) => boolean): IAsyncEnumerable<TSource> /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains the elements from the input sequence starting * at the first element in the linear series that does not pass the test specified by predicate. */ skipWhileAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Returns a specified number of contiguous elements from the start of a sequence. * @param amount The number of elements to return. * @returns An IAsyncEnumerable<T> that contains the specified * number of elements from the start of the input sequence. */ take(amount: number): IAsyncEnumerable<TSource> /** * Returns elements from a sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence * that occur before the element at which the test no longer passes. */ takeWhile(pedicate: (x: TSource, index: number) => boolean): IAsyncEnumerable<TSource> /** * Returns elements from a sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param predicate A async function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence * that occur before the element at which the test no longer passes. */ takeWhileAsync(pedicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Produces the set union of two sequences by using scrict equality comparison or a specified IEqualityComparer<T>. * @param second An AsyncIterable<T> whose distinct elements form the second set for the union. * @param comparer The IEqualityComparer<T> to compare values. Optional. * @returns An IAsyncEnumerable<T> that contains the elements from both input sequences, excluding duplicates. */ union(second: AsyncIterable<TSource>, comparer?: IEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Produces the set union of two sequences by using a specified IAsyncEqualityComparer<T>. * @param second An AsyncIterable<T> whose distinct elements form the second set for the union. * @param comparer The IAsyncEqualityComparer<T> to compare values. * @returns An IAsyncEnumerable<T> that contains the elements from both input sequences, excluding duplicates. */ unionAsync(second: AsyncIterable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Filters a sequence of values based on a predicate. * Each element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence that satisfy the condition. */ where(predicate: (x: TSource, index: number) => boolean): IAsyncEnumerable<TSource> /** * Filters a sequence of values based on a predicate. * Each element's index is used in the logic of the predicate function. * @param predicate A async function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence that satisfy the condition. */ whereAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. * @param second The second sequence to merge. * @param resultSelector A function that specifies how to merge the elements from the two sequences. * @returns An IAsyncEnumerable<TResult> that contains merged elements of two input sequences. */ zip<TSecond, TResult>( second: AsyncIterable<TSecond>, resultSelector: (x: TSource, y: TSecond) => TResult): IAsyncEnumerable<TResult> /** * Creates a tuple of corresponding elements of two sequences, producing a sequence of the results. * @param second The second sequence to merge. * @returns An IAsyncEnumerable<[T, Y]> that contains merged elements of two input sequences. */ zip<TSecond>(second: AsyncIterable<TSecond>): IAsyncEnumerable<[TSource, TSecond]> /** * Applies a specified async function to the corresponding elements of two sequences, * producing a sequence of the results. * @param second The second sequence to merge. * @param resultSelector An async function that specifies how to merge the elements from the two sequences. * @returns An IAsyncEnumerable<T> that contains merged elements of two input sequences. */ zipAsync<TSecond, TResult>( second: AsyncIterable<TSecond>, resultSelector: (x: TSource, y: TSecond) => Promise<TResult>): IAsyncEnumerable<TResult> }
the_stack
import { MachineApi } from "../wa-api"; import { MemoryHelper } from "../memory-helpers"; import { BLOCK_LOOKUP_TABLE, Z88_PIXEL_BUFFER, VM_MEMORY, Z88_MACHINE_STATE_BUFFER, Z88_BEEPER_BUFFER, } from "../memory-map"; import { FrameBoundZ80Machine } from "../FrameBoundZ80Machine"; import { CambridgeZ88MachineState, MachineState, } from "@shared/machines/machine-state"; import { KeyMapping } from "../keyboard"; import { cz88KeyCodes, cz88KeyMappings } from "./cz88-keys"; import { ExtraMachineFeatures } from "../Z80MachineBase"; import { CZ88_BATTERY_LOW, CZ88_HARD_RESET, CZ88_PRESS_BOTH_SHIFTS, CZ88_SOFT_RESET, } from "@shared/machines/macine-commands"; import { IVmEngineController } from "../IVmEngineController"; import { IAudioRenderer } from "../IAudioRenderer"; import { ICambridgeZ88BaseStateManager } from "./ICambrideZ88BaseStateMananger"; /** * This class implements the Cambride Z88 machine */ export class CambridgeZ88 extends FrameBoundZ80Machine { /** * The type identifier of the machine */ readonly typeId = "cz88"; /** * Friendly name to display */ readonly displayName = "Cambridge Z88"; /** * The default keyboard type */ readonly keyboardType: string = "cz88"; // --- Screen dimensions private _screenWidth = 0; private _screenHeight = 0; // --- Beeper emulation private _beeperRenderer: IAudioRenderer | null = null; // --- A factory method for audio renderers private _audioRendererFactory: (sampleRate: number) => IAudioRenderer = () => new SilentAudioRenderer(); // --- A state manager factory private _stateManager: ICambridgeZ88BaseStateManager = new DefaultCambridgeZ88BaseStateManager(); /** * Creates a new instance of the ZX Spectrum machine * @param api Machine API to access WA * @param scw Optional screen width * @param sch Optional screen height */ constructor( public api: MachineApi, public options?: Record<string, any>, roms?: Uint8Array[] ) { super(api, options?.rom ? [options.rom] : roms); this.prepareMachine(); this.initCards(); // --- Save configuration const state = this.getMachineState(); this._screenWidth = state.screenWidth; this._screenHeight = state.screenLines; } /** * Resets the machine */ reset(): void { this.api.setupMachine(); this.initCards(); } initCards(): void { // --- Init RAM slots if (this.options?.slot1) { this.initSlot(1, this.options.slot1); } if (this.options?.slot2) { this.initSlot(2, this.options.slot2); } if (this.options?.slot3) { this.initSlot(3, this.options.slot3); this.api.setZ88Card3Rom(true); } } /** * Initializes the specified slot with the given contents * @param slot * @param contents */ initSlot(slot: number, contents: Uint8Array): void { let mask = 0x3f; switch (contents.length) { case 0x10_0000: mask = 0x3f; break; case 0x08_0000: mask = 0x1f; break; case 0x04_0000: mask = 0x0f; break; case 0x02_0000: mask = 0x07; break; case 0x01_0000: mask = 0x03; break; case 0x00_8000: mask = 0x01; break; } this.api.setZ88ChipMask(slot + 1, mask); let mh = new MemoryHelper(this.api, this.getRomPageBaseAddress()); const slotBase = slot * 1024 * 1024; for (let i = 0; i < contents.length; i++) { mh.writeByte(slotBase + i, contents[i]); } } /** * Override this property to apply multiple engine loops before * Refreshing the UI */ readonly engineLoops = 8; /** * Override this method to configure the virtual machine before turning it on */ configureMachine(): void { this.api.setZ88ScreenSize( this.options?.scw ?? 0xff, this.options?.sch ?? 8 ); } /** * Assigns an audio renderer factory to this instance * @param factory Audio renderer factory */ setAudioRendererFactory( factory: (sampleRate: number) => IAudioRenderer ): void { this._audioRendererFactory = factory; } /** * Sets the ZX Spectrum base state manage object * @param manager State manager object */ setStateManager(manager: ICambridgeZ88BaseStateManager): void { this._stateManager = manager; } /** * Get the list of machine features supported */ getExtraMachineFeatures(): ExtraMachineFeatures[] { return ["Sound"]; } /** * Gets the key mapping used by the machine */ getKeyMapping(): KeyMapping { return cz88KeyMappings; } /** * Resolves a string key code to a key number * @param code Key code to resolve */ resolveKeyCode(code: string): number | null { return cz88KeyCodes[code] ?? null; } /** * Retrieves a ZX Spectrum 48 machine state object */ createMachineState(): MachineState { return new CambridgeZ88MachineState(); } /** * Gets the memory address of the first ROM page of the machine */ getRomPageBaseAddress(): number { return 0x00_0000; } /** * Gets the specified memory partition * @param partition Partition index */ getMemoryPartition(partition: number): Uint8Array { const mh = new MemoryHelper(this.api, (partition & 0xff) * 0x4000); const result = new Uint8Array(0x4000); for (let j = 0; j < 0x4000; j++) { result[j] = mh.readByte(j); } return result; } /** * Gets the current state of the ZX Spectrum machine */ getMachineState(): CambridgeZ88MachineState { const s = super.getMachineState() as CambridgeZ88MachineState; this.api.getMachineState(); const mh = new MemoryHelper(this.api, Z88_MACHINE_STATE_BUFFER); // --- Blink device data s.COM = mh.readByte(0); s.EPR = mh.readByte(1); // --- Machine modes s.shiftsReleased = mh.readBool(2); s.isInSleepMode = mh.readBool(3); // --- Interrupt s.INT = mh.readByte(4); s.STA = mh.readByte(5); s.interruptSignalActive = mh.readBool(6); // --- Memory device s.SR0 = mh.readByte(7); s.SR1 = mh.readByte(8); s.SR2 = mh.readByte(9); s.SR3 = mh.readByte(10); s.chipMask0 = mh.readByte(11); s.chipMask1 = mh.readByte(12); s.chipMask2 = mh.readByte(13); s.chipMask3 = mh.readByte(14); s.chipMask4 = mh.readByte(15); s.chipMask5 = mh.readByte(16); // --- RTC device s.TIM0 = mh.readByte(17); s.TIM1 = mh.readByte(18); s.TIM2 = mh.readByte(19); s.TIM3 = mh.readByte(20); s.TIM4 = mh.readByte(21); s.TSTA = mh.readByte(22); s.TMK = mh.readByte(23); // --- Screen device s.PB0 = mh.readUint16(24); s.PB1 = mh.readUint16(26); s.PB2 = mh.readUint16(28); s.PB3 = mh.readUint16(30); s.SBF = mh.readUint16(32); s.SCW = mh.readByte(34); s.SCH = mh.readByte(35); s.screenFrameCount = mh.readUint32(36); s.flashPhase = mh.readBool(40); s.textFlashPhase = mh.readBool(41); s.lcdWentOff = mh.readBool(42); // --- Setup screen size s.screenWidth = s.SCW === 100 ? 800 : 640; s.screenLines = s.SCH * 8; // --- Audio s.audioSampleRate = mh.readUint32(47); s.audioSampleLength = mh.readUint32(51); s.audioLowerGate = mh.readUint32(55); s.audioUpperGate = mh.readUint32(59); s.audioGateValue = mh.readUint32(63); s.audioNextSampleTact = mh.readUint32(67); s.audioSampleCount = mh.readUint32(71); s.beeperLastEarBit = mh.readBool(75); // --- Others s.KBLine0 = mh.readByte(76); s.KBLine1 = mh.readByte(77); s.KBLine2 = mh.readByte(78); s.KBLine3 = mh.readByte(79); s.KBLine4 = mh.readByte(80); s.KBLine5 = mh.readByte(81); s.KBLine6 = mh.readByte(82); s.KBLine7 = mh.readByte(83); const slotMh = new MemoryHelper(this.api, BLOCK_LOOKUP_TABLE); s.s0OffsetL = slotMh.readUint32(0) - VM_MEMORY; s.s0FlagL = slotMh.readByte(8); s.s0OffsetH = slotMh.readUint32(16) - VM_MEMORY; s.s0FlagH = slotMh.readByte(24); s.s1OffsetL = slotMh.readUint32(32) - VM_MEMORY; s.s1FlagL = slotMh.readByte(40); s.s1OffsetH = slotMh.readUint32(48) - VM_MEMORY; s.s1FlagH = slotMh.readByte(56); s.s2OffsetL = slotMh.readUint32(64) - VM_MEMORY; s.s2FlagL = slotMh.readByte(72); s.s2OffsetH = slotMh.readUint32(80) - VM_MEMORY; s.s2FlagH = slotMh.readByte(88); s.s3OffsetL = slotMh.readUint32(96) - VM_MEMORY; s.s3FlagL = slotMh.readByte(104); s.s3OffsetH = slotMh.readUint32(112) - VM_MEMORY; s.s3FlagH = slotMh.readByte(120); return s; } /** * Gets the addressable Z80 memory contents from the machine */ getMemoryContents(): Uint8Array { const result = new Uint8Array(0x1_0000); const mh = new MemoryHelper(this.api, BLOCK_LOOKUP_TABLE); for (let i = 0; i < 8; i++) { const offs = i * 0x2000; const pageStart = mh.readUint32(i * 16); const source = new Uint8Array(this.api.memory.buffer, pageStart, 0x2000); for (let j = 0; j < 0x2000; j++) { result[offs + j] = source[j]; } } return result; } /** * Gets the screen data of the virtual machine */ /** * Gets the screen data of the ZX Spectrum machine */ getScreenData(): Uint32Array { const buffer = this.api.memory.buffer as ArrayBuffer; const screenData = new Uint32Array( buffer.slice( Z88_PIXEL_BUFFER, Z88_PIXEL_BUFFER + 4 * this._screenWidth * this._screenHeight ) ); return screenData; } /** * Sets the audio sample rate * @param rate Sample rate */ setAudioSampleRate(rate: number): void { this.api.setBeeperSampleRate(rate); } /** * Prepares the engine for code injection * @param model Model to run in the virtual machine */ async prepareForInjection(_model: string): Promise<number> { // TODO: Implement this method return 0; } /** * Cleans up audio */ async cleanupAudio(): Promise<void> { if (this._beeperRenderer) { await this._beeperRenderer.closeAudio(); this._beeperRenderer = null; } } // ========================================================================== // Lifecycle methods /** * Override this method to define an action when the virtual machine has * started. * @param debugging Is started in debug mode? */ async beforeStarted(debugging: boolean): Promise<void> { await super.beforeStarted(debugging); // --- Init audio renderers const state = this.getMachineState(); this._beeperRenderer = this._audioRendererFactory( state.tactsInFrame / state.audioSampleLength ); this._beeperRenderer.suspend(); await this._beeperRenderer.initializeAudio(); } /** * Stops audio when the machine has paused * @param isFirstPause Is the machine paused the first time? */ async onPaused(isFirstPause: boolean): Promise<void> { await super.onPaused(isFirstPause); this.cleanupAudio(); } /** * Stops audio when the machine has stopped */ async onStopped(): Promise<void> { await super.onStopped(); this.cleanupAudio(); } /** * Takes care that the screen and the audio gets refreshed as a frame * completes * @param resultState Machine state on frame completion */ async onFrameCompleted( resultState: CambridgeZ88MachineState, toWait: number ): Promise<void> { const state = resultState as CambridgeZ88MachineState; this.vmEngineController.setUiMessage( state.lcdWentOff ? "Z88 turned the LCD off (no activity). Press F6 to use Z88 again." : null ); if (toWait >= 0) { this.vmEngineController.signScreenRefreshed(); } // --- Update load state const emuState = this._stateManager.getState().emulatorPanelState; if (!this.executionOptions.disableScreenRendering) { // --- Obtain beeper samples let mh = new MemoryHelper(this.api, Z88_BEEPER_BUFFER); const beeperSamples = mh .readBytes(0, resultState.audioSampleCount) .map((smp) => (emuState.muted ? 0 : smp * (emuState.soundLevel ?? 0))); this._beeperRenderer.storeSamples(beeperSamples); this._beeperRenderer.resume(); } } /** * Executes a machine specific command. * @param command Command to execute * @param controller Machine controller */ async executeMachineCommand( command: string, controller: IVmEngineController ): Promise<void> { switch (command) { case CZ88_SOFT_RESET: await controller.stop(); await controller.start(); break; case CZ88_HARD_RESET: await controller.stop(); this.api.setupMachine(); this.api.clearMemory(); this.initCards(); await controller.start(); break; case CZ88_PRESS_BOTH_SHIFTS: this.api.setKeyStatus(cz88KeyCodes.ShiftL, true); this.api.setKeyStatus(cz88KeyCodes.ShiftR, true); await new Promise((r) => setTimeout(r, 400)); this.api.setKeyStatus(cz88KeyCodes.ShiftL, false); this.api.setKeyStatus(cz88KeyCodes.ShiftR, false); break; case CZ88_BATTERY_LOW: const state = this.getMachineState(); if (state.isInSleepMode) { this.api.setKeyStatus(cz88KeyCodes.ShiftL, true); this.api.setKeyStatus(cz88KeyCodes.ShiftR, true); await new Promise((r) => setTimeout(r, 400)); this.api.setKeyStatus(cz88KeyCodes.ShiftL, false); this.api.setKeyStatus(cz88KeyCodes.ShiftR, false); } this.api.raiseBatteryLow(); break; } } } /** * Z88 INT flag values */ export enum IntFlags { BM_INTKWAIT = 0x80, BM_INTA19 = 0x40, BM_INTFLAP = 0x20, BM_INTUART = 0x10, BM_INTBTL = 0x08, BM_INTKEY = 0x04, BM_INTTIME = 0x02, BM_INTGINT = 0x01, } /** * Z88 TSTA flag values */ export enum TstaFlags { BM_TSTATICK = 0x01, BM_TSTASEC = 0x02, BM_TSTAMIN = 0x04, } /** * Z88 TMK flag values */ export enum TmkFlags { BM_TMKTICK = 0x01, BM_TMKSEC = 0x02, BM_TMKMIN = 0x04, } /** * Provides a way to test a Z88 virtual machine in Node */ class SilentAudioRenderer implements IAudioRenderer { async initializeAudio(): Promise<void> {} storeSamples(_samples: number[]): void {} suspend(): void {} resume(): void {} async closeAudio(): Promise<void> {} } /** * A no-op implementation of class DefaultZxSpectrumBaseStateManager implements ICambridgeZ88BaseStateManager { */ class DefaultCambridgeZ88BaseStateManager implements ICambridgeZ88BaseStateManager { getState(): any {} }
the_stack
'use strict'; import * as core from '@actions/core'; import * as fs from 'fs'; import * as yaml from 'js-yaml'; import { checkForErrors, sleep } from '../utility'; import { Kubectl } from '../../kubectl-object-model'; import { KubernetesWorkload } from '../../constants'; import * as fileHelper from '../files-helper'; import * as helper from '../resource-object-utility'; import * as TaskInputParameters from '../../input-parameters'; import { routeBlueGreenService } from './service-blue-green-helper'; import { routeBlueGreenIngress } from './ingress-blue-green-helper'; import { routeBlueGreenSMI } from './smi-blue-green-helper'; export const BLUE_GREEN_DEPLOYMENT_STRATEGY = 'BLUE-GREEN'; export const GREEN_LABEL_VALUE = 'green'; export const NONE_LABEL_VALUE = 'None'; export const BLUE_GREEN_VERSION_LABEL = 'k8s.deploy.color'; export const GREEN_SUFFIX = '-green'; export const STABLE_SUFFIX = '-stable' const INGRESS_ROUTE = 'INGRESS'; const SMI_ROUTE = 'SMI'; export function isBlueGreenDeploymentStrategy() { const deploymentStrategy = TaskInputParameters.deploymentStrategy; return deploymentStrategy && deploymentStrategy.toUpperCase() === BLUE_GREEN_DEPLOYMENT_STRATEGY; } export function isIngressRoute(): boolean { const routeMethod = TaskInputParameters.routeMethod; return routeMethod && routeMethod.toUpperCase() === INGRESS_ROUTE; } export function isSMIRoute(): boolean { const routeMethod = TaskInputParameters.routeMethod; return routeMethod && routeMethod.toUpperCase() === SMI_ROUTE; } export interface BlueGreenManifests { serviceEntityList: any[], serviceNameMap: Map<string, string>, unroutedServiceEntityList: any[], deploymentEntityList: any[], ingressEntityList: any[], otherObjects: any[] } export async function routeBlueGreen(kubectl: Kubectl, inputManifestFiles: string[]) { // get buffer time let bufferTime: number = parseInt(TaskInputParameters.versionSwitchBuffer); //logging start of buffer time let dateNow = new Date(); console.log(`Starting buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`); // waiting await sleep(bufferTime*1000*60); // logging end of buffer time dateNow = new Date(); console.log(`Stopping buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`); const manifestObjects: BlueGreenManifests = getManifestObjects(inputManifestFiles); // routing to new deployments if (isIngressRoute()) { routeBlueGreenIngress(kubectl, GREEN_LABEL_VALUE, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList); } else if (isSMIRoute()) { routeBlueGreenSMI(kubectl, GREEN_LABEL_VALUE, manifestObjects.serviceEntityList); } else { routeBlueGreenService(kubectl, GREEN_LABEL_VALUE, manifestObjects.serviceEntityList); } } export function deleteWorkloadsWithLabel(kubectl: Kubectl, deleteLabel: string, deploymentEntityList: any[]) { let resourcesToDelete = [] deploymentEntityList.forEach((inputObject) => { const name = inputObject.metadata.name; const kind = inputObject.kind; if (deleteLabel === NONE_LABEL_VALUE) { // if dellabel is none, deletes stable deployments const resourceToDelete = { name : name, kind : kind}; resourcesToDelete.push(resourceToDelete); } else { // if dellabel is not none, then deletes new green deployments const resourceToDelete = { name : getBlueGreenResourceName(name, GREEN_SUFFIX), kind : kind }; resourcesToDelete.push(resourceToDelete); } }); // deletes the deployments deleteObjects(kubectl, resourcesToDelete); } export function deleteWorkloadsAndServicesWithLabel(kubectl: Kubectl, deleteLabel: string, deploymentEntityList: any[], serviceEntityList: any[]) { // need to delete services and deployments const deletionEntitiesList = deploymentEntityList.concat(serviceEntityList); let resourcesToDelete = [] deletionEntitiesList.forEach((inputObject) => { const name = inputObject.metadata.name; const kind = inputObject.kind; if (deleteLabel === NONE_LABEL_VALUE) { // if not dellabel, delete stable objects const resourceToDelete = { name : name, kind : kind}; resourcesToDelete.push(resourceToDelete); } else { // else delete green labels const resourceToDelete = { name : getBlueGreenResourceName(name, GREEN_SUFFIX), kind : kind }; resourcesToDelete.push(resourceToDelete); } }); deleteObjects(kubectl, resourcesToDelete); } export function deleteObjects(kubectl: Kubectl, deleteList: any[]) { // delete services and deployments deleteList.forEach((delObject) => { try { const result = kubectl.delete([delObject.kind, delObject.name]); checkForErrors([result]); } catch (ex) { // Ignore failures of delete if doesn't exist } }); } export function getSuffix(label: string): string { if(label === GREEN_LABEL_VALUE) { return GREEN_SUFFIX } else { return ''; } } // other common functions export function getManifestObjects (filePaths: string[]): BlueGreenManifests { const deploymentEntityList = []; const routedServiceEntityList = []; const unroutedServiceEntityList = []; const ingressEntityList = []; const otherEntitiesList = []; let serviceNameMap = new Map<string, string>(); filePaths.forEach((filePath: string) => { const fileContents = fs.readFileSync(filePath); yaml.safeLoadAll(fileContents, function (inputObject) { if(!!inputObject) { const kind = inputObject.kind; const name = inputObject.metadata.name; if (helper.isDeploymentEntity(kind)) { deploymentEntityList.push(inputObject); } else if (helper.isServiceEntity(kind)) { if (isServiceRouted(inputObject, deploymentEntityList)) { routedServiceEntityList.push(inputObject); serviceNameMap.set(name, getBlueGreenResourceName(name, GREEN_SUFFIX)); } else { unroutedServiceEntityList.push(inputObject); } } else if (helper.isIngressEntity(kind)) { ingressEntityList.push(inputObject); } else { otherEntitiesList.push(inputObject); } } }); }) return { serviceEntityList: routedServiceEntityList, serviceNameMap: serviceNameMap, unroutedServiceEntityList: unroutedServiceEntityList, deploymentEntityList: deploymentEntityList, ingressEntityList: ingressEntityList, otherObjects: otherEntitiesList }; } export function isServiceRouted(serviceObject: any[], deploymentEntityList: any[]): boolean { let shouldBeRouted: boolean = false; const serviceSelector: any = getServiceSelector(serviceObject); if (!!serviceSelector) { if (deploymentEntityList.some((depObject) => { // finding if there is a deployment in the given manifests the service targets const matchLabels: any = getDeploymentMatchLabels(depObject); return (!!matchLabels && isServiceSelectorSubsetOfMatchLabel(serviceSelector, matchLabels)) })) { shouldBeRouted = true; } } return shouldBeRouted; } export function createWorkloadsWithLabel(kubectl: Kubectl, deploymentObjectList: any[], nextLabel: string) { const newObjectsList = []; deploymentObjectList.forEach((inputObject) => { // creating deployment with label const newBlueGreenObject = getNewBlueGreenObject(inputObject, nextLabel); core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject)); newObjectsList.push(newBlueGreenObject); }); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const result = kubectl.apply(manifestFiles); return { 'result': result, 'newFilePaths': manifestFiles }; } export function getNewBlueGreenObject(inputObject: any, labelValue: string): object { const newObject = JSON.parse(JSON.stringify(inputObject)); // Updating name only if label is green label is given if (labelValue === GREEN_LABEL_VALUE) { newObject.metadata.name = getBlueGreenResourceName(inputObject.metadata.name, GREEN_SUFFIX); } // Adding labels and annotations addBlueGreenLabelsAndAnnotations(newObject, labelValue); return newObject; } export function addBlueGreenLabelsAndAnnotations(inputObject: any, labelValue: string) { //creating the k8s.deploy.color label const newLabels = new Map<string, string>(); newLabels[BLUE_GREEN_VERSION_LABEL] = labelValue; // updating object labels and selector labels helper.updateObjectLabels(inputObject, newLabels, false); helper.updateSelectorLabels(inputObject, newLabels, false); // updating spec labels if it is a service if (!helper.isServiceEntity(inputObject.kind)) { helper.updateSpecLabels(inputObject, newLabels, false); } } export function getBlueGreenResourceName(name: string, suffix: string) { return `${name}${suffix}`; } export function getDeploymentMatchLabels(deploymentObject: any): any { if (!!deploymentObject && deploymentObject.kind.toUpperCase()==KubernetesWorkload.pod.toUpperCase() && !!deploymentObject.metadata && !!deploymentObject.metadata.labels) { return deploymentObject.metadata.labels; } else if (!!deploymentObject && deploymentObject.spec && deploymentObject.spec.selector && deploymentObject.spec.selector.matchLabels) { return deploymentObject.spec.selector.matchLabels; } return null; } export function getServiceSelector(serviceObject: any): any { if (!!serviceObject && serviceObject.spec && serviceObject.spec.selector) { return serviceObject.spec.selector; } else return null; } export function isServiceSelectorSubsetOfMatchLabel(serviceSelector: any, matchLabels: any): boolean { let serviceSelectorMap = new Map(); let matchLabelsMap = new Map(); JSON.parse(JSON.stringify(serviceSelector), (key, value) => { serviceSelectorMap.set(key, value); }); JSON.parse(JSON.stringify(matchLabels), (key, value) => { matchLabelsMap.set(key, value); }); let isMatch = true; serviceSelectorMap.forEach((value, key) => { if (!!key && (!matchLabelsMap.has(key) || matchLabelsMap.get(key)) != value) { isMatch = false; } }); return isMatch; } export function fetchResource(kubectl: Kubectl, kind: string, name: string) { const result = kubectl.getResource(kind, name); if (result == null || !!result.stderr) { return null; } if (!!result.stdout) { const resource = JSON.parse(result.stdout); try { UnsetsClusterSpecficDetails(resource); return resource; } catch (ex) { core.debug('Exception occurred while Parsing ' + resource + ' in Json object'); core.debug(`Exception:${ex}`); } } return null; } function UnsetsClusterSpecficDetails(resource: any) { if (resource == null) { return; } // Unsets the cluster specific details in the object if (!!resource) { const metadata = resource.metadata; const status = resource.status; if (!!metadata) { const newMetadata = { 'annotations': metadata.annotations, 'labels': metadata.labels, 'name': metadata.name }; resource.metadata = newMetadata; } if (!!status) { resource.status = {}; } } }
the_stack
import { PromiseFactory, TimeoutError } from 'common/promises/promise-factory'; import { CallbackWindowCommandMessageListener, CommandMessage, CommandMessageResponse, CommandMessageResponseCallback, RespondableCommandMessageCommunicator, } from 'injected/frameCommunicators/respondable-command-message-communicator'; import { failTestOnErrorLogger } from 'tests/unit/common/fail-test-on-error-logger'; import { LinkedWindowMessagePoster } from 'tests/unit/common/linked-window-message-poster'; import { RecordingLogger } from 'tests/unit/common/recording-logger'; import { createSimulatedWindowMessagePoster, SimulatedWindowMessagePoster, } from 'tests/unit/common/simulated-window'; import { IMock, It, Mock, MockBehavior, Times } from 'typemoq'; describe('RespondableCommandMessageCommunicator', () => { let testSubject: RespondableCommandMessageCommunicator; let mockBackchannelWindowMessagePoster: SimulatedWindowMessagePoster; let mockPromiseFactory: IMock<PromiseFactory>; const uniqueId = 'unique_id'; beforeEach(() => { mockBackchannelWindowMessagePoster = createSimulatedWindowMessagePoster(); mockPromiseFactory = Mock.ofType<PromiseFactory>(); testSubject = new RespondableCommandMessageCommunicator( mockBackchannelWindowMessagePoster.object, () => { return uniqueId; }, mockPromiseFactory.object, failTestOnErrorLogger, ); }); describe('promise message behavior', () => { test('addPromiseCommandMessageListener does not register listener if one already exists for that command', () => { testSubject.initialize(); const listener1 = jest.fn(); const listener2 = jest.fn(); expect(() => testSubject.addPromiseCommandMessageListener('command1', listener1), ).not.toThrow(); expect(() => testSubject.addPromiseCommandMessageListener('command1', listener2), ).toThrowError(`Cannot register two listeners for the same command (command1)`); }); test('onWindowMessage parses message request and sends response to registered listener', async () => { testSubject.initialize(); const targetWindow = {} as Window; const inputRequest = { type: 'CommandMessageRequest', commandMessageId: 'request-id', command: 'command1', payload: 'request payload', }; const expectedResponse = { type: 'CommandMessageResponse', requestCommandMessageId: 'request-id', payload: 'response payload', }; const listener1 = jest.fn(async (receivedMessage, sourceWindow) => { expect(receivedMessage.payload).toBe(inputRequest.payload); return { payload: expectedResponse.payload }; }); const listener2 = jest.fn(async (receivedMessage, sourceWindow) => { fail("shouldn't be called"); }); testSubject.addPromiseCommandMessageListener('command1', listener1); testSubject.addPromiseCommandMessageListener('command2', listener2); mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, expectedResponse)) .verifiable(Times.once()); // trigger message await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( inputRequest, targetWindow, ); expect(listener1).toHaveBeenCalledTimes(1); expect(listener2).not.toHaveBeenCalled(); mockBackchannelWindowMessagePoster.verifyAll(); }); test('onWindowMessage parses message request and sends back an empty response if there is no registered listener', async () => { testSubject.initialize(); const targetWindow = {} as Window; const inputRequest = { type: 'CommandMessageRequest', commandMessageId: 'request-id', command: 'command1', payload: 'request payload', }; const expectedResponse = { type: 'CommandMessageResponse', requestCommandMessageId: 'request-id', payload: null, }; mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, expectedResponse)) .verifiable(Times.once()); // trigger message await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( inputRequest, targetWindow, ); mockBackchannelWindowMessagePoster.verifyAll(); }); test('onWindowMessage parses message request and sends back an empty response if listener is removed', async () => { testSubject.initialize(); const targetWindow = {} as Window; const inputRequest = { type: 'CommandMessageRequest', commandMessageId: 'request-id', command: 'command1', payload: 'request payload', }; const expectedResponse = { type: 'CommandMessageResponse', requestCommandMessageId: 'request-id', payload: null, }; const listener1 = jest.fn(async () => null); testSubject.addPromiseCommandMessageListener('command1', listener1); testSubject.removeCommandMessageListener('command1'); mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, expectedResponse)) .verifiable(Times.once()); // trigger message await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( inputRequest, targetWindow, ); mockBackchannelWindowMessagePoster.verifyAll(); expect(listener1).not.toHaveBeenCalled(); }); test('onWindowMessage parses message request and sends back an empty response if listener elects not to respond', async () => { testSubject.initialize(); const targetWindow = {} as Window; const inputRequest = { type: 'CommandMessageRequest', commandMessageId: 'request-id', command: 'command1', payload: 'request payload', }; const expectedResponse = { type: 'CommandMessageResponse', requestCommandMessageId: 'request-id', payload: null, }; const listener1 = async (receivedMessage, sourceWindow) => { return null; }; testSubject.addPromiseCommandMessageListener('command1', listener1); mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, expectedResponse)) .verifiable(Times.once()); // trigger message await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( inputRequest, targetWindow, ); mockBackchannelWindowMessagePoster.verifyAll(); }); test("onWindowMessage ignores messages that aren't related to respondable commands", async () => { testSubject.initialize(); const targetWindow = {} as Window; const promiseListener = jest.fn(); const callbackListener = jest.fn(); testSubject.addPromiseCommandMessageListener('command1', promiseListener); testSubject.addCallbackCommandMessageListener('command2', callbackListener); mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(It.isAny(), It.isAny())) .verifiable(Times.never()); // trigger message await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( { unrelated: 'message' }, targetWindow, ); mockBackchannelWindowMessagePoster.verifyAll(); expect(promiseListener).not.toHaveBeenCalled(); expect(callbackListener).not.toHaveBeenCalled(); }); test('sendPromiseCommandMessage creates deferred promise which resolves with matching response from WindowMessagePoster', async () => { testSubject.initialize(); const targetWindow = {} as Window; const commandMessage = { command: 'command1', payload: 'message1', }; const commandMessageResponseWrapper = { command: 'command1', payload: 'message1', requestCommandMessageId: 'unique_id', type: 'CommandMessageResponse', }; const listener1 = jest.fn((receivedMessage, sourceWindow) => { return receivedMessage.payload; }); const commandMessageRequestWrapper = { command: 'command1', payload: 'message1', commandMessageId: 'id1', type: 'CommandMessageRequest', }; testSubject.addPromiseCommandMessageListener('command1', listener1); //will listen for 'command1' command mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, It.isAny())) .verifiable(); mockPromiseFactory .setup(x => x.timeout( It.isAny(), RespondableCommandMessageCommunicator.promiseResponseTimeoutMilliseconds, ), ) .returns((originalPromise: Promise<any>) => originalPromise) .verifiable(Times.once()); //create deferred promise for command const commandPromise = testSubject.sendPromiseCommandMessage( targetWindow, commandMessage, ); //send request wrapper to window await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( commandMessageRequestWrapper, targetWindow, ); //send response wrapper to window const windowMessagePromise = mockBackchannelWindowMessagePoster.notifyOnWindowMessage( commandMessageResponseWrapper, targetWindow, ); const [, message] = await Promise.all([windowMessagePromise, commandPromise]); //run response request and sending response at same time expect(message).toEqual({ payload: 'message1' }); }); test('sendPromiseCommandMessage creates deferred promise which never resolves without response from WindowMessagePoster', async () => { testSubject.initialize(); const targetWindow = {} as Window; const commandMessage = { command: 'command1', payload: 'message1', }; const commandMessageResponseWrapper = { command: 'command1', payload: 'message1', requestCommandMessageId: 'unique_id', type: 'CommandMessageResponse', }; const listener1 = jest.fn((receivedMessage, sourceWindow) => { return receivedMessage.payload; }); const commandMessageRequestWrapper = { command: 'command1', payload: 'message1', commandMessageId: 'id1', type: 'CommandMessageRequest', }; testSubject.addPromiseCommandMessageListener('command1', listener1); //will listen for 'command1' command mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, It.isAny())) .verifiable(); mockPromiseFactory .setup(x => x.timeout( It.isAny(), RespondableCommandMessageCommunicator.promiseResponseTimeoutMilliseconds, ), ) .returns(async () => Promise.resolve()) .verifiable(Times.once()); //create deferred promise for command const commandPromise = await testSubject.sendPromiseCommandMessage( targetWindow, commandMessage, ); //send request wrapper to window await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( commandMessageRequestWrapper, targetWindow, ); //send response wrapper to window const windowMessagePromise = await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( commandMessageResponseWrapper, targetWindow, ); const [, message] = await Promise.all([windowMessagePromise, commandPromise]); //run response request and sending response at same time expect(message).toEqual(undefined); }); describe('timeout behavior', () => { const targetWindow = {} as Window; const commandMessage = { command: 'command1', payload: 'message1', }; let recordingLogger: RecordingLogger; beforeEach(() => { recordingLogger = new RecordingLogger(); mockBackchannelWindowMessagePoster.setup(poster => poster.postMessage(targetWindow, It.isAny()), ); mockPromiseFactory .setup(x => x.timeout( It.isAny(), RespondableCommandMessageCommunicator.promiseResponseTimeoutMilliseconds, ), ) .returns(() => Promise.reject(new TimeoutError('mock timeout'))) .verifiable(Times.once()); testSubject = new RespondableCommandMessageCommunicator( mockBackchannelWindowMessagePoster.object, () => { return uniqueId; }, mockPromiseFactory.object, recordingLogger, ); }); it('rejects with an error that warns about potential message interception', async () => { testSubject.initialize(); await expect( testSubject.sendPromiseCommandMessage(targetWindow, commandMessage), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Timed out attempting to establish communication with target window. Is there a script inside it intercepting window messages? Underlying error: mock timeout"`, ); expect(recordingLogger.errorMessages).toStrictEqual([]); }); it('logs an error if a response comes back after we already failed with a timeout', async () => { testSubject.initialize(); await expect( testSubject.sendPromiseCommandMessage(targetWindow, commandMessage), ).rejects.toThrowError(); const lateResponse = { command: commandMessage.command, payload: 'late response message', requestCommandMessageId: 'unique_id', type: 'CommandMessageResponse', }; await mockBackchannelWindowMessagePoster.notifyOnWindowMessage( lateResponse, targetWindow, ); expect(recordingLogger.errorMessages).toMatchInlineSnapshot(` Array [ "Received a response for command command1 after it timed out", ] `); }); }); it('propogates errors from the underlying postMessage by rejecting with them as-is', async () => { testSubject.initialize(); const targetWindow = {} as Window; const commandMessage = { command: 'command1', payload: 'message1', }; const postMessageError = new Error('from underlying postMessage'); mockBackchannelWindowMessagePoster .setup(poster => poster.postMessage(targetWindow, It.isAny())) .throws(postMessageError); mockPromiseFactory .setup(x => x.timeout(It.isAny(), It.isAny())) .returns(originalPromise => originalPromise); await expect( testSubject.sendPromiseCommandMessage(targetWindow, commandMessage), ).rejects.toThrowError(postMessageError); }); }); describe('callback message behavior', () => { const emptyCommand1Message = { command: 'command1', payload: {} }; const noopReplyHandler = () => {}; const stubGenerateUID = () => 'unique_id'; let senderWindow: Window; let sender: RespondableCommandMessageCommunicator; let receiverWindow: Window; let receiver: RespondableCommandMessageCommunicator; let mockListener: IMock<CallbackWindowCommandMessageListener>; let mockReplyHandler: IMock<CommandMessageResponseCallback>; let senderLogger: RecordingLogger; let receiverLogger: RecordingLogger; beforeEach(() => { senderLogger = new RecordingLogger(); receiverLogger = new RecordingLogger(); const [senderPoster, receiverPoster] = LinkedWindowMessagePoster.createLinkedMockPair(); senderWindow = senderPoster.window; receiverWindow = receiverPoster.window; sender = new RespondableCommandMessageCommunicator( senderPoster, stubGenerateUID, mockPromiseFactory.object, senderLogger, ); receiver = new RespondableCommandMessageCommunicator( receiverPoster, stubGenerateUID, mockPromiseFactory.object, receiverLogger, ); mockListener = Mock.ofInstance(() => {}, MockBehavior.Strict); mockReplyHandler = Mock.ofInstance(() => {}, MockBehavior.Strict); sender.initialize(); receiver.initialize(); }); it('supports callback-based communcation in single-response mode', () => { const sentMessage: CommandMessage = { command: 'command1', payload: { request: 1 }, }; const response: CommandMessageResponse = { payload: { response: 1 }, }; mockListener .setup(l => l(sentMessage, senderWindow, It.isAny())) .callback((msg, sender, responder) => { responder(response); }) .verifiable(Times.once()); mockReplyHandler.setup(h => h(response)).verifiable(Times.once()); receiver.addCallbackCommandMessageListener('command1', mockListener.object); sender.sendCallbackCommandMessage( receiverWindow, sentMessage, mockReplyHandler.object, 'single', ); mockListener.verifyAll(); mockReplyHandler.verifyAll(); senderLogger.verifyNoErrors(); receiverLogger.verifyNoErrors(); }); it('supports callback-based communcation in multiple-response mode', () => { const sentMessage: CommandMessage = { command: 'command1', payload: { request: 1 }, }; const response1: CommandMessageResponse = { payload: { response: 1 }, }; const response2: CommandMessageResponse = { payload: { response: 2 }, }; mockListener .setup(l => l(sentMessage, senderWindow, It.isAny())) .callback((msg, sender, responder) => { responder(response1); responder(response2); }) .verifiable(Times.once()); mockReplyHandler.setup(h => h(response1)).verifiable(Times.once()); mockReplyHandler.setup(h => h(response2)).verifiable(Times.once()); receiver.addCallbackCommandMessageListener('command1', mockListener.object); sender.sendCallbackCommandMessage( receiverWindow, sentMessage, mockReplyHandler.object, 'multiple', ); mockListener.verifyAll(); mockReplyHandler.verifyAll(); senderLogger.verifyNoErrors(); receiverLogger.verifyNoErrors(); }); it('does not apply a timeout to callback messages', () => { sender.sendCallbackCommandMessage( receiverWindow, emptyCommand1Message, noopReplyHandler, 'single', ); mockPromiseFactory.verify(pf => pf.timeout(It.isAny(), It.isAny()), Times.never()); }); it('ignores repeated responses to a single-response message', () => { const sentMessage: CommandMessage = { command: 'command1', payload: { request: 1 }, }; const response1: CommandMessageResponse = { payload: { response: 1 }, }; const response2: CommandMessageResponse = { payload: { response: 2 }, }; mockListener .setup(l => l(sentMessage, senderWindow, It.isAny())) .callback((msg, sender, responder) => { responder(response1); responder(response2); }) .verifiable(Times.once()); mockReplyHandler.setup(h => h(response1)).verifiable(Times.once()); mockReplyHandler.setup(h => h(response2)).verifiable(Times.never()); receiver.addCallbackCommandMessageListener('command1', mockListener.object); sender.sendCallbackCommandMessage( receiverWindow, sentMessage, mockReplyHandler.object, 'single', ); mockListener.verifyAll(); mockReplyHandler.verifyAll(); senderLogger.verifyNoErrors(); receiverLogger.verifyNoErrors(); }); it('propogates errors from the underlying postMessage by rejecting with them as-is', () => { const unlinkedWindow = {} as Window; expect(() => sender.sendCallbackCommandMessage( unlinkedWindow, emptyCommand1Message, noopReplyHandler, 'single', ), ).toThrowErrorMatchingInlineSnapshot( `"target window unreachable (LinkedWindowMessagePoster not linked to it)"`, ); }); it('handles throwing listeners by logging an error at the receiver', () => { const listenerError = new Error('from listener'); const sentMessage: CommandMessage = { command: 'command1', payload: { request: 1 }, }; mockListener .setup(l => l(sentMessage, senderWindow, It.isAny())) .callback((msg, sender, responder) => { throw listenerError; }) .verifiable(Times.once()); mockReplyHandler.setup(h => h(It.isAny())).verifiable(Times.never()); receiver.addCallbackCommandMessageListener('command1', mockListener.object); sender.sendCallbackCommandMessage( receiverWindow, sentMessage, mockReplyHandler.object, 'single', ); mockListener.verifyAll(); mockReplyHandler.verifyAll(); senderLogger.verifyNoErrors(); expect(receiverLogger.errorMessages).toMatchInlineSnapshot(` Array [ "Error at command1 listener callback: from listener", ] `); }); it('handles throwing replyHandlers by logging an error at the sender', () => { const replyHandlerError = new Error('from replyHandler'); const sentMessage: CommandMessage = { command: 'command1', payload: { request: 1 }, }; const response: CommandMessageResponse = { payload: { response: 1 }, }; mockListener .setup(l => l(sentMessage, senderWindow, It.isAny())) .callback((msg, sender, responder) => { responder(response); }) .verifiable(Times.once()); mockReplyHandler .setup(h => h(response)) .callback(() => { throw replyHandlerError; }) .verifiable(Times.once()); receiver.addCallbackCommandMessageListener('command1', mockListener.object); sender.sendCallbackCommandMessage( receiverWindow, sentMessage, mockReplyHandler.object, 'single', ); mockListener.verifyAll(); mockReplyHandler.verifyAll(); receiverLogger.verifyNoErrors(); expect(senderLogger.errorMessages).toMatchInlineSnapshot(` Array [ "Error at unique_id response callback: from replyHandler", ] `); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_schedulingparameter_Information { interface tab_tab_5_Sections { tab_5_section_2: DevKit.Controls.Section; } interface tab_tab_5 extends DevKit.Controls.ITab { Section: tab_tab_5_Sections; } interface Tabs { tab_5: tab_tab_5; } interface Body { Tab: Tabs; /** When changing bookings on hourly Schedule Board, automatically update travel time and distance for affected bookings. */ msdyn_AutoUpdateBookingTravel: DevKit.Controls.OptionSet; /** Determines if the mapping provider will be used for map location and distance calculations. */ msdyn_ConnectToMaps: DevKit.Controls.Boolean; /** Shows the logical name of the latitude field to be used by geolocations. */ msdyn_CustomGeoLatitudeField: DevKit.Controls.String; /** Shows the logical name of custom entity to be used for geolocations. */ msdyn_CustomGeoLocationEntity: DevKit.Controls.String; /** Shows the logical name of the longitude field to be used for geolocations. */ msdyn_CustomGeoLongitudeField: DevKit.Controls.String; /** Shows the logical name of the resource field to be used for geolocations. */ msdyn_CustomGeoResourceField: DevKit.Controls.String; /** Shows the logical name of the timestamp field to be used for geolocations. */ msdyn_CustomGeoTimestampField: DevKit.Controls.String; msdyn_DefaultRadiusUnit: DevKit.Controls.OptionSet; msdyn_DefaultRadiusValue: DevKit.Controls.Integer; /** Disable Sanitizing HTML Templates on the Schedule Board */ msdyn_DisableSanitizingHTMLTemplates: DevKit.Controls.Boolean; /** Enable appointments to display on the new schedule board and be considered in availability search for resources. */ msdyn_EnableAppointments: DevKit.Controls.OptionSet; /** Determines if a custom entity will be used as a source of geo locations for resources to be displayed in the map view. */ msdyn_EnableCustomGeoLocation: DevKit.Controls.Boolean; msdyn_GeoLocationExpiresAfterXMinutes: DevKit.Controls.Integer; msdyn_GeoLocationRefreshIntervalSeconds: DevKit.Controls.Integer; /** Api key for map */ msdyn_MapApiKey: DevKit.Controls.String; /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Determines if the schedule assistant should automatically filter results based on the requirement territory. */ msdyn_SAAutoFilterServiceTerritory: DevKit.Controls.Boolean; msdyn_ScheduleBoardRefreshIntervalSeconds: DevKit.Controls.Integer; } } class Formmsdyn_schedulingparameter_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_schedulingparameter_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_schedulingparameter_Information */ Body: DevKit.Formmsdyn_schedulingparameter_Information.Body; } class msdyn_schedulingparameterApi { /** * DynamicsCrm.DevKit msdyn_schedulingparameterApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** For internal use */ msdyn_AdvancedSettings: DevKit.WebApi.StringValue; /** When changing bookings on hourly Schedule Board, automatically update travel time and distance for affected bookings. */ msdyn_AutoUpdateBookingTravel: DevKit.WebApi.OptionSetValue; /** Configuration that defines operations, which will be executed in background periodically (internal use only) */ msdyn_BackgroundJobsConfiguration: DevKit.WebApi.StringValue; /** Determines if the mapping provider will be used for map location and distance calculations. */ msdyn_ConnectToMaps: DevKit.WebApi.BooleanValue; /** Shows the logical name of the latitude field to be used by geolocations. */ msdyn_CustomGeoLatitudeField: DevKit.WebApi.StringValue; /** Shows the logical name of custom entity to be used for geolocations. */ msdyn_CustomGeoLocationEntity: DevKit.WebApi.StringValue; /** Shows the logical name of the longitude field to be used for geolocations. */ msdyn_CustomGeoLongitudeField: DevKit.WebApi.StringValue; /** Shows the logical name of the resource field to be used for geolocations. */ msdyn_CustomGeoResourceField: DevKit.WebApi.StringValue; /** Shows the logical name of the timestamp field to be used for geolocations. */ msdyn_CustomGeoTimestampField: DevKit.WebApi.StringValue; msdyn_DefaultRadiusUnit: DevKit.WebApi.OptionSetValue; msdyn_DefaultRadiusValue: DevKit.WebApi.IntegerValue; /** Disable Sanitizing HTML Templates on the Schedule Board */ msdyn_DisableSanitizingHTMLTemplates: DevKit.WebApi.BooleanValue; /** Enable appointments to display on the new schedule board and be considered in availability search for resources. */ msdyn_EnableAppointments: DevKit.WebApi.OptionSetValue; /** Determines if a custom entity will be used as a source of geo locations for resources to be displayed in the map view. */ msdyn_EnableCustomGeoLocation: DevKit.WebApi.BooleanValue; /** Determines if scheduling optimization is enabled. */ msdyn_enableOptimizer: DevKit.WebApi.BooleanValue; msdyn_GeoLocationExpiresAfterXMinutes: DevKit.WebApi.IntegerValue; msdyn_GeoLocationRefreshIntervalSeconds: DevKit.WebApi.IntegerValue; /** Api key for map */ msdyn_MapApiKey: DevKit.WebApi.StringValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Determines if the schedule assistant should automatically filter results based on the requirement territory. */ msdyn_SAAutoFilterServiceTerritory: DevKit.WebApi.BooleanValue; msdyn_ScheduleBoardRefreshIntervalSeconds: DevKit.WebApi.IntegerValue; /** A unique identifier for an entity instance. */ msdyn_schedulingparameterId: DevKit.WebApi.GuidValue; /** Unique identifier for the organization */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Status of the Scheduling Parameter */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Scheduling Parameter */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_schedulingparameter { enum msdyn_AutoUpdateBookingTravel { /** 192350000 */ Disabled, /** 192350001 */ Enabled } enum msdyn_DefaultRadiusUnit { /** 192350001 */ KM, /** 192350000 */ Miles } enum msdyn_EnableAppointments { /** 192350000 */ No, /** 192350001 */ Yes } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { StartTranslationParameters, GetTranslationsStatusParameters, GetDocumentStatusParameters, GetTranslationStatusParameters, CancelTranslationParameters, GetDocumentsStatusParameters, GetSupportedDocumentFormatsParameters, GetSupportedGlossaryFormatsParameters, GetSupportedStorageSourcesParameters, } from "./parameters"; import { StartTranslation202Response, StartTranslation400Response, StartTranslation401Response, StartTranslation429Response, StartTranslation500Response, StartTranslation503Response, GetTranslationsStatus200Response, GetTranslationsStatus400Response, GetTranslationsStatus401Response, GetTranslationsStatus429Response, GetTranslationsStatus500Response, GetTranslationsStatus503Response, GetDocumentStatus200Response, GetDocumentStatus401Response, GetDocumentStatus404Response, GetDocumentStatus429Response, GetDocumentStatus500Response, GetDocumentStatus503Response, GetTranslationStatus200Response, GetTranslationStatus401Response, GetTranslationStatus404Response, GetTranslationStatus429Response, GetTranslationStatus500Response, GetTranslationStatus503Response, CancelTranslation200Response, CancelTranslation401Response, CancelTranslation404Response, CancelTranslation429Response, CancelTranslation500Response, CancelTranslation503Response, GetDocumentsStatus200Response, GetDocumentsStatus400Response, GetDocumentsStatus401Response, GetDocumentsStatus404Response, GetDocumentsStatus429Response, GetDocumentsStatus500Response, GetDocumentsStatus503Response, GetSupportedDocumentFormats200Response, GetSupportedDocumentFormats429Response, GetSupportedDocumentFormats500Response, GetSupportedDocumentFormats503Response, GetSupportedGlossaryFormats200Response, GetSupportedGlossaryFormats429Response, GetSupportedGlossaryFormats500Response, GetSupportedGlossaryFormats503Response, GetSupportedStorageSources200Response, GetSupportedStorageSources429Response, GetSupportedStorageSources500Response, GetSupportedStorageSources503Response, } from "./responses"; import { getClient, ClientOptions, Client } from "@azure-rest/core-client"; import { KeyCredential, TokenCredential } from "@azure/core-auth"; export interface GetTranslationsStatus { /** * Use this API to submit a bulk (batch) translation request to the Document Translation service. * Each request can contain multiple documents and must contain a source and destination container for each document. * * The prefix and suffix filter (if supplied) are used to filter folders. The prefix is applied to the subpath after the container name. * * Glossaries / Translation memory can be included in the request and are applied by the service when the document is translated. * * If the glossary is invalid or unreachable during translation, an error is indicated in the document status. * If a file with the same name already exists at the destination, it will be overwritten. The targetUrl for each target language must be unique. */ post( options: StartTranslationParameters ): Promise< | StartTranslation202Response | StartTranslation400Response | StartTranslation401Response | StartTranslation429Response | StartTranslation500Response | StartTranslation503Response >; /** * Returns a list of batch requests submitted and the status for each request. * This list only contains batch requests submitted by the user (based on the resource). * * If the number of requests exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and include a continuation token in the response. * The absence of a continuation token means that no additional pages are available. * * $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection. * * $top indicates the total number of records the user wants to be returned across all pages. * $skip indicates the number of records to skip from the list of batches based on the sorting method specified. By default, we sort by descending start time. * $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), \@nextLink will contain the link to the next page. * * $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc"). * The default sorting is descending by createdDateTimeUtc. * Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled operations. * createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by. * The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd). * * The server honors the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token. * * When both $top and $skip are included, the server should first apply $skip and then $top on the collection. * Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options. * This reduces the risk of the client making assumptions about the data returned. */ get( options?: GetTranslationsStatusParameters ): Promise< | GetTranslationsStatus200Response | GetTranslationsStatus400Response | GetTranslationsStatus401Response | GetTranslationsStatus429Response | GetTranslationsStatus500Response | GetTranslationsStatus503Response >; } export interface GetDocumentStatus { /** Returns the translation status for a specific document based on the request Id and document Id. */ get( options?: GetDocumentStatusParameters ): Promise< | GetDocumentStatus200Response | GetDocumentStatus401Response | GetDocumentStatus404Response | GetDocumentStatus429Response | GetDocumentStatus500Response | GetDocumentStatus503Response >; } export interface CancelTranslation { /** * Returns the status for a document translation request. * The status includes the overall request status, as well as the status for documents that are being translated as part of that request. */ get( options?: GetTranslationStatusParameters ): Promise< | GetTranslationStatus200Response | GetTranslationStatus401Response | GetTranslationStatus404Response | GetTranslationStatus429Response | GetTranslationStatus500Response | GetTranslationStatus503Response >; /** * Cancel a currently processing or queued translation. * Cancel a currently processing or queued translation. * A translation will not be cancelled if it is already completed or failed or cancelling. A bad request will be returned. * All documents that have completed translation will not be cancelled and will be charged. * All pending documents will be cancelled if possible. */ delete( options?: CancelTranslationParameters ): Promise< | CancelTranslation200Response | CancelTranslation401Response | CancelTranslation404Response | CancelTranslation429Response | CancelTranslation500Response | CancelTranslation503Response >; } export interface GetDocumentsStatus { /** * Returns the status for all documents in a batch document translation request. * * If the number of documents in the response exceeds our paging limit, server-side paging is used. * Paginated responses indicate a partial result and include a continuation token in the response. The absence of a continuation token means that no additional pages are available. * * $top, $skip and $maxpagesize query parameters can be used to specify a number of results to return and an offset for the collection. * * $top indicates the total number of records the user wants to be returned across all pages. * $skip indicates the number of records to skip from the list of document status held by the server based on the sorting method specified. By default, we sort by descending start time. * $maxpagesize is the maximum items returned in a page. If more items are requested via $top (or $top is not specified and there are more items to be returned), \@nextLink will contain the link to the next page. * * $orderBy query parameter can be used to sort the returned list (ex "$orderBy=createdDateTimeUtc asc" or "$orderBy=createdDateTimeUtc desc"). * The default sorting is descending by createdDateTimeUtc. * Some query parameters can be used to filter the returned list (ex: "status=Succeeded,Cancelled") will only return succeeded and cancelled documents. * createdDateTimeUtcStart and createdDateTimeUtcEnd can be used combined or separately to specify a range of datetime to filter the returned list by. * The supported filtering query parameters are (status, ids, createdDateTimeUtcStart, createdDateTimeUtcEnd). * * When both $top and $skip are included, the server should first apply $skip and then $top on the collection. * Note: If the server can't honor $top and/or $skip, the server must return an error to the client informing about it instead of just ignoring the query options. * This reduces the risk of the client making assumptions about the data returned. */ get( options?: GetDocumentsStatusParameters ): Promise< | GetDocumentsStatus200Response | GetDocumentsStatus400Response | GetDocumentsStatus401Response | GetDocumentsStatus404Response | GetDocumentsStatus429Response | GetDocumentsStatus500Response | GetDocumentsStatus503Response >; } export interface GetSupportedDocumentFormats { /** * The list of supported document formats supported by the Document Translation service. * The list includes the common file extension, as well as the content-type if using the upload API. */ get( options?: GetSupportedDocumentFormatsParameters ): Promise< | GetSupportedDocumentFormats200Response | GetSupportedDocumentFormats429Response | GetSupportedDocumentFormats500Response | GetSupportedDocumentFormats503Response >; } export interface GetSupportedGlossaryFormats { /** * The list of supported glossary formats supported by the Document Translation service. * The list includes the common file extension used. */ get( options?: GetSupportedGlossaryFormatsParameters ): Promise< | GetSupportedGlossaryFormats200Response | GetSupportedGlossaryFormats429Response | GetSupportedGlossaryFormats500Response | GetSupportedGlossaryFormats503Response >; } export interface GetSupportedStorageSources { /** Returns a list of storage sources/options supported by the Document Translation service. */ get( options?: GetSupportedStorageSourcesParameters ): Promise< | GetSupportedStorageSources200Response | GetSupportedStorageSources429Response | GetSupportedStorageSources500Response | GetSupportedStorageSources503Response >; } export interface Routes { /** Resource for '/batches' has methods for the following verbs: post, get */ (path: "/batches"): GetTranslationsStatus; /** Resource for '/batches/\{id\}/documents/\{documentId\}' has methods for the following verbs: get */ (path: "/batches/{id}/documents/{documentId}", id: string, documentId: string): GetDocumentStatus; /** Resource for '/batches/\{id\}' has methods for the following verbs: get, delete */ (path: "/batches/{id}", id: string): CancelTranslation; /** Resource for '/batches/\{id\}/documents' has methods for the following verbs: get */ (path: "/batches/{id}/documents", id: string): GetDocumentsStatus; /** Resource for '/documents/formats' has methods for the following verbs: get */ (path: "/documents/formats"): GetSupportedDocumentFormats; /** Resource for '/glossaries/formats' has methods for the following verbs: get */ (path: "/glossaries/formats"): GetSupportedGlossaryFormats; /** Resource for '/storagesources' has methods for the following verbs: get */ (path: "/storagesources"): GetSupportedStorageSources; } export type DocumentTranslatorClient = Client & { path: Routes; }; export interface DocumentTranslatorFactory { (endpoint: string, credentials: TokenCredential | KeyCredential, options?: ClientOptions): void; } export default function DocumentTranslator( endpoint: string, credentials: TokenCredential | KeyCredential, options: ClientOptions = {} ): DocumentTranslatorClient { const baseUrl = options.baseUrl ?? `${endpoint}/translator/text/batch/v1.0-preview.1`; options = { ...options, credentials: { scopes: ["https://cognitiveservices.azure.com/.default"], apiKeyHeaderName: "Ocp-Apim-Subscription-Key", }, }; return getClient(baseUrl, credentials, options) as DocumentTranslatorClient; }
the_stack
import { extractGremlinQueries } from '../extractGremlinQueries'; test('Extract the parts of the code that can be parsed as Gremlin', () => { expect( extractGremlinQueries( `graph = TinkerFactory.createModern() g = graph.traversal() g.V().has('name','marko').out('knows').values('name')`, ), ).toStrictEqual([`g.V().has('name','marko').out('knows').values('name')`]); expect( extractGremlinQueries( `g.V().has('name','marko').next() g.V(marko).out('knows') g.V(marko).out('knows').values('name')`, ), ).toStrictEqual([ `g.V().has('name','marko').next()`, `g.V(marko).out('knows')`, `g.V(marko).out('knows').values('name')`, ]); expect( extractGremlinQueries( `g = graph.traversal(); List<Vertex> vertices = g.V().toList()`, ), ).toStrictEqual([`g.V().toList()`]); expect( extractGremlinQueries( `v1 = g.addV('person').property('name','marko').next() v2 = g.addV('person').property('name','stephen').next() g.V(v1).addE('knows').to(v2).property('weight',0.75).iterate()`, ), ).toStrictEqual([ `g.addV('person').property('name','marko').next()`, `g.addV('person').property('name','stephen').next()`, `g.V(v1).addE('knows').to(v2).property('weight',0.75).iterate()`, ]); expect( extractGremlinQueries( `marko = g.V().has('person','name','marko').next() peopleMarkoKnows = g.V().has('person','name','marko').out('knows').toList()`, ), ).toStrictEqual([ `g.V().has('person','name','marko').next()`, `g.V().has('person','name','marko').out('knows').toList()`, ]); expect( extractGremlinQueries( `graph = TinkerGraph.open() g = graph.traversal() v = g.addV().property('name','marko').property('name','marko a. rodriguez').next() g.V(v).properties('name').count() v.property(list, 'name', 'm. a. rodriguez') g.V(v).properties('name').count() g.V(v).properties() g.V(v).properties('name') g.V(v).properties('name').hasValue('marko') g.V(v).properties('name').hasValue('marko').property('acl','private') g.V(v).properties('name').hasValue('marko a. rodriguez') g.V(v).properties('name').hasValue('marko a. rodriguez').property('acl','public') g.V(v).properties('name').has('acl','public').value() g.V(v).properties('name').has('acl','public').drop() g.V(v).properties('name').has('acl','public').value() g.V(v).properties('name').has('acl','private').value() g.V(v).properties() g.V(v).properties().properties() g.V(v).properties().property('date',2014) g.V(v).properties().property('creator','stephen') g.V(v).properties().properties() g.V(v).properties('name').valueMap() g.V(v).property('name','okram') g.V(v).properties('name') g.V(v).values('name')`, ), ).toStrictEqual([ `g.addV().property('name','marko').property('name','marko a. rodriguez').next()`, `g.V(v).properties('name').count()`, `g.V(v).properties('name').count()`, `g.V(v).properties()`, `g.V(v).properties('name')`, `g.V(v).properties('name').hasValue('marko')`, `g.V(v).properties('name').hasValue('marko').property('acl','private')`, `g.V(v).properties('name').hasValue('marko a. rodriguez')`, `g.V(v).properties('name').hasValue('marko a. rodriguez').property('acl','public')`, `g.V(v).properties('name').has('acl','public').value()`, `g.V(v).properties('name').has('acl','public').drop()`, `g.V(v).properties('name').has('acl','public').value()`, `g.V(v).properties('name').has('acl','private').value()`, `g.V(v).properties()`, `g.V(v).properties().properties()`, `g.V(v).properties().property('date',2014)`, `g.V(v).properties().property('creator','stephen')`, `g.V(v).properties().properties()`, `g.V(v).properties('name').valueMap()`, `g.V(v).property('name','okram')`, `g.V(v).properties('name')`, `g.V(v).values('name')`, ]); expect( extractGremlinQueries( `g.V().as('a'). properties('location').as('b'). hasNot('endTime').as('c'). select('a','b','c').by('name').by(value).by('startTime') // determine the current location of each person g.V().has('name','gremlin').inE('uses'). order().by('skill',asc).as('a'). outV().as('b'). select('a','b').by('skill').by('name') // rank the users of gremlin by their skill level`, ), ).toStrictEqual([ `g.V().as('a'). properties('location').as('b'). hasNot('endTime').as('c'). select('a','b','c').by('name').by(value).by('startTime')`, `g.V().has('name','gremlin').inE('uses'). order().by('skill',asc).as('a'). outV().as('b'). select('a','b').by('skill').by('name')`, ]); expect( extractGremlinQueries( `g.V(1).out().values('name') g.V(1).out().map {it.get().value('name')} g.V(1).out().map(values('name'))`, ), ).toStrictEqual([ `g.V(1).out().values('name')`, `g.V(1).out().map {it.get().value('name')}`, `g.V(1).out().map(values('name'))`, ]); expect( extractGremlinQueries( `g.V().filter {it.get().label() == 'person'} g.V().filter(label().is('person')) g.V().hasLabel('person')`, ), ).toStrictEqual([ `g.V().filter {it.get().label() == 'person'}`, `g.V().filter(label().is('person'))`, `g.V().hasLabel('person')`, ]); expect( extractGremlinQueries( `g.V().hasLabel('person').sideEffect(System.out.&println) g.V().sideEffect(outE().count().store("o")). sideEffect(inE().count().store("i")).cap("o","i")`, ), ).toStrictEqual([ `g.V().hasLabel('person').sideEffect(System.out.&println)`, `g.V().sideEffect(outE().count().store("o")). sideEffect(inE().count().store("i")).cap("o","i")`, ]); expect( extractGremlinQueries( `g.V().branch {it.get().value('name')}. option('marko', values('age')). option(none, values('name')) g.V().branch(values('name')). option('marko', values('age')). option(none, values('name')) g.V().choose(has('name','marko'), values('age'), values('name'))`, ), ).toStrictEqual([ `g.V().branch {it.get().value('name')}. option('marko', values('age')). option(none, values('name'))`, `g.V().branch(values('name')). option('marko', values('age')). option(none, values('name'))`, `g.V().choose(has('name','marko'), values('age'), values('name'))`, ]); expect( extractGremlinQueries( `g.V().out('created').hasNext() g.V().out('created').next() g.V().out('created').next(2) g.V().out('nothing').tryNext() g.V().out('created').toList() g.V().out('created').toSet() g.V().out('created').toBulkSet() results = ['blah',3] g.V().out('created').fill(results) g.addV('person').iterate()`, ), ).toStrictEqual([ `g.V().out('created').hasNext()`, `g.V().out('created').next()`, `g.V().out('created').next(2)`, `g.V().out('nothing').tryNext()`, `g.V().out('created').toList()`, `g.V().out('created').toSet()`, `g.V().out('created').toBulkSet()`, `g.V().out('created').fill(results)`, `g.addV('person').iterate()`, ]); expect( extractGremlinQueries( `g.V(1).as('a').out('created').in('created').where(neq('a')). addE('co-developer').from('a').property('year',2009) g.V(3,4,5).aggregate('x').has('name','josh').as('a'). select('x').unfold().hasLabel('software').addE('createdBy').to('a') g.V().as('a').out('created').addE('createdBy').to('a').property('acl','public') g.V(1).as('a').out('knows'). addE('livesNear').from('a').property('year',2009). inV().inE('livesNear').values('year') g.V().match( __.as('a').out('knows').as('b'), __.as('a').out('created').as('c'), __.as('b').out('created').as('c')). addE('friendlyCollaborator').from('a').to('b'). property(id,23).property('project',select('c').values('name')) g.E(23).valueMap() marko = g.V().has('name','marko').next() peter = g.V().has('name','peter').next() g.V(marko).addE('knows').to(peter) g.addE('knows').from(marko).to(peter)`, ), ).toStrictEqual([ `g.V(1).as('a').out('created').in('created').where(neq('a')). addE('co-developer').from('a').property('year',2009)`, `g.V(3,4,5).aggregate('x').has('name','josh').as('a'). select('x').unfold().hasLabel('software').addE('createdBy').to('a')`, `g.V().as('a').out('created').addE('createdBy').to('a').property('acl','public')`, `g.V(1).as('a').out('knows'). addE('livesNear').from('a').property('year',2009). inV().inE('livesNear').values('year')`, `g.V().match( __.as('a').out('knows').as('b'), __.as('a').out('created').as('c'), __.as('b').out('created').as('c')). addE('friendlyCollaborator').from('a').to('b'). property(id,23).property('project',select('c').values('name'))`, `g.E(23).valueMap()`, `g.V().has('name','marko').next()`, `g.V().has('name','peter').next()`, `g.V(marko).addE('knows').to(peter)`, `g.addE('knows').from(marko).to(peter)`, ]); expect( extractGremlinQueries( `g.addV('person').property('name','stephen') g.V().values('name') g.V().outE('knows').addV().property('name','nothing') g.V().has('name','nothing') g.V().has('name','nothing').bothE()`, ), ).toStrictEqual([ `g.addV('person').property('name','stephen')`, `g.V().values('name')`, `g.V().outE('knows').addV().property('name','nothing')`, `g.V().has('name','nothing')`, `g.V().has('name','nothing').bothE()`, ]); expect( extractGremlinQueries( `g.V(1).property('country','usa') g.V(1).property('city','santa fe').property('state','new mexico').valueMap() g.V(1).property(list,'age',35) g.V(1).valueMap() g.V(1).property('friendWeight',outE('knows').values('weight').sum(),'acl','private') g.V(1).properties('friendWeight').valueMap()`, ), ).toStrictEqual([ `g.V(1).property('country','usa')`, `g.V(1).property('city','santa fe').property('state','new mexico').valueMap()`, `g.V(1).property(list,'age',35)`, `g.V(1).valueMap()`, `g.V(1).property('friendWeight',outE('knows').values('weight').sum(),'acl','private')`, `g.V(1).properties('friendWeight').valueMap()`, ]); expect( extractGremlinQueries( `g.V(1).out('created') g.V(1).out('created').aggregate('x') g.V(1).out('created').aggregate(global, 'x') g.V(1).out('created').aggregate('x').in('created') g.V(1).out('created').aggregate('x').in('created').out('created') g.V(1).out('created').aggregate('x').in('created').out('created'). where(without('x')).values('name')`, ), ).toStrictEqual([ `g.V(1).out('created')`, `g.V(1).out('created').aggregate('x')`, `g.V(1).out('created').aggregate(global, 'x')`, `g.V(1).out('created').aggregate('x').in('created')`, `g.V(1).out('created').aggregate('x').in('created').out('created')`, `g.V(1).out('created').aggregate('x').in('created').out('created'). where(without('x')).values('name')`, ]); expect( extractGremlinQueries( `g.V().out('knows').aggregate('x').cap('x') g.V().out('knows').aggregate('x').by('name').cap('x')`, ), ).toStrictEqual([ `g.V().out('knows').aggregate('x').cap('x')`, `g.V().out('knows').aggregate('x').by('name').cap('x')`, ]); expect( extractGremlinQueries( `g.V().aggregate(global, 'x').limit(1).cap('x') g.V().aggregate(local, 'x').limit(1).cap('x') g.withoutStrategies(EarlyLimitStrategy).V().aggregate(local,'x').limit(1).cap('x')`, ), ).toStrictEqual([ `g.V().aggregate(global, 'x').limit(1).cap('x')`, `g.V().aggregate(local, 'x').limit(1).cap('x')`, `g.withoutStrategies(EarlyLimitStrategy).V().aggregate(local,'x').limit(1).cap('x')`, ]); expect( extractGremlinQueries( `g.V().as('a').out('created').as('b').select('a','b') g.V().as('a').out('created').as('b').select('a','b').by('name')`, ), ).toStrictEqual([ `g.V().as('a').out('created').as('b').select('a','b')`, `g.V().as('a').out('created').as('b').select('a','b').by('name')`, ]); expect( extractGremlinQueries( `g.V().sideEffect{println "first: \${it}"}.sideEffect{println "second: \${it}"}.iterate() g.V().sideEffect{println "first: \${it}"}.barrier().sideEffect{println "second: \${it}"}.iterate()`, ), ).toStrictEqual([ `g.V().sideEffect{println "first: \${it}"}.sideEffect{println "second: \${it}"}.iterate()`, `g.V().sideEffect{println "first: \${it}"}.barrier().sideEffect{println "second: \${it}"}.iterate()`, ]); expect( extractGremlinQueries( `graph = TinkerGraph.open() g = graph.traversal() g.io('data/grateful-dead.xml').read().iterate() g = graph.traversal().withoutStrategies(LazyBarrierStrategy) clockWithResult(1){g.V().both().both().both().count().next()} clockWithResult(1){g.V().repeat(both()).times(3).count().next()} clockWithResult(1){g.V().both().barrier().both().barrier().both().barrier().count().next()}`, ), ).toStrictEqual([`g.io('data/grateful-dead.xml').read().iterate()`]); expect( extractGremlinQueries( `graph = TinkerGraph.open() g = graph.traversal() g.io('data/grateful-dead.xml').read().iterate() clockWithResult(1){g.V().both().both().both().count().next()} g.V().both().both().both().count().iterate().toString()`, ), ).toStrictEqual([ `g.io('data/grateful-dead.xml').read().iterate()`, `g.V().both().both().both().count().iterate().toString()`, ]); expect( extractGremlinQueries( `g.V().group().by(bothE().count()) g.V().group().by(bothE().count()).by('name') g.V().group().by(bothE().count()).by(count())`, ), ).toStrictEqual([ `g.V().group().by(bothE().count())`, `g.V().group().by(bothE().count()).by('name')`, `g.V().group().by(bothE().count()).by(count())`, ]); expect( extractGremlinQueries( `g.V().groupCount('a').by(label).cap('a') g.V().groupCount('a').by(label).groupCount('b').by(outE().count()).cap('a','b')`, ), ).toStrictEqual([ `g.V().groupCount('a').by(label).cap('a')`, `g.V().groupCount('a').by(label).groupCount('b').by(outE().count()).cap('a','b')`, ]); expect( extractGremlinQueries( `g.V().hasLabel('person'). choose(values('age').is(lte(30)), __.in(), __.out()).values('name') g.V().hasLabel('person'). choose(values('age')). option(27, __.in()). option(32, __.out()).values('name')`, ), ).toStrictEqual([ `g.V().hasLabel('person'). choose(values('age').is(lte(30)), __.in(), __.out()).values('name')`, `g.V().hasLabel('person'). choose(values('age')). option(27, __.in()). option(32, __.out()).values('name')`, ]); expect( extractGremlinQueries( `g.V().choose(hasLabel('person'), out('created')).values('name') g.V().choose(hasLabel('person'), out('created'), identity()).values('name')`, ), ).toStrictEqual([ `g.V().choose(hasLabel('person'), out('created')).values('name')`, `g.V().choose(hasLabel('person'), out('created'), identity()).values('name')`, ]); expect( extractGremlinQueries( `g.V(1).coalesce(outE('knows'), outE('created')).inV().path().by('name').by(label) g.V(1).coalesce(outE('created'), outE('knows')).inV().path().by('name').by(label) g.V(1).property('nickname', 'okram') g.V().hasLabel('person').coalesce(values('nickname'), values('name'))`, ), ).toStrictEqual([ `g.V(1).coalesce(outE('knows'), outE('created')).inV().path().by('name').by(label)`, `g.V(1).coalesce(outE('created'), outE('knows')).inV().path().by('name').by(label)`, `g.V(1).property('nickname', 'okram')`, `g.V().hasLabel('person').coalesce(values('nickname'), values('name'))`, ]); expect( extractGremlinQueries( `g.V().coin(0.5) g.V().coin(0.0) g.V().coin(1.0)`, ), ).toStrictEqual([`g.V().coin(0.5)`, `g.V().coin(0.0)`, `g.V().coin(1.0)`]); expect( extractGremlinQueries( `g.V(). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). project('name','component'). by('name'). by('component') g.V().hasLabel('person'). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). with(ConnectedComponent.edges, outE('knows')). project('name','component'). by('name'). by('component')`, ), ).toStrictEqual([ `g.V(). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). project('name','component'). by('name'). by('component')`, `g.V().hasLabel('person'). connectedComponent(). with(ConnectedComponent.propertyName, 'component'). with(ConnectedComponent.edges, outE('knows')). project('name','component'). by('name'). by('component')`, ]); expect( extractGremlinQueries( `g.V().choose(hasLabel('person'), values('name'), constant('inhuman')) g.V().coalesce( hasLabel('person').values('name'), constant('inhuman'))`, ), ).toStrictEqual([ `g.V().choose(hasLabel('person'), values('name'), constant('inhuman'))`, `g.V().coalesce( hasLabel('person').values('name'), constant('inhuman'))`, ]); expect( extractGremlinQueries( `g.V().count() g.V().hasLabel('person').count() g.V().hasLabel('person').outE('created').count().path() g.V().hasLabel('person').outE('created').count().map {it.get() * 10}.path()`, ), ).toStrictEqual([ `g.V().count()`, `g.V().hasLabel('person').count()`, `g.V().hasLabel('person').outE('created').count().path()`, `g.V().hasLabel('person').outE('created').count().map {it.get() * 10}.path()`, ]); expect( extractGremlinQueries( `g.V(1).both().both() g.V(1).both().both().cyclicPath() g.V(1).both().both().cyclicPath().path() g.V(1).as('a').out('created').as('b'). in('created').as('c'). cyclicPath(). path() g.V(1).as('a').out('created').as('b'). in('created').as('c'). cyclicPath().from('a').to('b'). path()`, ), ).toStrictEqual([ `g.V(1).both().both()`, `g.V(1).both().both().cyclicPath()`, `g.V(1).both().both().cyclicPath().path()`, `g.V(1).as('a').out('created').as('b'). in('created').as('c'). cyclicPath(). path()`, `g.V(1).as('a').out('created').as('b'). in('created').as('c'). cyclicPath().from('a').to('b'). path()`, ]); });
the_stack
module Fayde.Media.VSM { export interface IOutValue { Value: any; } export interface IStateData { state: VisualState; group: VisualStateGroup; } export class VisualStateManager extends DependencyObject { static VisualStateGroupsProperty: DependencyProperty = DependencyProperty.RegisterAttachedCore("VisualStateGroups", () => VisualStateGroupCollection, VisualStateManager); static GetVisualStateGroups(d: DependencyObject): VisualStateGroupCollection { return d.GetValue(VisualStateManager.VisualStateGroupsProperty); } static SetVisualStateGroups(d: DependencyObject, value: VisualStateGroupCollection) { d.SetValue(VisualStateManager.VisualStateGroupsProperty, value); } static CustomVisualStateManagerProperty: DependencyProperty = DependencyProperty.RegisterAttachedCore("CustomVisualStateManager", () => VisualStateManager, VisualStateManager); static GetCustomVisualStateManager(d: DependencyObject): VisualStateManager { return d.GetValue(VisualStateManager.CustomVisualStateManagerProperty); } static SetCustomVisualStateManager(d: DependencyObject, value: VisualStateManager) { d.SetValue(VisualStateManager.CustomVisualStateManagerProperty, value); } static GoToState(control: Controls.Control, stateName: string, useTransitions: boolean): boolean { if (!control) throw new ArgumentException("control"); if (!stateName) throw new ArgumentException("stateName"); var root = VisualStateManager._GetTemplateRoot(control); if (!root) return false; var groups = VisualStateManager.GetVisualStateGroups(root); if (!groups) return false; var data: IStateData = { group: null, state: null }; if (!VisualStateManager._TryGetState(groups, stateName, data)) return false; var customVsm = VisualStateManager.GetCustomVisualStateManager(root); if (customVsm) { return customVsm.GoToStateCore(control, root, stateName, data.group, data.state, useTransitions); } else if (data.state != null) { return VisualStateManager.GoToStateInternal(control, root, data.group, data.state, useTransitions); } return false; } GoToStateCore(control: Controls.Control, element: FrameworkElement, stateName: string, group: VisualStateGroup, state: VisualState, useTransitions: boolean): boolean { return VisualStateManager.GoToStateInternal(control, element, group, state, useTransitions); } private static GoToStateInternal(control: Controls.Control, element: FrameworkElement, group: VisualStateGroup, state: VisualState, useTransitions: boolean): boolean { var lastState = group.CurrentState; if (lastState === state) return true; if (VSM.Debug && window.console) { console.log("VSM:GoToState:[" + (<any>control)._ID + "]" + (lastState ? lastState.Name : "()") + "-->" + state.Name); } var transition = useTransitions ? VisualStateManager._GetTransition(element, group, lastState, state) : null; var storyboard: Animation.Storyboard; if (transition == null || (transition.GeneratedDuration.IsZero && ((storyboard = transition.Storyboard) == null || storyboard.Duration.IsZero))) { if (transition != null && storyboard != null) { group.StartNewThenStopOld(element, [storyboard, state.Storyboard]); } else { group.StartNewThenStopOld(element, [state.Storyboard]); } group.RaiseCurrentStateChanging(element, lastState, state, control); group.RaiseCurrentStateChanged(element, lastState, state, control); } else { var dynamicTransition = genDynamicTransAnimations(element, group, state, transition); transition.DynamicStoryboardCompleted = false; var dynamicCompleted = function (sender, e) { if (transition.Storyboard == null || transition.ExplicitStoryboardCompleted === true) { group.StartNewThenStopOld(element, [state.Storyboard]); group.RaiseCurrentStateChanged(element, lastState, state, control); } transition.DynamicStoryboardCompleted = true; }; var eventClosure = {}; dynamicTransition.Completed.on(dynamicCompleted, eventClosure); if (transition.Storyboard != null && transition.ExplicitStoryboardCompleted === true) { var transitionCompleted = function (sender, e) { if (transition.DynamicStoryboardCompleted === true) { group.StartNewThenStopOld(element, [state.Storyboard]); group.RaiseCurrentStateChanged(element, lastState, state, control); } transition.Storyboard.Completed.off(transitionCompleted, eventClosure); transition.ExplicitStoryboardCompleted = true; }; transition.ExplicitStoryboardCompleted = false; transition.Storyboard.Completed.on(transitionCompleted, eventClosure); } group.StartNewThenStopOld(element, [transition.Storyboard, dynamicTransition]); group.RaiseCurrentStateChanging(element, lastState, state, control); } group.CurrentState = state; return true; } static DestroyStoryboards(control: Controls.Control, root: FrameworkElement) { if (!root) return false; var groups = VisualStateManager.GetVisualStateGroups(root); if (!groups) return false; var enumerator = groups.getEnumerator(); while (enumerator.moveNext()) { (<VisualStateGroup>enumerator.current).StopCurrentStoryboards(root); } } static Deactivate (control: Controls.Control, root: FrameworkElement) { if (!root) return false; var groups = VisualStateManager.GetVisualStateGroups(root); if (!groups) return false; for (var en = groups.getEnumerator(); en.moveNext();) { en.current.Deactivate(); } } static Activate (control: Controls.Control, root: FrameworkElement) { if (!root) return false; var groups = VisualStateManager.GetVisualStateGroups(root); if (!groups) return false; for (var en = groups.getEnumerator(); en.moveNext();) { en.current.Activate(); } } private static _GetTemplateRoot(control: Controls.Control): FrameworkElement { if (control instanceof Controls.UserControl) return (<Controls.UserControl>control).XamlNode.TemplateRoot; var enumerator = control.XamlNode.GetVisualTreeEnumerator(); var node: FENode = null; if (enumerator.moveNext()) { node = enumerator.current; if (!(node instanceof FENode)) node = null; } return (node) ? node.XObject : null; } static GetGroup(control: Controls.Control, name: string): VisualStateGroup { var root = VisualStateManager._GetTemplateRoot(control); if (!root) return null; var groups = VisualStateManager.GetVisualStateGroups(root); if (!groups) return null; var enumerator = groups.getEnumerator(); while (enumerator.moveNext()) { if (enumerator.current.Name === name) return enumerator.current; } return null; } private static _TryGetState(groups: VisualStateGroupCollection, stateName: string, data: IStateData): boolean { var enumerator = groups.getEnumerator(); while (enumerator.moveNext()) { data.group = enumerator.current; data.state = data.group.GetState(stateName); if (data.state) return true; } data.group = null; data.state = null; return false; } private static _GetTransition(element: FrameworkElement, group: VisualStateGroup, from: VisualState, to: VisualState): VisualTransition { if (!element) throw new ArgumentException("element"); if (!group) throw new ArgumentException("group"); if (!to) throw new ArgumentException("to"); var best = null; var defaultTransition = null; var bestScore = -1; var enumerator = group.Transitions.getEnumerator(); var transition: VisualTransition; while (enumerator.moveNext()) { transition = enumerator.current; if (!defaultTransition && transition.IsDefault) { defaultTransition = transition; continue; } var score = -1; var transFromState = group.GetState(transition.From); var transToState = group.GetState(transition.To); if (from === transFromState) score += 1; else if (transFromState != null) continue; if (to === transToState) score += 2; else if (transToState != null) continue; if (score > bestScore) { bestScore = score; best = transition; } } if (best != null) return best; return defaultTransition; } } Fayde.CoreLibrary.add(VisualStateManager); import Timeline = Animation.Timeline; import Storyboard = Animation.Storyboard; function genDynamicTransAnimations(root: FrameworkElement, group: VisualStateGroup, state: VisualState, transition: VisualTransition): Animation.Storyboard { var dynamic = new Animation.Storyboard(); if (transition != null) { dynamic.Duration = transition.GeneratedDuration; } else { dynamic.Duration = new Duration(new TimeSpan()); } var currentAnimations = flattenTimelines(group.CurrentStoryboards); var transitionAnimations = flattenTimelines([transition != null ? transition.Storyboard : null]); var newStateAnimations = flattenTimelines([state.Storyboard]); // Remove any animations that the transition already animates. // There is no need to create an interstitial animation if one already exists. for (var i = 0, len = transitionAnimations.length; i < len; i++){ removeTuple(transitionAnimations[i], currentAnimations); removeTuple(transitionAnimations[i], newStateAnimations); } var tuple: ITimelineTuple; // Generate the "to" animations for (var i = 0, len = newStateAnimations.length; i < len;i++){ // The new "To" Animation -- the root is passed as a reference point for name lookup. tuple = newStateAnimations[i]; var toAnimation = genToAnimation(root, tuple.timeline, true); // If the animation is of a type that we can't generate transition animations // for, GenerateToAnimation will return null, and we should just keep going. if (toAnimation != null) { ensureTarget(root, tuple.timeline, toAnimation); toAnimation.Duration = dynamic.Duration; dynamic.Children.Add(toAnimation); } removeTuple(tuple, currentAnimations); } // Generate the "from" animations for (var i = 0, len = currentAnimations.length; i < len;i++){ tuple = currentAnimations[i]; var fromAnimation = tuple.timeline.GenerateFrom(); if (fromAnimation != null) { ensureTarget(root, tuple.timeline, fromAnimation); fromAnimation.Duration = dynamic.Duration; var propertyName = Animation.Storyboard.GetTargetProperty(tuple.timeline); Animation.Storyboard.SetTargetProperty(fromAnimation, propertyName); dynamic.Children.Add(fromAnimation); } } return dynamic; } function ensureTarget(root: FrameworkElement, source: Timeline, dest: Timeline) { if (source.ManualTarget != null) { Storyboard.SetTarget(dest, source.ManualTarget); } else { var targetName = Storyboard.GetTargetName(source); if (targetName) Storyboard.SetTargetName(dest, targetName); } } function genToAnimation(root: FrameworkElement, timeline: Timeline, isEntering: boolean) { var result = timeline.GenerateTo(isEntering); if (!result) return null; var targetName = Storyboard.GetTargetName(timeline); Storyboard.SetTargetName(result, targetName); if (targetName) { var target = <DependencyObject>root.FindName(targetName); if (target instanceof DependencyObject) Storyboard.SetTarget(result, target); } Storyboard.SetTargetProperty(result, Storyboard.GetTargetProperty(timeline)); return result; } interface ITimelineTuple { dobj: DependencyObject; propd: DependencyProperty; timeline: Timeline; } function flattenTimelines(storyboards: Storyboard[]): ITimelineTuple[]{ var tuples: ITimelineTuple[] = []; for (var i = 0, len = storyboards.length; i < len; i++) { flattenTimeline((tp) => tuples.push(tp), storyboards[i], null, null); } return tuples; } function flattenTimeline(callback: (tuple: ITimelineTuple) => void, timeline: Timeline, targetObject: DependencyObject, targetPropertyPath: Data.PropertyPath) { if (!timeline) return; var resolution = Storyboard.ResolveTarget(timeline); if (resolution.Target) targetObject = resolution.Target; if (resolution.Property) targetPropertyPath = resolution.Property; if (timeline instanceof Storyboard) { for (var i = 0, children = (<Storyboard>timeline).Children, len = children.Count; i < len; i++) { flattenTimeline(callback, children.GetValueAt(i), targetObject, targetPropertyPath); } } else { if (targetPropertyPath && targetObject) { // When resolving down to a DO and DP, we don't actually want to clone DOs like we do // when starting a storyboard normally. var oto: IOutValue = { Value: targetObject }; var propd = Data.PropertyPath.ResolvePropertyPath(oto, targetPropertyPath, []); if (propd && oto.Value) callback({ dobj: oto.Value, propd: propd, timeline: timeline }); } } } function removeTuple(tuple: ITimelineTuple, list: ITimelineTuple[]) { for (var i = 0, len = list.length; i < len; i++) { var l = list[i]; if (l.dobj === tuple.dobj && l.propd === tuple.propd) return list.splice(i, 1); } } }
the_stack
import {cssClasses, numbers} from '../../mdc-ripple/constants'; import {MDCRippleFoundation} from '../../mdc-ripple/foundation'; import {captureHandlers, checkNumTimesSpyCalledWithArgs} from '../../../testing/helpers/foundation'; import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup'; import {testFoundation} from './helpers'; const {DEACTIVATION_TIMEOUT_MS} = numbers; describe('MDCRippleFoundation - Deactivation logic', () => { setUpMdcTestEnvironment(); testFoundation( 'runs deactivation UX on touchend after touchstart', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]}); jasmine.clock().tick(1); documentHandlers['touchend'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); // NOTE: here and below, we use {times: 2} as these classes are removed // during activation as well in order to support re-triggering the // ripple. We want to test that this is called a *second* time when // deactivating. checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX on pointerup after pointerdown', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['pointerdown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['pointerup'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX on contextmenu after pointerdown', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['pointerdown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['contextmenu'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX on mouseup after mousedown', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['mouseup'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX on contextmenu after mousedown', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['contextmenu'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation on keyup after keydown when keydown makes surface active', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); adapter.isSurfaceActive.and.returnValue(true); foundation.init(); jasmine.clock().tick(1); handlers['keydown']({key: 'Space'}); jasmine.clock().tick(1); handlers['keyup']({key: 'Space'}); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'does not run deactivation on keyup after keydown if keydown did not make surface active', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); adapter.isSurfaceActive.and.returnValue(false); foundation.init(); jasmine.clock().tick(1); handlers['keydown']({key: 'Space'}); jasmine.clock().tick(1); handlers['keyup']({key: 'Space'}); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); // Note that all of these should be called 0 times since a keydown that // does not make a surface active should never activate it in the first // place. expect(adapter.removeClass) .not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION); expect(adapter.addClass) .not.toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX on public deactivate() call', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { foundation.init(); jasmine.clock().tick(1); foundation.activate(); jasmine.clock().tick(1); foundation.deactivate(); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'runs deactivation UX when activation UX timer finishes first (activation held for a long time)', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); documentHandlers['mouseup'](); jasmine.clock().tick(1); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); expect(adapter.addClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); expect(adapter.removeClass) .toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'clears any pending deactivation UX timers when re-triggered', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); // Trigger the first interaction handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['mouseup'](); jasmine.clock().tick(1); // Simulate certain amount of delay between first and second interaction jasmine.clock().tick(20); // Trigger the second interaction handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['mouseup'](); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); // Verify that deactivation timer was called 3 times: // - Once during the initial activation // - Once again during the second activation when the ripple was // re-triggered // - A third and final time when the deactivation UX timer runs checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 3); checkNumTimesSpyCalledWithArgs( adapter.addClass, [cssClasses.FG_DEACTIVATION], 1); }); testFoundation( 'clears any pending foreground deactivation class removal timers when re-triggered', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); // Trigger the first interaction handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['mouseup'](); jasmine.clock().tick(1); // Tick the clock such that the deactivation UX gets run, but _not_ so // the foreground deactivation removal timer gets run jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); // Sanity check that the foreground deactivation class removal was only // called once within the activation code. checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_DEACTIVATION], 1); // Trigger another activation handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); // Tick the clock past the time when the initial foreground deactivation // timer would have ran. jasmine.clock().tick(numbers.FG_DEACTIVATION_MS); // Verify that the foreground deactivation class removal was only called // twice: once within the original activation, and again within this // subsequent activation; NOT by means of any timers firing. checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_DEACTIVATION], 2); }); testFoundation( 'waits until activation UX timer runs before removing active fill classes', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); documentHandlers['mouseup'](); // Test conditions slightly before the timeout lapses (subtracting ~2 // frames due to runToFrame above) jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS - 32); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 1); expect(adapter.addClass) .not.toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); jasmine.clock().tick(32); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_DEACTIVATION], 1); }); testFoundation( 'waits until actual deactivation UX is needed if animation finishes before deactivating', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); foundation.init(); jasmine.clock().tick(1); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 1); expect(adapter.addClass) .not.toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION); }); testFoundation( 'only re-activates when there are no additional pointer events to be processed', ({adapter, foundation}: {adapter: any, foundation: MDCRippleFoundation}) => { const handlers = captureHandlers(adapter, 'registerInteractionHandler'); const documentHandlers = captureHandlers(adapter, 'registerDocumentInteractionHandler'); foundation.init(); jasmine.clock().tick(1); // Simulate Android 6 / Chrome latest event flow. handlers['pointerdown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]}); jasmine.clock().tick(1); jasmine.clock().tick(DEACTIVATION_TIMEOUT_MS); documentHandlers['pointerup'](); jasmine.clock().tick(1); // At this point, the deactivation UX should have run, since the initial // activation was triggered by a pointerdown event. checkNumTimesSpyCalledWithArgs( adapter.removeClass, [cssClasses.FG_ACTIVATION], 2); checkNumTimesSpyCalledWithArgs( adapter.addClass, [cssClasses.FG_DEACTIVATION], 1); // Also at this point, all of the document event handlers should have // been deregistered so no more will be called. ['mouseup', 'pointerup', 'touchend'].forEach((type) => { expect(adapter.deregisterDocumentInteractionHandler) .toHaveBeenCalledWith(type, jasmine.any(Function)); }); handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); // Verify that activation only happened once, at pointerdown checkNumTimesSpyCalledWithArgs( adapter.addClass, [cssClasses.FG_ACTIVATION], 1); documentHandlers['mouseup'](); jasmine.clock().tick(1); jasmine.clock().tick(numbers.TAP_DELAY_MS); // Finally, verify that since mouseup happened, we can re-activate the // ripple. handlers['mousedown']({pageX: 0, pageY: 0}); jasmine.clock().tick(1); checkNumTimesSpyCalledWithArgs( adapter.addClass, [cssClasses.FG_ACTIVATION], 2); }); });
the_stack
import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; import { DOCUMENT, isPlatformBrowser } from '@angular/common'; import { ScrollToConfigOptions, ScrollToConfigOptionsTarget, ScrollToListenerTarget, ScrollToTarget } from './scroll-to-config.interface'; import { ScrollToAnimation } from './scroll-to-animation'; import { DEFAULTS, isElementRef, isNativeElement, isNumber, isString, isWindow, stripHash } from './scroll-to-helpers'; import { Observable, ReplaySubject, throwError } from 'rxjs'; /** * The Scroll To Service handles starting, interrupting * and ending the actual Scroll Animation. It provides * some utilities to find the proper HTML Element on a * given page to setup Event Listeners and calculate * distances for the Animation. */ @Injectable() export class ScrollToService { /** * The animation that provides the scrolling * to happen smoothly over time. Defining it here * allows for usage of e.g. `start` and `stop` * methods within this Angular Service. */ private animation: ScrollToAnimation; /** * Interruptive Events allow to scrolling animation * to be interrupted before it is finished. The list * of Interruptive Events represents those. */ private interruptiveEvents: string[]; /** * Construct and setup required paratemeters. * * @param document A Reference to the Document * @param platformId Angular Platform ID */ constructor( @Inject(DOCUMENT) private document: any, @Inject(PLATFORM_ID) private platformId: any ) { this.interruptiveEvents = ['mousewheel', 'DOMMouseScroll', 'touchstart']; } /** * Target an Element to scroll to. Notice that the `TimeOut` decorator * ensures the executing to take place in the next Angular lifecycle. * This allows for scrolling to elements that are e.g. initially hidden * by means of `*ngIf`, but ought to be scrolled to eventually. * * @todo type 'any' in Observable should become custom type like 'ScrollToEvent' (base class), see issue comment: * - https://github.com/nicky-lenaers/ngx-scroll-to/issues/10#issuecomment-317198481 * * @param options Configuration Object * @returns Observable */ scrollTo(options: ScrollToConfigOptions): Observable<any> { if (!isPlatformBrowser(this.platformId)) { return new ReplaySubject().asObservable(); } return this.start(options); } /** * Start a new Animation. * * @todo Emit proper events from subscription * * @param options Configuration Object * @returns Observable */ private start(options: ScrollToConfigOptions): Observable<number> { // Merge config with default values const mergedConfigOptions = { ...DEFAULTS as ScrollToConfigOptions, ...options } as ScrollToConfigOptionsTarget; if (this.animation) { this.animation.stop(); } const targetNode = this.getNode(mergedConfigOptions.target); if (mergedConfigOptions.target && !targetNode) { return throwError('Unable to find Target Element'); } const container: HTMLElement = this.getContainer(mergedConfigOptions, targetNode); if (mergedConfigOptions.container && !container) { return throwError('Unable to find Container Element'); } const listenerTarget = this.getListenerTarget(container) || window; let to = container ? container.getBoundingClientRect().top : 0; if (targetNode) { to = isWindow(listenerTarget) ? window.scrollY + targetNode.getBoundingClientRect().top : targetNode.getBoundingClientRect().top; } // Create Animation this.animation = new ScrollToAnimation( container, listenerTarget, isWindow(listenerTarget), to, mergedConfigOptions, isPlatformBrowser(this.platformId) ); const onInterrupt = () => this.animation.stop(); this.addInterruptiveEventListeners(listenerTarget, onInterrupt); // Start Animation const animation$ = this.animation.start(); this.subscribeToAnimation(animation$, listenerTarget, onInterrupt); return animation$; } /** * Subscribe to the events emitted from the Scrolling * Animation. Events might be used for e.g. unsubscribing * once finished. * * @param animation$ The Animation Observable * @param listenerTarget The Listener Target for events * @param onInterrupt The handler for Interruptive Events * @returns Void */ private subscribeToAnimation( animation$: Observable<any>, listenerTarget: ScrollToListenerTarget, onInterrupt: EventListenerOrEventListenerObject ) { const subscription = animation$ .subscribe( () => { }, () => { }, () => { this.removeInterruptiveEventListeners(this.interruptiveEvents, listenerTarget, onInterrupt); subscription.unsubscribe(); } ); } /** * Get the container HTML Element in which * the scrolling should happen. * * @param options The Merged Configuration Object * @param targetNode the targeted HTMLElement */ private getContainer(options: ScrollToConfigOptions, targetNode: HTMLElement): HTMLElement | null { let container: HTMLElement | null = null; if (options.container) { container = this.getNode(options.container, true); } else if (targetNode) { container = this.getFirstScrollableParent(targetNode); } return container; } /** * Add listeners for the Animation Interruptive Events * to the Listener Target. * * @param events List of events to listen to * @param listenerTarget Target to attach the listener on * @param handler Handler for when the listener fires * @returns Void */ private addInterruptiveEventListeners( listenerTarget: ScrollToListenerTarget, handler: EventListenerOrEventListenerObject): void { if (!listenerTarget) { listenerTarget = window; } this.interruptiveEvents .forEach(event => listenerTarget .addEventListener(event, handler, this.supportPassive() ? {passive: true} : false)); } /** * Feature-detect support for passive event listeners. * * @returns Whether or not passive event listeners are supported */ private supportPassive(): boolean { let supportsPassive = false; try { const opts = Object.defineProperty({}, 'passive', { get: () => { supportsPassive = true; } }); window.addEventListener('testPassive', null, opts); window.removeEventListener('testPassive', null, opts); } catch (e) { } return supportsPassive; } /** * Remove listeners for the Animation Interrupt Event from * the Listener Target. Specifying the correct handler prevents * memory leaks and makes the allocated memory available for * Garbage Collection. * * @param events List of Interruptive Events to remove * @param listenerTarget Target to attach the listener on * @param handler Handler for when the listener fires * @returns Void */ private removeInterruptiveEventListeners( events: string[], listenerTarget: ScrollToListenerTarget, handler: EventListenerOrEventListenerObject): void { if (!listenerTarget) { listenerTarget = window; } events.forEach(event => listenerTarget.removeEventListener(event, handler)); } /** * Find the first scrollable parent Node of a given * Element. The DOM Tree gets searched upwards * to find this first scrollable parent. Parents might * be ignored by CSS styles applied to the HTML Element. * * @param nativeElement The Element to search the DOM Tree upwards from * @returns The first scrollable parent HTML Element */ private getFirstScrollableParent(nativeElement: HTMLElement): HTMLElement { let style: CSSStyleDeclaration = window.getComputedStyle(nativeElement); const overflowRegex: RegExp = /(auto|scroll|overlay)/; if (style.position === 'fixed') { return null; } let parent = nativeElement; while (parent.parentElement) { parent = parent.parentElement; style = window.getComputedStyle(parent); if (style.position === 'absolute' || style.overflow === 'hidden' || style.overflowY === 'hidden') { continue; } if (overflowRegex.test(style.overflow + style.overflowY) || parent.tagName === 'BODY') { return parent; } } return null; } /** * Get the Target Node to scroll to. * * @param id The given ID of the node, either a string or * an element reference * @param allowBodyTag Indicate whether or not the Document Body is * considered a valid Target Node * @returns The Target Node to scroll to */ private getNode(id: ScrollToTarget, allowBodyTag: boolean = false): HTMLElement { let targetNode: HTMLElement; if (isString(id)) { if (allowBodyTag && (id === 'body' || id === 'BODY')) { targetNode = this.document.body; } else { targetNode = this.document.getElementById(stripHash(id)); } } else if (isNumber(id)) { targetNode = this.document.getElementById(String(id)); } else if (isElementRef(id)) { targetNode = id.nativeElement; } else if (isNativeElement(id)) { targetNode = id; } return targetNode; } /** * Retrieve the Listener target. This Listener Target is used * to attach Event Listeners on. In case of the target being * the Document Body, we need the actual `window` to listen * for events. * * @param container The HTML Container element * @returns The Listener Target to attach events on */ private getListenerTarget(container: HTMLElement): ScrollToListenerTarget { if (!container) { return null; } return this.isDocumentBody(container) ? window : container; } /** * Test if a given HTML Element is the Document Body. * * @param element The given HTML Element * @returns Whether or not the Element is the * Document Body Element */ private isDocumentBody(element: HTMLElement): element is HTMLBodyElement { return element.tagName.toUpperCase() === 'BODY'; } }
the_stack
import * as React from 'react'; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { Label } from "office-ui-fabric-react/lib/Label"; import * as strings from 'ControlStrings'; import styles from './ListItemAttachments.module.scss'; import { UploadAttachment } from './UploadAttachment'; import { IListItemAttachmentFile } from './IListItemAttachmentFile'; import { DocumentCard, DocumentCardActions, DocumentCardPreview, IDocumentCardPreviewImage } from 'office-ui-fabric-react/lib/DocumentCard'; import { ImageFit } from 'office-ui-fabric-react/lib/Image'; import { IListItemAttachmentsProps } from '.'; import { IListItemAttachmentsState } from '.'; import SPservice from "../../services/SPService"; import { TooltipHost, DirectionalHint } from 'office-ui-fabric-react/lib/Tooltip'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import utilities from './utilities'; import { Placeholder } from "../placeholder"; import * as telemetry from '../../common/telemetry'; interface IPreviewImageCollection { [fileName: string]: IDocumentCardPreviewImage; } export class ListItemAttachments extends React.Component<IListItemAttachmentsProps, IListItemAttachmentsState> { private _spservice: SPservice; private previewImages: IPreviewImageCollection = {}; private _utilities: utilities; constructor(props: IListItemAttachmentsProps) { super(props); telemetry.track('ReactListItemAttachments', {}); this.state = { file: null, hideDialog: true, dialogMessage: '', attachments: [], deleteAttachment: false, disableButton: false, showPlaceHolder: false, fireUpload: false, filesToUpload: [], itemId: props.itemId }; // Get SPService Factory this._spservice = new SPservice(this.props.context); this._utilities = new utilities(); } /** * componentDidMount lifecycle hook */ public async componentDidMount() { await this.loadAttachments(); } private async loadAttachmentPreview(file: IListItemAttachmentFile): Promise<IDocumentCardPreviewImage> { return this._utilities.GetFileImageUrl(file).then(previewImageUrl => { return { name: file.FileName, previewImageSrc: previewImageUrl, iconSrc: '', imageFit: ImageFit.center, width: 187, height: 130, }; }); } public async uploadAttachments(itemId: number){ if(this.state.filesToUpload){ await Promise.all(this.state.filesToUpload.map(file=>this._spservice.addAttachment( this.props.listId, itemId, file.name, file, this.props.webUrl))); } return new Promise<void>((resolve,error)=>{ this.setState({ filesToUpload: [], itemId: itemId },()=>this.loadAttachments().then(resolve)); }); } protected loadAttachmentsPreview(files: IListItemAttachmentFile[]){ const filePreviewImages = files.map(file => this.loadAttachmentPreview(file)); return Promise.all(filePreviewImages).then(filePreviews => { filePreviews.forEach(preview => { this.previewImages[preview.name] = preview; }); this.setState({ fireUpload: false, hideDialog: true, dialogMessage: '', attachments: files, showPlaceHolder: files.length === 0 ? true : false }); }); } /** * Load Item Attachments */ private async loadAttachments() { if(this.state.itemId){ await this._spservice.getListItemAttachments(this.props.listId, this.state.itemId).then(async (files: IListItemAttachmentFile[]) => { await this.loadAttachmentsPreview(files); }).catch((error: Error) => { this.setState({ fireUpload: false, hideDialog: false, dialogMessage: strings.ListItemAttachmentserrorLoadAttachments.replace('{0}', error.message) }); }); } else if(this.state.filesToUpload && this.state.filesToUpload.length > 0){ let files = this.state.filesToUpload.map(file=>({ FileName: file.name, ServerRelativeUrl: undefined })); await this.loadAttachmentsPreview(files); } else{ this.setState({ fireUpload: false, hideDialog: true, dialogMessage: '', showPlaceHolder: true }); } } /** * Close the dialog */ private _closeDialog = () => { this.setState({ fireUpload: false, hideDialog: true, dialogMessage: '', file: null, deleteAttachment: false, }); this.loadAttachments(); } /** * Attachment uploaded event handler */ private _onAttachmentUpload = async (file: File) => { // load Attachments if(!this.state.itemId){ let files = this.state.filesToUpload || []; files.push(file); this.setState({ filesToUpload: [...files] }); } await this.loadAttachments(); } /** * On delete attachment event handler * * @param file */ private onDeleteAttachment = (file: IListItemAttachmentFile) => { this.setState({ fireUpload: false, hideDialog: false, deleteAttachment: true, file: file, dialogMessage: strings.ListItemAttachmentsconfirmDelete.replace('{0}', file.FileName), }); } /** * Delete the attachment once it was confirmed */ private onConfirmedDeleteAttachment = async () => { // Delete Attachment const { file } = this.state; this.setState({ fireUpload: false, disableButton: true, }); try { if(this.state.itemId){ await this._spservice.deleteAttachment(file.FileName, this.props.listId, this.state.itemId, this.props.webUrl); } else{ let filesToUpload = this.state.filesToUpload; let fileToRemove = filesToUpload.find(f=>f.name === file.FileName); if(fileToRemove){ filesToUpload.splice(filesToUpload.indexOf(fileToRemove),1); } let attachments = this.state.attachments; let attachmentToRemove = attachments.find(attachment => attachment.FileName === file.FileName); if(attachmentToRemove){ attachments.splice(attachments.indexOf(attachmentToRemove),1); } this.setState({ filesToUpload: [...filesToUpload], attachments: [...attachments] }); } this.setState({ fireUpload: false, hideDialog: false, deleteAttachment: false, disableButton: false, file: null, dialogMessage: strings.ListItemAttachmentsfileDeletedMsg.replace('{0}', file.FileName), }); } catch (error) { this.setState({ fireUpload: false, hideDialog: false, file: null, deleteAttachment: false, dialogMessage: strings.ListItemAttachmentsfileDeleteError.replace('{0}', file.FileName).replace('{1}', error.message) }); } } /** * Default React render method */ public render() { const { openAttachmentsInNewWindow } = this.props; return ( <div className={styles.ListItemAttachments}> <UploadAttachment listId={this.props.listId} itemId={this.state.itemId} disabled={this.props.disabled} context={this.props.context} onAttachmentUpload={this._onAttachmentUpload} fireUpload={this.state.fireUpload} /> { this.state.showPlaceHolder ? <Placeholder iconName='Upload' iconText={this.props.label || strings.ListItemAttachmentslPlaceHolderIconText} description={this.props.description || strings.ListItemAttachmentslPlaceHolderDescription} buttonLabel={strings.ListItemAttachmentslPlaceHolderButtonLabel} hideButton={this.props.disabled} onConfigure={() => this.setState({ fireUpload: true })} /> : this.state.attachments.map(file => { const fileName = file.FileName; const previewImage = this.previewImages[fileName]; return ( <div key={fileName} className={styles.documentCardWrapper}> <TooltipHost content={fileName} calloutProps={{ gapSpace: 0, isBeakVisible: true }} closeDelay={200} directionalHint={DirectionalHint.rightCenter}> <DocumentCard onClickHref={!openAttachmentsInNewWindow && `${file.ServerRelativeUrl}?web=1`} onClick={openAttachmentsInNewWindow && (() => window.open(`${file.ServerRelativeUrl}?web=1`, "_blank"))} // JJ - 20200613 - needed to support Microsoft Teams className={styles.documentCard}> <DocumentCardPreview previewImages={[previewImage]} /> <Label className={styles.fileLabel}>{fileName}</Label> <DocumentCardActions actions={ [ { iconProps: { iconName: 'Delete', title: strings.ListItemAttachmentsActionDeleteIconTitle, }, title: strings.ListItemAttachmentsactionDeleteTitle, text: strings.ListItemAttachmentsactionDeleteTitle, disabled: this.props.disabled, onClick: (ev) => { ev.preventDefault(); ev.stopPropagation(); this.onDeleteAttachment(file); } }, ] } /> </DocumentCard> </TooltipHost> </div> ); })} { !this.state.hideDialog && <Dialog hidden={this.state.hideDialog} type={DialogType.normal} onDismiss={this._closeDialog} dialogContentProps={{ type: DialogType.normal, title: strings.ListItemAttachmentsdialogTitle, subText: this.state.dialogMessage }} modalProps={{ isBlocking: true, containerClassName: 'ms-dialogMainOverride' }} > <DialogFooter> <div style={{ marginBottom: 7 }}> { this.state.disableButton ? <Spinner size={SpinnerSize.medium} /> : null } </div> { this.state.deleteAttachment ? (<PrimaryButton disabled={this.state.disableButton} onClick={this.onConfirmedDeleteAttachment}>{strings.ListItemAttachmentsdialogOKbuttonLabelOnDelete}</PrimaryButton>) : null } { this.state.deleteAttachment ? (<DefaultButton disabled={this.state.disableButton} onClick={this._closeDialog}>{strings.ListItemAttachmentsdialogCancelButtonLabel}</DefaultButton>) : <PrimaryButton onClick={this._closeDialog}>{strings.ListItemAttachmentsdialogOKbuttonLabel}</PrimaryButton> } </DialogFooter> </Dialog> } </div> ); } }
the_stack
import type { NumericArray, TypedArray } from "./typedarray.js"; export interface INDBase<BUF extends any[] | TypedArray = any[]> { size: NumericArray; stride: NumericArray; offset: number; data: BUF; readonly dim: number; order(): number[]; } /** * Semi-typechecked interface for cases accepting 1D-4D grids, i.e. * {@link IGrid1D} - {@link IGrid4D}. */ export interface IGridND<BUF extends any[] | TypedArray = any[], T = any> extends INDBase<BUF> { /** * Returns true if given position is valid (i.e. within grid bounds). * * @param pos - */ includes( ...pos: | [number] | [number, number] | [number, number, number] | [number, number, number, number] ): boolean; /** * Returns index for given position. Returns negative value if outside the * grid's defined region. * * @param pos - */ indexAt( ...pos: | [number] | [number, number] | [number, number, number] | [number, number, number, number] ): number; /** * Non-boundschecked version of {@link IGridND.indexAt}. Assumes given * position is valid. * * @param pos - */ indexAtUnsafe( ...pos: | [number] | [number, number] | [number, number, number] | [number, number, number, number] ): number; /** * Returns value at given position. If outside the grid's defined region, * returns a suitable zero value. * * @param pos - */ getAt( ...pos: | [number] | [number, number] | [number, number, number] | [number, number, number, number] ): T; /** * Non-boundschecked version of {@link IGridND.getAt}. Assumes given * position is valid. * * @param pos - */ getAtUnsafe( ...pos: | [number] | [number, number] | [number, number, number] | [number, number, number, number] ): T; /** * Writes value at given position. Has no effect if outside of the defined * region. Returns true, if succeeded. * * @param args - */ setAt( ...args: | [number, T] | [number, number, T] | [number, number, number, T] | [number, number, number, number, T] ): boolean; /** * Non-boundschecked version of {@link IGridND.setAt}. Assumes given * position is valid. Returns true, if succeeded. * * @param args - */ setAtUnsafe( ...args: | [number, T] | [number, number, T] | [number, number, number, T] | [number, number, number, number, T] ): boolean; } /** * Gridlike container for 1D accessible data. * * @remarks * See {@link IGrid1DMixin} for mixin implementation. */ export interface IGrid1D<BUF extends any[] | TypedArray = any[], T = any> extends INDBase<BUF> { readonly dim: 1; /** * Returns true if given position is valid (i.e. within grid bounds). * * @param d0 - */ includes(d0: number): boolean; /** * Returns index for given position. Returns negative value if outside the * grid's defined region. * * @param d0 - */ indexAt(d0: number): number; /** * Non-boundschecked version of {@link IGrid1D.indexAt}. Assumes given * position is valid. * * @param d0 - */ indexAtUnsafe(d0: number): number; /** * Returns value at given position. If outside the grid's defined region, * returns a suitable zero value. * * @param d0 - */ getAt(d0: number): T; /** * Non-boundschecked version of {@link IGrid1D.getAt}. Assumes given * position is valid. * * @param d0 - */ getAtUnsafe(d0: number): T; /** * Writes value at given position. Has no effect if outside of the defined * region. Returns true, if succeeded. * * @param d0 - * @param value - */ setAt(d0: number, value: T): boolean; /** * Non-boundschecked version of {@link IGrid1D.setAt}. Assumes given * position is valid. Returns true, if succeeded. * * @param d0 - * @param value - */ setAtUnsafe(d0: number, value: T): boolean; } /** * Gridlike container for 2D accessible data. * * @remarks * See {@link IGrid2DMixin} for mixin implementation. */ export interface IGrid2D<BUF extends any[] | TypedArray = any[], T = any> extends INDBase<BUF> { readonly dim: 2; /** * Returns true if given position is valid (i.e. within grid bounds). * * @param d0 - * @param d1 - */ includes(d0: number, d1: number): boolean; /** * Returns index for given position (stated in same order as * {@link IGrid2D.size} and {@link IGrid2D.stride}). Returns negative value * if outside the grid's defined region. * * @param d0 - * @param d1 - */ indexAt(d0: number, d1: number): number; /** * Non-boundschecked version of {@link IGrid2D.indexAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - */ indexAtUnsafe(d0: number, d1: number): number; /** * Returns value at given position (given in same order as * {@link IGrid2D.size} and {@link IGrid2D.stride}). If outside the grid's * defined region, returns a suitable zero value. * * @param d0 - * @param d1 - */ getAt(d0: number, d1: number): T; /** * Non-boundschecked version of {@link IGrid2D.getAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - */ getAtUnsafe(d0: number, d1: number): T; /** * Writes value at given position (given in same order as * {@link IGrid2D.size} and {@link IGrid2D.stride}). Has no effect if * outside of the defined region. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param value - */ setAt(d0: number, d1: number, value: T): boolean; /** * Non-boundschecked version of {@link IGrid2D.setAt}. Assumes given * position is valid. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param value - */ setAtUnsafe(d0: number, d1: number, value: T): boolean; } /** * Gridlike container for 3D accessible data. * * @remarks * See {@link IGrid3DMixin} for mixin implementation. */ export interface IGrid3D<BUF extends any[] | TypedArray = any[], T = any> extends INDBase<BUF> { readonly dim: 3; /** * Returns true if given position is valid (i.e. within grid bounds). * * @param d0 - * @param d1 - * @param d2 - */ includes(d0: number, d1: number, d2: number): boolean; /** * Returns index for given position (stated in same order as * {@link IGrid3D.size} and {@link IGrid3D.stride}). Returns negative value * if outside the grid's defined region. * * @param d0 - * @param d1 - * @param d2 - */ indexAt(d0: number, d1: number, d2: number): number; /** * Non-boundschecked version of {@link IGrid3D.indexAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - * @param d2 - */ indexAtUnsafe(d0: number, d1: number, d2: number): number; /** * Returns value at given position (given in same order as * {@link IGrid3D.size} and {@link IGrid3D.stride}). If outside the grid's * defined region, returns a suitable zero value. * * @param d0 - * @param d1 - * @param d2 - */ getAt(d0: number, d1: number, d2: number): T; /** * Non-boundschecked version of {@link IGrid3D.getAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - * @param d2 - */ getAtUnsafe(d0: number, d1: number, d2: number): T; /** * Writes value at given position (given in same order as * {@link IGrid3D.size} and {@link IGrid3D.stride}). Has no effect if * outside of the defined region. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param d2 - * @param value - */ setAt(d0: number, d1: number, d2: number, value: T): boolean; /** * Non-boundschecked version of {@link IGrid3D.setAt}. Assumes given * position is valid. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param d2 - * @param value - */ setAtUnsafe(d0: number, d1: number, d2: number, value: T): boolean; } /** * Gridlike container for 4D accessible data. * * @remarks * See {@link IGrid4DMixin} for mixin implementation. */ export interface IGrid4D<BUF extends any[] | TypedArray = any[], T = any> extends INDBase<BUF> { readonly dim: 4; /** * Returns true if given position is valid (i.e. within grid bounds). * * @param d0 - * @param d1 - * @param d2 - * @param d3 - */ includes(d0: number, d1: number, d2: number, d3: number): boolean; /** * Returns index for given position (stated in same order as * {@link IGrid4D.size} and {@link IGrid4D.stride}). Returns negative value * if outside the grid's defined region. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - */ indexAt(d0: number, d1: number, d2: number, d3: number): number; /** * Non-boundschecked version of {@link IGrid4D.indexAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - */ indexAtUnsafe(d0: number, d1: number, d2: number, d3: number): number; /** * Returns value at given position (given in same order as * {@link IGrid4D.size} and {@link IGrid4D.stride}). If outside the grid's * defined region, returns a suitable zero value. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - */ getAt(d0: number, d1: number, d2: number, d3: number): T; /** * Non-boundschecked version of {@link IGrid4D.getAt}. Assumes given * position is valid. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - */ getAtUnsafe(d0: number, d1: number, d2: number, d3: number): T; /** * Writes value at given position (given in same order as * {@link IGrid4D.size} and {@link IGrid4D.stride}). Has no effect if * outside of the defined region. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - * @param value - */ setAt(d0: number, d1: number, d2: number, d3: number, value: T): boolean; /** * Non-boundschecked version of {@link IGrid4D.setAt}. Assumes given * position is valid. Returns true, if succeeded. * * @param d0 - * @param d1 - * @param d2 - * @param d3 - * @param value - */ setAtUnsafe( d0: number, d1: number, d2: number, d3: number, value: T ): boolean; }
the_stack
'use strict'; import { window, ExtensionContext, Uri, ViewColumn, WebviewPanel, commands, workspace, ConfigurationTarget, extensions, TextDocument, Webview, WorkspaceFolder } from 'vscode'; import { PddlConfiguration, PDDL_PLANNER } from '../configuration/configuration'; import * as path from 'path'; import { showError } from '../utils'; import { ValDownloader } from '../validation/ValDownloader'; import { VAL_DOWNLOAD_COMMAND, ValDownloadOptions } from '../validation/valCommand'; import { PTEST_VIEW } from '../ptest/PTestCommands'; import { instrumentOperationAsVsCodeCommand } from "vscode-extension-telemetry-wrapper"; import { DEF_PLANNER_OUTPUT_TARGET, EXECUTION_TARGET, PlannersConfiguration, ScopedPlannerConfiguration } from '../configuration/PlannersConfiguration'; import { exists } from '../util/workspaceFs'; import { asWebviewUri, getWebViewHtml } from '../webviewUtils'; export const SHOULD_SHOW_OVERVIEW_PAGE = 'shouldShowOverviewPage'; export const LAST_SHOWN_OVERVIEW_PAGE = 'lastShownOverviewPage'; const LATER = 'LATER'; const NEVER = 'NEVER'; const ACCEPTED = 'ACCEPTED'; export class OverviewPage { private webViewPanel?: WebviewPanel; private iconsInstalled = false; private workspaceFolder: WorkspaceFolder | undefined; private readonly ICONS_EXTENSION_NAME = "vscode-icons-team.vscode-icons"; NEXT_TIP_TO_SHOW = 'nextTipToShow'; ACCEPTED_TO_WRITE_A_REVIEW = 'acceptedToWriteAReview'; constructor(private context: ExtensionContext, private pddlConfiguration: PddlConfiguration, private plannersConfiguration: PlannersConfiguration, private val: ValDownloader) { instrumentOperationAsVsCodeCommand("pddl.showOverview", () => this.showWelcomePage(true)); workspace.onDidChangeConfiguration(() => this.scheduleUpdatePageConfiguration(), undefined, this.context.subscriptions); workspace.onDidChangeWorkspaceFolders(() => this.scheduleUpdatePageConfiguration(), undefined, this.context.subscriptions); extensions.onDidChange(() => this.updateIconsAlerts(), this.context.subscriptions); this.updateIconsAlerts(); } async showWelcomePage(showAnyway: boolean): Promise<void> { if (this.webViewPanel) { this.webViewPanel.reveal(); } else { if (showAnyway || this.beenAWhile()) { this.createWelcomePage(false); } } } beenAWhile(): boolean { const lastTimeShown = this.context.globalState.get<string>(LAST_SHOWN_OVERVIEW_PAGE, new Date(2000, 0, 1).toString()); const hoursSinceLastShow = (Date.now() - Date.parse(lastTimeShown)) / 1000 / 60 / 60; return hoursSinceLastShow > 24; } async createWelcomePage(showOnTop: boolean): Promise<void> { const iconUri = this.context.asAbsolutePath('images/icon.png'); const webViewPanel = window.createWebviewPanel( "pddl.Welcome", "PDDL Overview", { viewColumn: ViewColumn.Active, preserveFocus: !showOnTop }, { retainContextWhenHidden: true, enableFindWidget: true, enableCommandUris: true, enableScripts: true, localResourceRoots: [ Uri.file(this.context.asAbsolutePath(this.VIEWS)), Uri.file(this.context.asAbsolutePath("images")) ] } ); const html = await this.getHtml(webViewPanel.webview); webViewPanel.webview.html = html; webViewPanel.iconPath = Uri.file(iconUri); webViewPanel.onDidDispose(() => this.webViewPanel = undefined, undefined, this.context.subscriptions); webViewPanel.webview.onDidReceiveMessage(message => this.handleMessage(message), undefined, this.context.subscriptions); webViewPanel.onDidChangeViewState(() => this.scheduleUpdatePageConfiguration()); this.webViewPanel = webViewPanel; this.context.subscriptions.push(this.webViewPanel); // record the last date the page was shown on top this.context.globalState.update(LAST_SHOWN_OVERVIEW_PAGE, new Date(Date.now())); } // eslint-disable-next-line @typescript-eslint/no-explicit-any async handleMessage(message: any): Promise<void> { console.log(`Message received from the webview: ${message.command}`); switch (message.command) { case 'onload': this.scheduleUpdatePageConfiguration(); this.showNextHint(); break; case 'shouldShowOverview': this.context.globalState.update(SHOULD_SHOW_OVERVIEW_PAGE, message.value); break; case 'tryHelloWorld': this.helloWorld().catch(showError); break; case 'openNunjucksSample': this.openNunjucksSample().catch(showError); break; case 'clonePddlSamples': commands.executeCommand("git.clone", "https://github.com/jan-dolejsi/vscode-pddl-samples.git"); break; case 'selectPlanner': this.plannersConfiguration.setSelectedPlanner(message.value as ScopedPlannerConfiguration, this.workspaceFolder).catch(showError); break; case 'deletePlanner': commands.executeCommand('pddl.deletePlanner', message.value as ScopedPlannerConfiguration); break; case 'configurePlanner': commands.executeCommand('pddl.configurePlanner', message.value as ScopedPlannerConfiguration); break; case 'showConfiguration': commands.executeCommand('pddl.showPlannerConfiguration', message.value as ScopedPlannerConfiguration); break; case 'plannerOutputTarget': this.pddlConfiguration.updateEffectiveConfiguration("pddlPlanner", "executionTarget", message.value as string); break; case 'workspaceFolderSelected': const workspaceFolderUriAsString = message.workspaceFolderUri as string; this.workspaceFolder = workspace.getWorkspaceFolder(Uri.parse(workspaceFolderUriAsString)); this.scheduleUpdatePageConfiguration(); break; case 'installIcons': try { await commands.executeCommand("workbench.extensions.installExtension", this.ICONS_EXTENSION_NAME); } catch (err) { window.showErrorMessage("Could not install the VS Code Icons extension: " + err); } break; case 'enableIcons': await workspace.getConfiguration().update("workbench.iconTheme", "vscode-icons", ConfigurationTarget.Global); break; case 'downloadVal': const options: ValDownloadOptions = { bypassConsent: message.informedDecision }; await commands.executeCommand(VAL_DOWNLOAD_COMMAND, options); break; case 'enableFormatOnType': this.pddlConfiguration.setEditorFormatOnType(true, { forPddlOnly: message.forPddlOnly as boolean}); break; case 'hintOk': this.hintAcknowledged(); break; case 'hintLater': this.hintHide(); break; case 'hintNext': this.hintShowNext(); break; case 'feedbackAccepted': this.feedbackAccepted(); break; case 'feedbackLater': this.feedbackAskLater(); break; case 'feedbackNever': this.feedbackAskNever(); break; default: if (message.command?.startsWith('command:')) { const command = message.command as string; await commands.executeCommand(command.substr('command:'.length)); } else { console.warn('Unexpected command: ' + message.command); } } } readonly VIEWS = "views"; readonly CONTENT_FOLDER = path.join(this.VIEWS, "overview"); readonly COMMON_FOLDER = path.join(this.VIEWS, "common"); private tipDisplayed = 0; async showNextHint(): Promise<void> { const tipsUri = Uri.joinPath(this.context.extensionUri, 'tips.html'); const tips: string[] = (await workspace.fs.readFile(tipsUri)).toString().split("\n"); let nextTipToShow = this.context.globalState.get(this.NEXT_TIP_TO_SHOW, 0); for (let index = nextTipToShow; index < tips.length; index++) { const tip = tips[index]; // skip tips that were removed subsequently as obsolete if (tip.trim() === "") { nextTipToShow++; continue; } this.tipDisplayed = nextTipToShow; this.showTip(tip); return; } if (nextTipToShow === tips.length) { this.showTip(undefined); this.askForReview(); } this.context.globalState.update(this.NEXT_TIP_TO_SHOW, nextTipToShow); } showTip(tip: string | undefined): void { this.webViewPanel?.webview.postMessage({ command: 'showHint', hint: tip }); } hintShowNext(): void { this.context.globalState.update(this.NEXT_TIP_TO_SHOW, this.tipDisplayed+1); this.showNextHint(); } hintHide(): void { this.showTip(undefined); } hintAcknowledged(): void { this.context.globalState.update(this.NEXT_TIP_TO_SHOW, this.tipDisplayed + 1); this.showTip(undefined); } async askForReview(): Promise<void> { // what was the user response last time? const accepted = this.context.globalState.get(this.ACCEPTED_TO_WRITE_A_REVIEW, LATER); if (accepted === LATER) { this.showFeedbackRequest(true); } } feedbackAccepted(): void { const reviewPage = 'https://marketplace.visualstudio.com/items?itemName=jan-dolejsi.pddl#review-details'; commands.executeCommand('vscode.open', Uri.parse(reviewPage)); this.context.globalState.update(this.ACCEPTED_TO_WRITE_A_REVIEW, ACCEPTED); this.showFeedbackRequest(false); } feedbackAskNever(): void { this.context.globalState.update(this.ACCEPTED_TO_WRITE_A_REVIEW, NEVER); this.showFeedbackRequest(false); } feedbackAskLater(): void { this.context.globalState.update(this.ACCEPTED_TO_WRITE_A_REVIEW, LATER); this.showFeedbackRequest(false); } showFeedbackRequest(shouldShow: boolean): void { this.webViewPanel?.webview.postMessage({ command: 'showFeedbackRequest', visible: shouldShow }); } async helloWorld(): Promise<void> { const sampleDocuments = await this.createSample('helloWorld', 'Hello World!'); if (!sampleDocuments) { return; } // canceled const documentsToOpen = await this.openSampleFiles(sampleDocuments, ['domain.pddl', 'problem.pddl']); const workingDirectory = path.dirname(documentsToOpen[0].fileName); commands.executeCommand("pddl.planAndDisplayResult", documentsToOpen[0].uri, documentsToOpen[1].uri, workingDirectory, ""); } async openNunjucksSample(): Promise<void> { const sampleDocuments = await this.createSample('nunjucks', 'Nunjucks template sample'); if (!sampleDocuments) { return; } // canceled // let documentsToOpen = await this.openSampleFiles(sampleDocuments, ['domain.pddl', 'problem.pddl', 'problem0.json']); const ptestJsonName = '.ptest.json'; const ptestJson = sampleDocuments.find(doc => path.basename(doc.fileName) === ptestJsonName); if (!ptestJson) { throw new Error("Could not find " + ptestJsonName); } const generatedProblemUri = ptestJson.uri.with({ fragment: '0' }); await commands.executeCommand(PTEST_VIEW, generatedProblemUri); // let workingDirectory = path.dirname(documentsToOpen[0].fileName); // commands.executeCommand("pddl.planAndDisplayResult", documentsToOpen[0].uri, generatedProblemUri, workingDirectory, ""); } async openSampleFiles(sampleDocuments: TextDocument[], fileNamesToOpen: string[]): Promise<TextDocument[]> { const documentsToOpen = fileNamesToOpen .map(fileName => sampleDocuments.find(doc => path.basename(doc.fileName) === fileName)); // were all files found? if (documentsToOpen.some(v => !v)) { throw new Error('One or more sample files were not found: ' + fileNamesToOpen); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const validDocumentsToOpen = documentsToOpen.map(v => v!); for (let index = 0; index < validDocumentsToOpen.length; index++) { const doc = sampleDocuments[index]; const viewColumn: ViewColumn = this.indexToViewColumn(index); await window.showTextDocument(doc, { viewColumn: viewColumn, preview: false }); } return validDocumentsToOpen; } indexToViewColumn(index: number): ViewColumn { switch (index) { case 0: return ViewColumn.One; case 1: return ViewColumn.Two; case 2: return ViewColumn.Three; case 3: return ViewColumn.Four; default: return ViewColumn.Five; } } async createSample(subDirectory: string, sampleName: string): Promise<TextDocument[] | undefined> { let folder: Uri | undefined; if (!workspace.workspaceFolders || workspace.workspaceFolders.length === 0) { const folders = await window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, openLabel: `Select folder for the '${sampleName}' sample...` }); if (folders) { folder = folders[0]; } } else if (workspace.workspaceFolders.length === 1) { folder = workspace.workspaceFolders[0].uri; } else { const selectedFolder = await window.showWorkspaceFolderPick({ placeHolder: `Select workspace folder for the '${sampleName}' sample...` }); folder = selectedFolder?.uri; } if (!folder) { return undefined; } const sampleFiles = await workspace.fs.readDirectory(Uri.joinPath(this.context.extensionUri, this.CONTENT_FOLDER, subDirectory)); const sampleFileNames = sampleFiles .map(child => child[0]); // pick up the file name const sampleDocuments: TextDocument[] = []; for (const sampleFile of sampleFileNames) { const shouldWrite = await this.overwriteIfExists(folder!, sampleFile); if (shouldWrite === undefined) { return undefined; } const sampleTargetPath = Uri.joinPath(folder!, sampleFile); if (shouldWrite) { const sampleResourcePath = Uri.joinPath(this.context.extensionUri, this.CONTENT_FOLDER, subDirectory, sampleFile); await workspace.fs.copy(sampleResourcePath, sampleTargetPath, { overwrite: true }); } const sampleDocument = await workspace.openTextDocument(sampleTargetPath); sampleDocuments.push(sampleDocument); } return sampleDocuments; } /** * Checks whether the file already exists and decides whether to overwrite it. * @param folder folder uri * @param sampleFile sample file to write * @returns undefined, if the user cancels. */ async overwriteIfExists(folder: Uri, sampleFile: string): Promise<boolean | undefined> { const sampleTargetPath = Uri.joinPath(folder, sampleFile); if (await exists(sampleTargetPath)) { const overwrite = "Overwrite"; const answer = await window.showWarningMessage(`File '${sampleFile}' already exists.`, { modal: true }, overwrite, "Skip"); if (answer === undefined) { // canceled by the user return undefined; } return answer === overwrite; } else { // it does not exist return true; } } async getHtml(webview: Webview): Promise<string> { return getWebViewHtml(this.context, { relativePath: this.CONTENT_FOLDER, htmlFileName: 'overview.html', allowUnsafeInlineScripts: true, // used mostly by the alerts fonts: [ Uri.file(path.join("..", "..", this.COMMON_FOLDER, "codicon.ttf")) ] }, webview); } updateIconsAlerts(): void { this.iconsInstalled = extensions.getExtension(this.ICONS_EXTENSION_NAME) !== undefined; this.scheduleUpdatePageConfiguration(); } updateTimeout: NodeJS.Timeout | undefined; scheduleUpdatePageConfiguration(options?: { immediate?: boolean }): void { if (options?.immediate) { this.updatePageConfiguration(); } else { if (this.updateTimeout) { this.updateTimeout.refresh(); } else { this.updateTimeout = setTimeout(() => { this.updatePageConfiguration().catch(showError); }, 500); } } } async updatePageConfiguration(): Promise<boolean> { if (this.updateTimeout) { clearTimeout(this.updateTimeout); this.updateTimeout = undefined; } if (!this.webViewPanel || !this.webViewPanel.active) { return false; } let planners: ScopedPlannerConfiguration[] | undefined; let plannersConfigError: string | undefined; this.workspaceFolder = this.workspaceFolder ?? (workspace.workspaceFolders && workspace.workspaceFolders[0]); try { planners = this.plannersConfiguration.getPlanners(this.workspaceFolder); } catch (err: unknown) { plannersConfigError = (err as Error).message ?? err; console.log(plannersConfigError); } const message: OverviewConfiguration = { command: 'updateConfiguration', workspaceFolders: workspace.workspaceFolders?.map(wf => this.toWireWorkspaceFolder(wf)) ?? [], selectedWorkspaceFolder: this.workspaceFolder && this.toWireWorkspaceFolder(this.workspaceFolder), planners: planners ?? [], selectedPlanner: this.plannersConfiguration.getSelectedPlanner(this.workspaceFolder)?.configuration.title, plannersConfigError: plannersConfigError, plannerOutputTarget: workspace.getConfiguration(PDDL_PLANNER, this.workspaceFolder).get<string>(EXECUTION_TARGET, DEF_PLANNER_OUTPUT_TARGET), parser: this.pddlConfiguration.getParserPath(this.workspaceFolder), validator: this.pddlConfiguration.getValidatorPath(this.workspaceFolder), imagesPath: asWebviewUri(Uri.file(this.context.asAbsolutePath('images')), this.webViewPanel.webview).toString(), shouldShow: this.context.globalState.get<boolean>(SHOULD_SHOW_OVERVIEW_PAGE, true), autoSave: workspace.getConfiguration("files", this.workspaceFolder).get<string>("autoSave", "off"), showInstallIconsAlert: !this.iconsInstalled, showEnableIconsAlert: this.iconsInstalled && workspace.getConfiguration().get<string>("workbench.iconTheme") !== "vscode-icons", downloadValAlert: !this.pddlConfiguration.getValidatorPath(this.workspaceFolder) || !(await this.val.isInstalled()), updateValAlert: await this.val.isNewValVersionAvailable(), showEnableFormatterAlert: !this.pddlConfiguration.getEditorFormatOnType() // todo: workbench.editor.revealIfOpen }; return this?.webViewPanel?.webview?.postMessage(message) ?? false; } private toWireWorkspaceFolder(workspaceFolder: WorkspaceFolder): WireWorkspaceFolder { return { name: workspaceFolder.name, uri: workspaceFolder.uri.toString() }; } } interface OverviewConfiguration { command: string; workspaceFolders: WireWorkspaceFolder[]; selectedWorkspaceFolder?: WireWorkspaceFolder; planners: ScopedPlannerConfiguration[]; selectedPlanner?: string; plannersConfigError?: string; plannerOutputTarget: string; parser?: string; validator?: string; imagesPath: string; shouldShow: boolean; autoSave: string; showInstallIconsAlert: boolean; showEnableIconsAlert: boolean; downloadValAlert: boolean; updateValAlert: boolean; showEnableFormatterAlert: boolean; } interface WireWorkspaceFolder { uri: string; name: string; }
the_stack
import { Aurelia, TaskQueue } from 'aurelia-framework'; import { inlineView, Controller, bindable, ShadowDOM, ViewSlot, ShadowSlot } from './aurelia-templating'; import 'aurelia-loader-webpack'; // the test in this file is done in integration testing style, // instead of unit testing style to the rest as it requires higher level of setup complexity // to ensure correctness at runtime describe('shadow-dom.integration.spec.js', () => { describe('default slot', () => { it('works in basic default slot scenario', async () => { const Template_App = `<template> <parent> <child repeat.for="i of itemCount" value.bind="i"></child> </parent> </template>`; const Template_Parent = '<template>This is parent<div><slot></slot></div></template>'; const Template_Child = '<template><span>${value}</span></template>'; @inlineView(Template_App) // @ts-ignore class App { itemCount = 10; } @inlineView(Template_Parent) // @ts-ignore class Parent {} @inlineView(Template_Child) // @ts-ignore class Child { // @ts-ignore @bindable() value } const { aurelia, host, root, rootVm, } = await createFixture(App, [Parent, Child]); expect(host.querySelectorAll('parent child').length).toBe(10); expect(host.querySelectorAll('parent div child').length).toBe(10); expect(host.textContent.trim()).toBe('This is parent0123456789'); expect(root.view.children.length).toBe(/* 1 child view slot created for <parent/> */1); const atParentViewSlot: ViewSlot = root.view.children[0]; expect(atParentViewSlot.children.length).toBe(/* 10 views for 10 repeated <child/> */10); const slot: ShadowSlot = atParentViewSlot.projectToSlots[ShadowDOM.defaultSlotKey]; expect(slot.children.length).toBe(/* anchor */1 + /* projection */10); expect(slot.children.every((projectedNode: Node, idx) => { return projectedNode.nodeType === (idx === 0 ? Node.COMMENT_NODE : Node.ELEMENT_NODE); })); // unrender all content of <parent/> rootVm.itemCount = 0; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('parent child').length).toBe(0); expect(host.querySelectorAll('parent div child').length).toBe(0); expect(host.textContent.trim()).toBe('This is parent'); // assertion for issue https://github.com/aurelia/templating-resources/issues/392 // thanks to Thomas Darling https://github.com/thomas-darling expect(slot.children.length).toBe(/* anchor */1 + /* projection */0); root.detached(); root.unbind(); }); // in this test, we test 4 varition of default slot usages + default fallback content // also ensure that when value is changed dynamically (repeat collection empty/if value turned to false) // it will trigger the rendering/un-rendering correctly // 1. with repeat // 2. with if // 3. with empty space (should render default) // 4. nothing (should render default content) it('works in slot with fallback content scenario', async () => { const Template_App = `<template> <parent id="parent1"> <child repeat.for="i of itemCount" value.bind="i"></child> </parent> <parent id="parent2"><child if.bind="showChild2" value.bind="showChild2"></child></parent> <parent id="parent3"> </parent> <parent id="parent4"></parent> </template>`; const Template_Parent = '<template>This is parent<div><slot>Empty parent content</slot></div></template>'; const Template_Child = '<template><span>${value}</span></template>'; @inlineView(Template_App) // @ts-ignore class App { itemCount = 10; showChild2 = false; } @inlineView(Template_Parent) // @ts-ignore class Parent {} @inlineView(Template_Child) // @ts-ignore class Child { // @ts-ignore @bindable() value } const { aurelia, host, root, rootVm, } = await createFixture(App, [Parent, Child]); expect(root.view.children.length).toBe(/* 2 child views slot created for (4) <parent/>, last 2 do not have content */2, 'root view should have had 2 child viewslots'); const [atParent1ViewSlot, atParent2ViewSlot] = root.view.children as ViewSlot[]; const [parent1, parent2, parent3, parent4] = host.querySelectorAll<HTMLElement>('parent'); // #parent3 and #parent4 are considered equal // content comprising of all empty space nodes === no content expect(parent3.textContent.trim()).toBe('This is parentEmpty parent content'); expect(parent4.textContent.trim()).toBe('This is parentEmpty parent content'); // assert usage with content expect(host.querySelectorAll('#parent1 child').length).toBe(10); expect(host.querySelectorAll('#parent1 div child').length).toBe(10); expect(parent1.textContent.trim()).toBe('This is parent0123456789'); expect(atParent1ViewSlot.children.length).toBe(/* 10 views for 10 repeated <child/> */10); const parent1Default_ShadowSlot: ShadowSlot = atParent1ViewSlot.projectToSlots[ShadowDOM.defaultSlotKey]; expect(parent1Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection */10); expect(parent1Default_ShadowSlot.children.every((projectedNode: Node, idx) => { return projectedNode.nodeType === (idx === 0 ? Node.COMMENT_NODE : Node.ELEMENT_NODE); })); // unrender all content of #parent1 rootVm.itemCount = 0; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('#parent1 child').length).toBe(0); expect(host.querySelectorAll('#parent1 div child').length).toBe(0); expect(parent1.textContent.trim()).toBe('This is parentEmpty parent content', 'it should have had default fallback when setting itemCount to 0 (#parent1)'); // assertion for issue https://github.com/aurelia/templating-resources/issues/392 // thanks to Thomas Darling https://github.com/thomas-darling expect(parent1Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection */0); // rerender content of #parent1 rootVm.itemCount = 10; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('#parent1 child').length).toBe(10); expect(host.querySelectorAll('#parent1 div child').length).toBe(10); expect(parent1.textContent.trim()).toBe('This is parent0123456789'); expect(atParent1ViewSlot.children.length).toBe(/* 10 views for 10 repeated <child/> */10); expect(parent1Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection */10); expect(parent1Default_ShadowSlot.children.every((projectedNode: Node, idx) => { return projectedNode.nodeType === (idx === 0 ? Node.COMMENT_NODE : Node.ELEMENT_NODE); })); // =================================================================================== // assert usage WITHOUT content expect(host.querySelectorAll('#parent2 child').length).toBe(0); expect(parent2.textContent.trim()).toBe('This is parentEmpty parent content'); expect(atParent2ViewSlot.children.length).toBe(/* 10 views for 10 repeated <child/> */0); const parent2Default_ShadowSlot: ShadowSlot = atParent2ViewSlot.projectToSlots[ShadowDOM.defaultSlotKey]; expect(parent2Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection */0); expect(parent2Default_ShadowSlot.children.every((projectedNode: Node, idx) => { return projectedNode.nodeType === (idx === 0 ? Node.COMMENT_NODE : Node.ELEMENT_NODE); })); // unrender #parent2 <child/> rootVm.showChild2 = true; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('#parent2 child').length).toBe(1); expect(host.querySelectorAll('#parent2 div child').length).toBe(1); expect(parent2.textContent.trim()).toBe('This is parenttrue'); expect(parent2Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection node */1); // unrender #parent2 child rootVm.showChild2 = false; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('#parent2 child').length).toBe(0); expect(host.querySelectorAll('#parent2 div child').length).toBe(0); expect(parent2.textContent.trim()).toBe('This is parentEmpty parent content'); expect(parent2Default_ShadowSlot.children.length).toBe(/* anchor */1 + /* projection node */0); root.detached(); root.unbind(); }); }); describe('named slot', () => { it('works in basic named slot scenario', async () => { const Template_App = `<template> <parent> <child repeat.for="i of itemCount" value.bind="i" slot="child-value-display"></child> </parent> </template>`; const Template_Parent = '<template>This is parent<div><slot name="child-value-display"></slot></div></template>'; const Template_Child = '<template><span>${value}</span></template>'; @inlineView(Template_App) // @ts-ignore class App { itemCount = 10; } @inlineView(Template_Parent) // @ts-ignore class Parent {} @inlineView(Template_Child) // @ts-ignore class Child { // @ts-ignore @bindable() value } const { aurelia, host, root, rootVm, } = await createFixture(App, [Parent, Child]); expect(host.querySelectorAll('parent child').length).toBe(10); expect(host.querySelectorAll('parent div child').length).toBe(10); expect(host.textContent.trim()).toBe('This is parent0123456789'); expect(root.view.children.length).toBe(/* 1 child view slot created for <parent/> */1); const atParentViewSlot: ViewSlot = root.view.children[0]; expect(atParentViewSlot.children.length).toBe(/* 10 views for 10 repeated <child/> */10); const slot: ShadowSlot = atParentViewSlot.projectToSlots['child-value-display']; expect(slot.children.length).toBe(/* anchor */1 + /* projection */10); expect(slot.children.every((projectedNode: Node, idx) => { return projectedNode.nodeType === (idx === 0 ? Node.COMMENT_NODE : Node.ELEMENT_NODE); })); // unrender all content of <parent/> rootVm.itemCount = 0; await new Promise(r => aurelia.container.get(TaskQueue).queueMicroTask(r)); expect(host.querySelectorAll('parent child').length).toBe(0); expect(host.querySelectorAll('parent div child').length).toBe(0); expect(host.textContent.trim()).toBe('This is parent'); // assertion for issue https://github.com/aurelia/templating-resources/issues/392 // thanks to Thomas Darling https://github.com/thomas-darling expect(slot.children.length).toBe(/* anchor */1 + /* projection */0); root.detached(); root.unbind(); }); }); async function createFixture<T>(root: Constructable<T>, resources: any[] = []) { const aurelia = new Aurelia(); aurelia .use .defaultBindingLanguage() .defaultResources() .globalResources(resources) const host = document.createElement('div'); await aurelia.start(); await aurelia.setRoot(root, host); const rootController = aurelia['root'] as Controller; return { aurelia, host, root: rootController, rootVm: rootController.viewModel as T } } interface Constructable<T> { new(...args: any[]): T; } });
the_stack
import * as t from '@babel/types'; import { Binding } from './bindings'; import getFirstUnsafeLocation from './getFirstUnsafeLocation'; import { NodePath, Scope } from '@babel/traverse'; import * as Babel from '@babel/core'; import { replaceWithAndPreserveComments } from '@resugar/helper-comments'; export interface Options { onWarn?: (node: t.Node, code: string, message: string) => void; forceDefaultExport?: boolean; safeFunctionIdentifiers?: Array<string>; } export default function (): Babel.PluginItem { return ( { name: '@resugar/codemod-modules-commonjs', visitor: { Program(path: NodePath<t.Program>, state?: { opts?: Options }): void { unwrapIIFE(path); removeUseStrictDirective(path); rewriteImportsAndExports( path, state && state.opts ? state.opts.safeFunctionIdentifiers : undefined, (state && state.opts && state.opts.forceDefaultExport) || false ); }, ReferencedIdentifier( path: NodePath<t.Identifier>, state?: { opts?: Options } ): void { // TODO: Warn about `require`, `module`, and `exports` global references. let { node } = path; let onWarn = (state && state.opts && state.opts.onWarn) || (() => {}); if (node.name === 'require' && !path.scope.hasBinding('require')) { let source = extractRequirePathNode(path.parent); if (source) { onWarn( path.parent, 'unsupported-import', `Unsupported 'require' call cannot be transformed into an import` ); } } else if (node.name === 'exports') { onWarn( node, 'unsupported-export', `Unsupported export cannot be turned into an 'export' statement` ); } }, }, } as Babel.PluginItem ); } /** * Unwrap an IIFE at program scope if that's the only thing that's there. * * (function() { * // All program body here. * })(); */ function unwrapIIFE(path: NodePath<t.Program>) { let { node } = path; let iife = extractModuleIIFE(node); if (!iife) { return; } node.body = iife.body.body; } /** * Remove a 'use strict' directive in `path`'s body. */ function removeUseStrictDirective( path: NodePath<t.Program> | NodePath<t.BlockStatement> ) { let directives = path.node.directives; for (let i = 0; i < directives.length; i++) { let directive = directives[i]; if (directive.value.value === 'use strict') { directives.splice(i, 1); i--; } } } /** * Re-write requires as imports/exports and exports sets as export statements. */ function rewriteImportsAndExports( path: NodePath<t.Program>, safeFunctionIdentifiers: Array<string> = [], forceDefaultExport: boolean ) { const body = path.get('body'); if (!Array.isArray(body)) { throw new Error(`expected body paths from program node, got: ${body}`); } if (forceDefaultExport) { rewriteStatementsAsDefaultExport(path); } else { for (const statement of body) { rewriteAsExport(statement); } } const collectedDefaultImportNames: Array<string> = []; const firstUnsafeLocation = getFirstUnsafeLocation(path, [ 'require', ...safeFunctionIdentifiers, ]); for (const statement of body) { rewriteAsImport( statement, firstUnsafeLocation, collectedDefaultImportNames ); } removeDefaultAccesses(path, collectedDefaultImportNames); } /** * Rewrites the exports for a file, intentionally converting to a default export * with the same value as the previous module.exports. */ function rewriteStatementsAsDefaultExport(programPath: NodePath<t.Program>) { const exportPaths: Array<NodePath> = []; programPath.traverse({ 'MemberExpression|Identifier|ThisExpression'( path: | NodePath<t.MemberExpression> | NodePath<t.Identifier> | NodePath<t.ThisExpression> ): void { if (isExportsObject(path)) { exportPaths.push(path); path.skip(); } }, } as Babel.Visitor); if (exportPaths.length === 0) { return; } // Turn a unique `module.exports` line into a single `export default` statement. if (exportPaths.length === 1) { const exportPath = exportPaths[0]; const enclosingStatement = getEnclosingStatement(exportPath); if ( enclosingStatement.isExpressionStatement() && t.isAssignmentExpression(enclosingStatement.node.expression) && enclosingStatement.node.expression.left === exportPath.node ) { rewriteAssignmentToDefaultExport(enclosingStatement); return; } } const exportsIdentifier = generateUidIdentifier( programPath.scope, 'defaultExport' ); const firstStatement = getEnclosingStatement(exportPaths[0]); const lastStatement = getEnclosingStatement( exportPaths[exportPaths.length - 1] ); lastStatement.scope.registerDeclaration( firstStatement.insertBefore( t.variableDeclaration('var', [ t.variableDeclarator(exportsIdentifier, t.objectExpression([])), ]) )[0] ); for (const exportPath of exportPaths) { replaceWithAndPreserveComments(exportPath, exportsIdentifier); } lastStatement.insertAfter(t.exportDefaultDeclaration(exportsIdentifier)); } function getEnclosingStatement(path: NodePath): NodePath<t.Statement> { let resultPath = path; while (!t.isProgram(resultPath.parentPath.node)) { resultPath = resultPath.parentPath; } return resultPath as NodePath<t.Statement>; } function rewriteAsExport(path: NodePath): void { if (!path.isExpressionStatement()) { return; } const expression = path.get('expression'); if (!expression.isAssignmentExpression()) { return; } const left = expression.get('left'); const right = expression.get('right'); if (isExportsObject(left)) { rewriteSingleExportAsDefaultExport(path); } else if (left.isMemberExpression() && !left.node.computed) { if (!isExportsObject(left.get('object'))) { return; } if (right.isFunctionExpression()) { rewriteNamedFunctionExpressionExport(path); } else if (t.isIdentifier(right)) { rewriteNamedIdentifierExport(path); } else { rewriteNamedValueExport(path); } } } function isExportsObject(path: NodePath): boolean { const { node } = path; if (t.isMemberExpression(node)) { return ( !path.scope.hasBinding('module') && t.isIdentifier(node.object, { name: 'module' }) && t.isIdentifier(node.property, { name: 'exports' }) ); } else if (t.isIdentifier(node, { name: 'exports' })) { return !path.scope.hasBinding('exports'); } else { return isTopLevelThis(path); } } function isTopLevelThis(path: NodePath): boolean { if (!path.isThisExpression()) { return false; } let ancestor: NodePath = path; while (!t.isProgram(ancestor.node)) { if ( t.isFunction(ancestor.node) && !t.isArrowFunctionExpression(ancestor.node) ) { return false; } ancestor = ancestor.parentPath; } return true; } function mapExportObject(node: t.Node): Array<t.ExportDeclaration> | undefined { if (!t.isObjectExpression(node)) { return undefined; } const result: Array<t.ExportDeclaration> = []; for (const property of node.properties) { // Don't allow object methods or spread elements, i.e. // // module.exports = { ...a, b() {} }; // if (!t.isObjectProperty(property)) { return undefined; } // Don't allow computed properties, i.e. // // module.exports = { [a]: b }; // if (property.computed || !t.isIdentifier(property.key)) { return undefined; } // Don't allow destructuring patterns. I'm not sure this can actually happen, // but the types make me rule it out. if (t.isPatternLike(property.value) && !t.isIdentifier(property.value)) { return undefined; } // Handle simple mappings of existing bindings, i.e. // // module.exports = { a: b, c }; // if (t.isIdentifier(property.value)) { const lastExportDeclaration = result[result.length - 1]; if ( lastExportDeclaration && t.isExportNamedDeclaration(lastExportDeclaration) ) { lastExportDeclaration.specifiers.push( t.exportSpecifier(property.value, property.key) ); } else { result.push( t.exportNamedDeclaration( null, [t.exportSpecifier(property.value, property.key)], null ) ); } continue; } // Handle re-exports, i.e. // // module.exports = { a: require('./foo') }; // if (t.isCallExpression(property.value)) { const source = extractRequirePathNode(property.value); if (!source) { return undefined; } result.push( t.exportNamedDeclaration( null, [t.exportSpecifier(t.identifier('default'), property.key)], source ) ); continue; } result.push( t.exportNamedDeclaration( t.variableDeclaration('let', [ t.variableDeclarator(property.key, property.value), ]), [] ) ); } return result; } function rewriteSingleExportAsDefaultExport( path: NodePath<t.ExpressionStatement> ): void { const expression = path.get('expression'); if (!expression.isAssignmentExpression()) { return; } const right = expression.get('right'); const objectExports = mapExportObject(right.node); if (objectExports) { replaceWithAndPreserveComments(path, objectExports); } else { let pathNode = extractRequirePathNode(right.node); if (pathNode) { replaceWithAndPreserveComments(path, t.exportAllDeclaration(pathNode)); } else { rewriteAssignmentToDefaultExport(path); } } } function rewriteAssignmentToDefaultExport( path: NodePath<t.ExpressionStatement> ): void { const expression = path.get('expression') as NodePath<t.AssignmentExpression>; const right = expression.node.right; replaceWithAndPreserveComments(path, t.exportDefaultDeclaration(right)); } function rewriteNamedFunctionExpressionExport( path: NodePath<t.ExpressionStatement> ): boolean { const expression = path.get('expression') as NodePath<t.AssignmentExpression>; const left = expression.get('left') as NodePath<t.MemberExpression>; const right = expression.get('right') as NodePath<t.FunctionExpression>; const exportName = (left.node.property as t.Identifier).name; const id = right.node.id; const fnBinding = id ? id.name : null; const localId = generateUidIdentifier(path.scope, fnBinding || exportName); const localName = localId.name; if (localName === exportName) { if (!id) { right.node.id = t.identifier(exportName); } replaceWithAndPreserveComments( path, t.exportNamedDeclaration( t.functionDeclaration( t.identifier(exportName), right.node.params, right.node.body, right.node.generator, right.node.async ), [], null ) ); } else { let declaration: t.Statement = t.functionDeclaration( localId, right.node.params, right.node.body, right.node.generator, right.node.async ); if (!id) { // no-op } else if (fnBinding === localName) { // no-op } else { declaration = t.variableDeclaration('let', [ t.variableDeclarator(localId, right.node), ]); } replaceWithAndPreserveComments(path, [ declaration, t.exportNamedDeclaration(null, [ t.exportSpecifier(localId, t.identifier(exportName)), ]), ]); } return true; } function rewriteNamedIdentifierExport( path: NodePath<t.ExpressionStatement> ): boolean { const expression = path.get('expression') as NodePath<t.AssignmentExpression>; const left = expression.get('left') as NodePath<t.MemberExpression>; const property = left.get('property') as NodePath<t.Identifier>; const right = expression.get('right') as NodePath<t.Identifier>; let replacements: Array<t.Statement>; if (path.scope.hasBinding(right.node.name)) { const localBinding = right.node; replacements = [ t.exportNamedDeclaration( null, [t.exportSpecifier(localBinding, property.node)], null ), ]; } else { const localBinding = generateUidIdentifier(path.scope, property.node.name); if (localBinding.name === property.node.name) { replacements = [ t.exportNamedDeclaration( t.variableDeclaration('let', [ t.variableDeclarator(localBinding, right.node), ]), [], null ), ]; } else { replacements = [ t.variableDeclaration('let', [ t.variableDeclarator(localBinding, right.node), ]), t.exportNamedDeclaration( null, [t.exportSpecifier(localBinding, property.node)], null ), ]; } } replaceWithAndPreserveComments(path, replacements); return true; } function rewriteNamedValueExport( path: NodePath<t.ExpressionStatement> ): boolean { const expression = path.get('expression') as NodePath<t.AssignmentExpression>; const left = expression.get('left') as NodePath<t.MemberExpression>; const property = left.get('property') as NodePath<t.Identifier>; const right = expression.get('right'); const localBinding = generateUidIdentifier(path.scope, property.node.name); if (localBinding.name === property.node.name) { replaceWithAndPreserveComments( path, t.exportNamedDeclaration( t.variableDeclaration('let', [ t.variableDeclarator(t.identifier(property.node.name), right.node), ]), [], null ) ); } else { let block = path.parent as t.BlockStatement; let nodeIndex = block.body.indexOf(path.node); if (nodeIndex < 0) { throw new Error( `could not locate ${path.node.type} at ${path.node.loc!.start.line}:${ path.node.loc!.start.column } in its parent block` ); } replaceWithAndPreserveComments(path, [ t.variableDeclaration('let', [ t.variableDeclarator(localBinding, right.node), ]), t.exportNamedDeclaration( null, [t.exportSpecifier(localBinding, t.identifier(property.node.name))], null ), ]); } return true; } /** * Rewrite this potential import statement, considering various import styles. * Any new default import names are added to collectedDefaultImportNames. */ function rewriteAsImport( path: NodePath, firstUnsafeLocation: number, collectedDefaultImportNames: Array<string> ): boolean { if (path.scope.hasBinding('require')) { return false; } if (path.node && path.node.end! > firstUnsafeLocation) { return false; } return ( rewriteSingleExportRequire(path, collectedDefaultImportNames) || rewriteNamedExportRequire(path) || rewriteDeconstructedImportRequire(path) || rewriteSideEffectRequire(path) ); } /** * Convert * let a = require('b'); * to * import a from 'b'; * * Any imported names are added to the collectedDefaultImportNames parameter. */ function rewriteSingleExportRequire( path: NodePath, collectedDefaultImportNames: Array<string> ): boolean { let { node } = path; if (!t.isVariableDeclaration(node)) { return false; } let { declarations } = node; let extractableDeclarations: Array<{ declaration: t.VariableDeclarator; id: t.Identifier; pathNode: t.StringLiteral; }> = []; declarations.forEach((declaration) => { let { id, init } = declaration; if (!t.isIdentifier(id) || !init) { return; } let pathNode = extractRequirePathNode(init); if (!pathNode) { return; } extractableDeclarations.push({ declaration, id, pathNode, }); }); if (declarations.length === 0) { return false; } if (declarations.length !== extractableDeclarations.length) { // TODO: We have to replace only part of it. return false; } replaceWithAndPreserveComments( path, extractableDeclarations.map(({ id, pathNode }) => t.importDeclaration([t.importDefaultSpecifier(id)], pathNode) ) ); collectedDefaultImportNames.push( ...extractableDeclarations.map((d) => d.id.name) ); return true; } /** * Convert * let a = require('b').c; * to * import { c as a } from 'b'; */ function rewriteNamedExportRequire(path: NodePath): boolean { let declaration = extractSingleDeclaration(path.node); if (!declaration) { return false; } let { id, init } = declaration; if ( !t.isIdentifier(id) || !init || !t.isMemberExpression(init) || init.computed ) { return false; } let pathNode = extractRequirePathNode(init.object); if (!pathNode) { return false; } replaceWithAndPreserveComments( path, t.importDeclaration([t.importSpecifier(id, init.property)], pathNode) ); return true; } /** * Convert * let { a } = require('b'); * to * import { a } from 'b'; */ function rewriteDeconstructedImportRequire(path: NodePath): boolean { let declaration = extractSingleDeclaration(path.node); if (!declaration) { return false; } let { id, init } = declaration; if (!t.isObjectPattern(id) || !init) { return false; } let bindings = []; for (let property of id.properties) { if (t.isRestElement(property)) { return false; } let { key, value } = property; if (!t.isIdentifier(value)) { return false; } bindings.push(new Binding(value.name, key.name)); } let pathNode = extractRequirePathNode(init); if (!pathNode) { return false; } replaceWithAndPreserveComments( path, t.importDeclaration( bindings.map((binding) => t.importSpecifier( t.identifier(binding.localName), t.identifier(binding.exportName) ) ), pathNode ) ); return true; } /** * Convert * require('a'); * to * import 'a'; */ function rewriteSideEffectRequire(path: NodePath): boolean { let { node } = path; if (!t.isExpressionStatement(node)) { return false; } let pathNode = extractRequirePathNode(node.expression); if (!pathNode) { return false; } replaceWithAndPreserveComments(path, t.importDeclaration([], pathNode)); return true; } /** * Remove `.default` accesses on names that are known to be default imports. * For example, if `let a = require('a');` became `import a from 'a';`, then * any usage of `a.default` should change to just `a`. * * Note that this isn't 100% correct, and being fully correct here is * undecidable, but it seems good enough for real-world cases. */ function removeDefaultAccesses( programPath: NodePath<t.Program>, defaultImportNames: ReadonlyArray<string> ) { programPath.traverse({ MemberExpression(path: NodePath<t.MemberExpression>): void { const { object, property, computed } = path.node; if ( !computed && t.isIdentifier(object) && defaultImportNames.indexOf(object.name) !== -1 && t.isIdentifier(property) && property.name === 'default' ) { path.replaceWith(object); } }, }); } function extractSingleDeclaration(node: t.Node): t.VariableDeclarator | null { if (!t.isVariableDeclaration(node)) { return null; } if (node.declarations.length !== 1) { return null; } return node.declarations[0]; } function extractRequirePathNode(node: t.Node): t.StringLiteral | null { if (!node || !t.isCallExpression(node)) { return null; } if (!t.isIdentifier(node.callee, { name: 'require' })) { return null; } if (node.arguments.length !== 1) { return null; } let arg = node.arguments[0]; if (!t.isStringLiteral(arg)) { return null; } return arg; } /** * @private */ function extractModuleIIFE(node: t.Node): t.FunctionExpression | null { if (!t.isProgram(node)) { return null; } if (node.body.length !== 1) { return null; } let [statement] = node.body; if (!t.isExpressionStatement(statement)) { return null; } let { expression: call } = statement; if (t.isUnaryExpression(call) && call.operator === 'void') { // e.g. `void function(){}();` call = call.argument; } if (!t.isCallExpression(call)) { return null; } let { callee, arguments: args } = call; let iife; if (t.isFunctionExpression(callee)) { // e.g. `(function() {})();` if (args.length !== 0) { return null; } iife = callee; } else if (t.isMemberExpression(callee)) { // e.g. `(function() {}).call(this);` let { object, property, computed } = callee; if (computed || !t.isFunctionExpression(object)) { return null; } if (!t.isIdentifier(property, { name: 'call' })) { return null; } if (args.length !== 1 || !t.isThisExpression(args[0])) { return null; } iife = object; } else { return null; } if (iife.id || iife.params.length > 0 || iife.generator) { return null; } return iife; } interface ScopeWithPrivate extends Scope { hasLabel(label: string): boolean; references: { [key: string]: boolean }; uids: { [key: string]: boolean }; } function generateUidIdentifier(scope: Scope, name: string): t.Identifier { return t.identifier(generateUid(scope, name)); } /** * Mimics the `@babel/traverse` implementation of `Scope#generateUid` but * without always prefixing with `_`, which makes it impossible for the return * value to match `name`. */ function generateUid(scope: Scope, name: string): string { const privateScope = scope as ScopeWithPrivate; for (const uid of uniquify(name)) { if ( privateScope.hasLabel(uid) || privateScope.hasBinding(uid) || privateScope.hasGlobal(uid) || privateScope.hasReference(uid) ) { continue; } const program = privateScope.getProgramParent() as ScopeWithPrivate; program.references[uid] = true; program.uids[uid] = true; return uid; } throw new Error(`could not find a unique name based on ${name}`); } function* uniquify(name: string): Iterable<string> { yield name; yield `_${name}`; let i = 1; while (true) { yield `${name}${i++}`; } }
the_stack
import { ExactPackage, PackageConfig, PackageTarget, ExportsTarget } from '../install/package.js'; import { JspmError } from '../common/err.js'; import { Log } from '../common/log.js'; // @ts-ignore import { fetch } from '#fetch'; import { importedFrom } from "../common/url.js"; // @ts-ignore import { parse } from 'es-module-lexer/js'; import { getProvider, defaultProviders, Provider } from '../providers/index.js'; import { Analysis, createSystemAnalysis, createCjsAnalysis, createEsmAnalysis, createTsAnalysis } from './analysis.js'; import { getMapMatch } from '@jspm/import-map'; import { Installer, PackageProvider } from '../install/installer.js'; let realpath, pathToFileURL; export class Resolver { log: Log; pcfgPromises: Record<string, Promise<void>> = Object.create(null); pcfgs: Record<string, PackageConfig | null> = Object.create(null); fetchOpts: any; preserveSymlinks = false; providers = defaultProviders; constructor (log: Log, fetchOpts?: any, preserveSymlinks = false) { this.log = log; this.fetchOpts = fetchOpts; this.preserveSymlinks = preserveSymlinks; } addCustomProvider (name: string, provider: Provider) { if (!provider.pkgToUrl) throw new Error('Custom provider "' + name + '" must define a "pkgToUrl" method.'); if (!provider.parseUrlPkg) throw new Error('Custom provider "' + name + '" must define a "parseUrlPkg" method.'); if (!provider.resolveLatestTarget) throw new Error('Custom provider "' + name + '" must define a "resolveLatestTarget" method.'); this.providers = Object.assign({}, this.providers, { [name]: provider }); } parseUrlPkg (url: string): { pkg: ExactPackage, source: { layer: string, provider: string } } | undefined { for (const provider of Object.keys(this.providers)) { const providerInstance = this.providers[provider]; const result = providerInstance.parseUrlPkg.call(this, url); if (result) return { pkg: 'pkg' in result ? result.pkg : result, source: { provider, layer: 'layer' in result ? result.layer : 'default' } }; } return null; } pkgToUrl (pkg: ExactPackage, { provider, layer }: PackageProvider): string { return getProvider(provider, this.providers).pkgToUrl.call(this, pkg, layer); } async getPackageBase (url: string) { const pkg = this.parseUrlPkg(url); if (pkg) return this.pkgToUrl(pkg.pkg, pkg.source); let testUrl: URL; try { testUrl = new URL('./', url); } catch { return url; } const rootUrl = new URL('/', testUrl).href; do { let responseUrl; if (responseUrl = await this.checkPjson(testUrl.href)) return new URL('.', responseUrl).href; // No package base -> use directory itself if (testUrl.href === rootUrl) return new URL('./', url).href; } while (testUrl = new URL('../', testUrl)); } // TODO split this into getPackageDependencyConfig and getPackageResolutionConfig // since "dependencies" come from package base, while "imports" come from local pjson async getPackageConfig (pkgUrl: string): Promise<PackageConfig | null> { if (!pkgUrl.startsWith('file:') && !pkgUrl.startsWith('http:') && !pkgUrl.startsWith('https:') && !pkgUrl.startsWith('ipfs:')) return null; if (!pkgUrl.endsWith('/')) throw new Error(`Internal Error: Package URL must end in "/". Got ${pkgUrl}`); let cached = this.pcfgs[pkgUrl]; if (cached) return cached; if (!this.pcfgPromises[pkgUrl]) this.pcfgPromises[pkgUrl] = (async () => { const parsed = this.parseUrlPkg(pkgUrl); if (parsed) { const pcfg = await getProvider(parsed.source.provider, this.providers).getPackageConfig?.call(this, pkgUrl); if (pcfg !== undefined) { this.pcfgs[pkgUrl] = pcfg; return; } } const res = await fetch(`${pkgUrl}package.json`, this.fetchOpts); switch (res.status) { case 200: case 304: break; case 401: case 403: case 404: case 406: this.pcfgs[pkgUrl] = null; return; default: throw new JspmError(`Invalid status code ${res.status} reading package config for ${pkgUrl}. ${res.statusText}`); } if (res.headers && !res.headers.get('Content-Type')?.match(/^application\/json(;|$)/)) { this.pcfgs[pkgUrl] = null; } else try { this.pcfgs[pkgUrl] = await res.json(); } catch (e) { this.pcfgs[pkgUrl] = null; } })(); await this.pcfgPromises[pkgUrl]; return this.pcfgs[pkgUrl]; } async getDepList (pkgUrl: string, dev = false): Promise<string[]> { const pjson = (await this.getPackageConfig(pkgUrl))!; if (!pjson) return []; return [...new Set([ Object.keys(pjson.dependencies || {}), Object.keys(dev && pjson.devDependencies || {}), Object.keys(pjson.peerDependencies || {}), Object.keys(pjson.optionalDependencies || {}), Object.keys(pjson.imports || {}) ].flat())]; } async checkPjson (url: string): Promise<string | false> { if (await this.getPackageConfig(url) === null) return false; return url; } async exists (resolvedUrl: string) { const res = await fetch(resolvedUrl, this.fetchOpts); switch (res.status) { case 200: case 304: return true; case 404: case 406: return false; default: throw new JspmError(`Invalid status code ${res.status} loading ${resolvedUrl}. ${res.statusText}`); } } async resolveLatestTarget (target: PackageTarget, unstable: boolean, { provider, layer }: PackageProvider, parentUrl?: string): Promise<ExactPackage> { // find the range to resolve latest let range: any; for (const possibleRange of target.ranges.sort(target.ranges[0].constructor.compare)) { if (!range) { range = possibleRange; } else if (possibleRange.gt(range) && !range.contains(possibleRange)) { range = possibleRange; } } const latestTarget = { registry: target.registry, name: target.name, range }; const pkg = await getProvider(provider, this.providers).resolveLatestTarget.call(this, latestTarget, unstable, layer, parentUrl); if (pkg) return pkg; throw new JspmError(`Unable to resolve package ${latestTarget.registry}:${latestTarget.name} to "${latestTarget.range}"${importedFrom(parentUrl)}`); } async wasCommonJS (url: string): Promise<boolean> { // TODO: make this a provider hook const pkgUrl = await this.getPackageBase(url); if (!pkgUrl) return false; const pcfg = await this.getPackageConfig(pkgUrl); if (!pcfg) return false; const subpath = './' + url.slice(pkgUrl.length); return pcfg?.exports?.[subpath + '!cjs'] ? true : false; } async realPath (url: string): Promise<string> { if (!url.startsWith('file:') || this.preserveSymlinks) return url; let encodedColon = false; url = url.replace(/%3a/i, () => { encodedColon = true; return ':'; }); if (!realpath) { [{ realpath }, { pathToFileURL }] = await Promise.all([ import('fs' as any), import('url' as any) ]); } const outUrl = pathToFileURL(await new Promise((resolve, reject) => realpath(new URL(url), (err, result) => err ? reject(err) : resolve(result)))).href; if (encodedColon) return outUrl.replace(':', '%3a'); return outUrl; } async finalizeResolve (url: string, parentIsCjs: boolean, env: string[], installer: Installer, pkgUrl: string): Promise<string> { if (parentIsCjs && url.endsWith('/')) url = url.slice(0, -1); // Only CJS modules do extension searching for relative resolved paths if (parentIsCjs) url = await (async () => { // subfolder checks before file checks because of fetch if (await this.exists(url + '/package.json')) { const pcfg = await this.getPackageConfig(url) || {}; if (env.includes('browser') && typeof pcfg.browser === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.browser, new URL(url)), parentIsCjs, env, installer, pkgUrl); if (env.includes('module') && typeof pcfg.module === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.module, new URL(url)), parentIsCjs, env, installer, pkgUrl); if (typeof pcfg.main === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.main, new URL(url)), parentIsCjs, env, installer, pkgUrl); return this.finalizeResolve(await legacyMainResolve.call(this, null, new URL(url)), parentIsCjs, env, installer, pkgUrl); } if (await this.exists(url + '/index.js')) return url + '/index.js'; if (await this.exists(url + '/index.json')) return url + '/index.json'; if (await this.exists(url + '/index.node')) return url + '/index.node'; if (await this.exists(url)) return url; if (await this.exists(url + '.js')) return url + '.js'; if (await this.exists(url + '.json')) return url + '.json'; if (await this.exists(url + '.node')) return url + '.node'; return url; })(); // Only browser maps apply to relative resolved paths if (env.includes('browser')) { pkgUrl = pkgUrl || await this.getPackageBase(url); if (url.startsWith(pkgUrl)) { const pcfg = await this.getPackageConfig(pkgUrl); if (pcfg && typeof pcfg.browser === 'object' && pcfg.browser !== null) { const subpath = './' + url.slice(pkgUrl.length); if (pcfg.browser[subpath]) { const target = pcfg.browser[subpath]; if (target === false) throw new Error(`TODO: Empty browser map for ${subpath} in ${url}`); if (!target.startsWith('./')) throw new Error(`TODO: External browser map for ${subpath} to ${target} in ${url}`); return await this.finalizeResolve(pkgUrl + target.slice(2), parentIsCjs, env, installer, pkgUrl); } } } } // Node.js core resolutions if (url.startsWith('node:')) { const resolution = await installer.installTarget(url.slice(5), installer.stdlibTarget, pkgUrl, false, 'nodelibs/' + url.slice(5), pkgUrl); let [installPkg, installExport] = resolution.split('|'); if (!installPkg.endsWith('/')) installPkg += '/'; installExport = installExport.length ? './' + installExport : '.'; return this.finalizeResolve(await this.resolveExport(installPkg, installExport, env, parentIsCjs, url, installer, new URL(pkgUrl)), parentIsCjs, env, installer, installPkg); } return url; } async resolveExport (pkgUrl: string, subpath: string, env: string[], parentIsCjs: boolean, originalSpecifier: string, installer: Installer, parentUrl?: URL): Promise<string> { const pcfg = await this.getPackageConfig(pkgUrl) || {}; function throwExportNotDefined () { throw new JspmError(`No '${subpath}' exports subpath defined in ${pkgUrl} resolving ${originalSpecifier}${importedFrom(parentUrl)}.`, 'MODULE_NOT_FOUND'); } if (pcfg.exports !== undefined && pcfg.exports !== null) { function allDotKeys (exports: Record<string, any>) { for (let p in exports) { if (p[0] !== '.') return false; } return true; } if (typeof pcfg.exports === 'string') { if (subpath === '.') return this.finalizeResolve(new URL(pcfg.exports, pkgUrl).href, parentIsCjs, env, installer, pkgUrl); else throwExportNotDefined(); } else if (!allDotKeys(pcfg.exports)) { if (subpath === '.') return this.finalizeResolve(resolvePackageTarget(pcfg.exports, pkgUrl, env, '', installer), parentIsCjs, env, installer, pkgUrl); else throwExportNotDefined(); } else { const match = getMapMatch(subpath, pcfg.exports as Record<string, ExportsTarget>); if (match) { const resolved = resolvePackageTarget(pcfg.exports[match], pkgUrl, env, subpath.slice(match.length - (match.endsWith('*') ? 1 : 0)), installer); if (resolved === null) throwExportNotDefined(); return this.finalizeResolve(resolved, parentIsCjs, env, installer, pkgUrl); } throwExportNotDefined(); } } else { if (subpath === '.' || parentIsCjs && subpath === './') { if (env.includes('browser') && typeof pcfg.browser === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.browser, new URL(pkgUrl), originalSpecifier, pkgUrl), parentIsCjs, env, installer, pkgUrl); if (env.includes('module') && typeof pcfg.module === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.module, new URL(pkgUrl), originalSpecifier, pkgUrl), parentIsCjs, env, installer, pkgUrl); if (typeof pcfg.main === 'string') return this.finalizeResolve(await legacyMainResolve.call(this, pcfg.main, new URL(pkgUrl), originalSpecifier, pkgUrl), parentIsCjs, env, installer, pkgUrl); return this.finalizeResolve(await legacyMainResolve.call(this, null, new URL(pkgUrl), originalSpecifier, pkgUrl), parentIsCjs, env, installer, pkgUrl); } else { return this.finalizeResolve(new URL(subpath, new URL(pkgUrl)).href, parentIsCjs, env, installer, pkgUrl); } } } // async dlPackage (pkgUrl: string, outDirPath: string, beautify = false) { // if (existsSync(outDirPath)) // throw new JspmError(`Checkout directory ${outDirPath} already exists.`); // if (!pkgUrl.endsWith('/')) // pkgUrl += '/'; // const dlPool = new Pool(20); // const pkgContents: Record<string, string | ArrayBuffer> = Object.create(null); // const pcfg = await this.getPackageConfig(pkgUrl); // if (!pcfg || !pcfg.files || !(pcfg.files instanceof Array)) // throw new JspmError(`Unable to checkout ${pkgUrl} as there is no package files manifest.`); // await Promise.all((pcfg.files).map(async file => { // const url = pkgUrl + file; // await dlPool.queue(); // try { // const res = await fetch(url, this.fetchOpts); // switch (res.status) { // case 304: // case 200: // const contentType = res.headers && res.headers.get('content-type'); // let contents: string | ArrayBuffer = await res.arrayBuffer(); // if (beautify) { // if (contentType === 'application/javascript') { // // contents = jsBeautify(contents); // } // else if (contentType === 'application/json') { // contents = JSON.stringify(JSON.parse(contents.toString()), null, 2); // } // } // return pkgContents[file] = contents; // default: throw new JspmError(`Invalid status code ${res.status} looking up ${url} - ${res.statusText}`); // } // } // finally { // dlPool.pop(); // } // })); // for (const file of Object.keys(pkgContents)) { // const filePath = outDirPath + '/' + file; // mkdirp.sync(path.dirname(filePath)); // writeFileSync(filePath, Buffer.from(pkgContents[file])); // } // } async analyze (resolvedUrl: string, parentUrl: URL, system: boolean, isRequire: boolean, retry = true): Promise<Analysis> { const res = await fetch(resolvedUrl, this.fetchOpts); switch (res.status) { case 200: case 304: break; case 404: throw new JspmError(`Module not found: ${resolvedUrl}${importedFrom(parentUrl)}`, 'MODULE_NOT_FOUND'); default: throw new JspmError(`Invalid status code ${res.status} loading ${resolvedUrl}. ${res.statusText}`); } let source = await res.text(); // TODO: headers over extensions for non-file URLs try { if (resolvedUrl.endsWith('.ts') || resolvedUrl.endsWith('.tsx') || resolvedUrl.endsWith('.jsx')) return await createTsAnalysis(source, resolvedUrl); if (resolvedUrl.endsWith('.json')) { try { JSON.parse(source); return { deps: [], dynamicDeps: [], cjsLazyDeps: null, size: source.length, format: 'json' }; } catch {} } const [imports, exports] = parse(source) as any as [any[], string[]]; if (imports.every(impt => impt.d > 0) && !exports.length && resolvedUrl.startsWith('file:')) { // Support CommonJS package boundary checks for non-ESM on file: protocol only if (isRequire) { if (!(resolvedUrl.endsWith('.mjs') || resolvedUrl.endsWith('.js') && (await this.getPackageConfig(await this.getPackageBase(resolvedUrl)))?.type === 'module')) return createCjsAnalysis(imports, source, resolvedUrl); } else if (resolvedUrl.endsWith('.cjs') || resolvedUrl.endsWith('.js') && (await this.getPackageConfig(await this.getPackageBase(resolvedUrl)))?.type !== 'module') { return createCjsAnalysis(imports, source, resolvedUrl); } } return system ? createSystemAnalysis(source, imports, resolvedUrl) : createEsmAnalysis(imports, source, resolvedUrl); } catch (e) { if (!e.message || !e.message.startsWith('Parse error @:')) throw e; // fetch is _unstable_!!! // so we retry the fetch first if (retry) { try { return this.analyze(resolvedUrl, parentUrl, system, isRequire, false); } catch {} } // TODO: better parser errors if (e.message && e.message.startsWith('Parse error @:')) { const [topline] = e.message.split('\n', 1); const pos = topline.slice(14); let [line, col] = pos.split(':'); const lines = source.split('\n'); let errStack = ''; if (line > 1) errStack += '\n ' + lines[line - 2]; errStack += '\n> ' + lines[line - 1]; errStack += '\n ' + ' '.repeat(col - 1) + '^'; if (lines.length > 1) errStack += '\n ' + lines[line]; throw new JspmError(`${errStack}\n\nError parsing ${resolvedUrl}:${pos}`); } throw e; } } } export function resolvePackageTarget (target: ExportsTarget, packageUrl: string, env: string[], subpath: string, installer: Installer): string | null { if (typeof target === 'string') { if (subpath === '') return new URL(target, packageUrl).href; if (target.indexOf('*') !== -1) { return new URL(target.replace(/\*/g, subpath), packageUrl).href; } else if (target.endsWith('/')) { return new URL(target + subpath, packageUrl).href; } else { throw new Error('Expected pattern or path export'); } } else if (typeof target === 'object' && target !== null && !Array.isArray(target)) { for (const condition in target) { if (condition === 'default' || env.includes(condition)) { const resolved = resolvePackageTarget(target[condition], packageUrl, env, subpath, installer); if (resolved) return resolved; } } } else if (Array.isArray(target)) { // TODO: Validation for arrays for (const targetFallback of target) { return resolvePackageTarget(targetFallback, packageUrl, env, subpath, installer); } } return null; } async function legacyMainResolve (this: Resolver, main: string | null, pkgUrl: URL, originalSpecifier: string, parentUrl?: URL) { let guess: string; if (main) { if (await this.exists(guess = new URL(`./${main}/index.js`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}/index.json`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}/index.node`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}.js`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}.json`, pkgUrl).href)) return guess; if (await this.exists(guess = new URL(`./${main}.node`, pkgUrl).href)) return guess; } else { if (await this.exists(guess = new URL('./index.js', pkgUrl).href)) return guess; if (await this.exists(guess = new URL('./index.json', pkgUrl).href)) return guess; if (await this.exists(guess = new URL('./index.node', pkgUrl).href)) return guess; } // Not found. throw new JspmError(`Unable to resolve ${main ? main + ' in ' : ''}${pkgUrl} resolving ${originalSpecifier}${importedFrom(parentUrl)}.`, 'MODULE_NOT_FOUND'); }
the_stack
import * as React from 'react'; import { getShopifyImageDimensions, shopifyImageLoader, addImageSizeParametersToUrl, } from '../../utilities'; import type {Image as ImageType} from '../../storefront-api-types'; import type {PartialDeep, Simplify, SetRequired} from 'type-fest'; type HtmlImageProps = React.ImgHTMLAttributes<HTMLImageElement>; type ImageProps<GenericLoaderOpts> = | ShopifyImageProps | ExternalImageProps<GenericLoaderOpts>; export function Image<GenericLoaderOpts>(props: ImageProps<GenericLoaderOpts>) { if (!props.data && !props.src) { throw new Error(`<Image/>: requires either a 'data' or 'src' prop.`); } if (__HYDROGEN_DEV__ && props.data && props.src) { console.warn( `<Image/>: using both 'data' and 'src' props is not supported; using the 'data' prop by default` ); } if (props.data) { return <ShopifyImage {...props} />; } else { return <ExternalImage {...props} />; } } export type ShopifyLoaderOptions = { crop?: 'top' | 'bottom' | 'left' | 'right' | 'center'; scale?: 2 | 3; width?: HtmlImageProps['width'] | ImageType['width']; height?: HtmlImageProps['height'] | ImageType['height']; }; export type ShopifyLoaderParams = Simplify< ShopifyLoaderOptions & { src: ImageType['url']; } >; export type ShopifyImageProps = Omit<HtmlImageProps, 'src'> & { /** An object with fields that correspond to the Storefront API's * [Image object](https://shopify.dev/api/storefront/reference/common-objects/image). * The `data` prop is required if `src` isn't used, but both props shouldn't be used * at the same time. If both `src` and `data` are passed, then `data` takes priority. */ data: SetRequired<PartialDeep<ImageType>, 'url'>; /** A custom function that generates the image URL. Parameters passed in * are either `ShopifyLoaderParams` if using the `data` prop, or the * `LoaderOptions` object that you pass to `loaderOptions`. */ loader?: (params: ShopifyLoaderParams) => string; /** An object of `loader` function options. For example, if the `loader` function * requires a `scale` option, then the value can be a property of the * `loaderOptions` object (for example, `{scale: 2}`). When the `data` prop * is used, the object shape will be `ShopifyLoaderOptions`. When the `src` * prop is used, the data shape is whatever you define it to be, and this shape * will be passed to `loader`. */ loaderOptions?: ShopifyLoaderOptions; /** * 'src' shouldn't be passed when 'data' is used. */ src?: never; /** * An array of pixel widths to overwrite the default generated srcset. For example, `[300, 600, 800]`. */ widths?: (HtmlImageProps['width'] | ImageType['width'])[]; }; function ShopifyImage({ data, width, height, loading, loader = shopifyImageLoader, loaderOptions, widths, ...rest }: ShopifyImageProps) { if (!data.url) { throw new Error(`<Image/>: the 'data' prop requires the 'url' property`); } if (__HYDROGEN_DEV__ && !data.altText && !rest.alt) { console.warn( `<Image/>: the 'data' prop should have the 'altText' property, or the 'alt' prop, and one of them should not be empty. ${`Image: ${ data.id ?? data.url }`}` ); } const {width: finalWidth, height: finalHeight} = getShopifyImageDimensions( data, loaderOptions ); if ((__HYDROGEN_DEV__ && !finalWidth) || !finalHeight) { console.warn( `<Image/>: the 'data' prop requires either 'width' or 'data.width', and 'height' or 'data.height' properties. ${`Image: ${ data.id ?? data.url }`}` ); } let finalSrc = data.url; if (loader) { finalSrc = loader({ ...loaderOptions, src: data.url, width: finalWidth, height: finalHeight, }); if (typeof finalSrc !== 'string' || !finalSrc) { throw new Error( `<Image/>: 'loader' did not return a valid string. ${`Image: ${ data.id ?? data.url }`}` ); } } // determining what the intended width of the image is. For example, if the width is specified and lower than the image width, then that is the maximum image width // to prevent generating a srcset with widths bigger than needed or to generate images that would distort because of being larger than original const maxWidth = width && finalWidth && width < finalWidth ? width : finalWidth; const finalSrcset = rest.srcSet ?? internalImageSrcSet({ ...loaderOptions, widths, src: data.url, width: maxWidth, loader, }); /* eslint-disable hydrogen/prefer-image-component */ return ( <img id={data.id ?? ''} alt={data.altText ?? rest.alt ?? ''} loading={loading ?? 'lazy'} {...rest} src={finalSrc} width={finalWidth ?? undefined} height={finalHeight ?? undefined} srcSet={finalSrcset} /> ); /* eslint-enable hydrogen/prefer-image-component */ } type LoaderProps<GenericLoaderOpts> = { /** A URL string. This string can be an absolute path or a relative path depending * on the `loader`. The `src` prop is required if `data` isn't used, but both * props shouldn't be used at the same time. If both `src` and `data` are passed, * then `data` takes priority. */ src: HtmlImageProps['src']; /** The integer or string value for the width of the image. This is a required prop * when `src` is present. */ width: HtmlImageProps['width']; /** The integer or string value for the height of the image. This is a required prop * when `src` is present. */ height: HtmlImageProps['height']; /** An object of `loader` function options. For example, if the `loader` function * requires a `scale` option, then the value can be a property of the * `loaderOptions` object (for example, `{scale: 2}`). When the `data` prop * is used, the object shape will be `ShopifyLoaderOptions`. When the `src` * prop is used, the data shape is whatever you define it to be, and this shape * will be passed to `loader`. */ loaderOptions?: GenericLoaderOpts; }; type ExternalImageProps<GenericLoaderOpts> = SetRequired< HtmlImageProps, 'src' | 'width' | 'height' | 'alt' > & { /** A custom function that generates the image URL. Parameters passed in * are either `ShopifyLoaderParams` if using the `data` prop, or the * `LoaderOptions` object that you pass to `loaderOptions`. */ loader?: (params: LoaderProps<GenericLoaderOpts>) => string; /** An object of `loader` function options. For example, if the `loader` function * requires a `scale` option, then the value can be a property of the * `loaderOptions` object (for example, `{scale: 2}`). When the `data` prop * is used, the object shape will be `ShopifyLoaderOptions`. When the `src` * prop is used, the data shape is whatever you define it to be, and this shape * will be passed to `loader`. */ loaderOptions?: GenericLoaderOpts; /** * 'data' shouldn't be passed when 'src' is used. */ data?: never; /** * An array of pixel widths to generate a srcset. For example, `[300, 600, 800]`. */ widths?: HtmlImageProps['width'][]; }; function ExternalImage<GenericLoaderOpts>({ src, width, height, alt, loader, loaderOptions, widths, loading, ...rest }: ExternalImageProps<GenericLoaderOpts>) { if (!width || !height) { throw new Error( `<Image/>: when 'src' is provided, 'width' and 'height' are required and need to be valid values (i.e. greater than zero). Provided values: 'src': ${src}, 'width': ${width}, 'height': ${height}` ); } if (__HYDROGEN_DEV__ && !alt) { console.warn( `<Image/>: when 'src' is provided, 'alt' should also be provided. ${`Image: ${src}`}` ); } if ( widths && Array.isArray(widths) && widths.some((size) => isNaN(size as number)) ) throw new Error( `<Image/>: the 'widths' property must be an array of numbers` ); let finalSrc = src; if (loader) { finalSrc = loader({src, width, height, ...loaderOptions}); if (typeof finalSrc !== 'string' || !finalSrc) { throw new Error(`<Image/>: 'loader' did not return a valid string`); } } let finalSrcset = rest.srcSet ?? undefined; if (!finalSrcset && loader && widths) { // Height is a requirement in the LoaderProps, so to keep the aspect ratio, we must determine the height based on the default values const heightToWidthRatio = parseInt(height as string) / parseInt(width as string); finalSrcset = widths ?.map((width) => parseInt(width as string, 10)) ?.map( (width) => `${loader({ ...loaderOptions, src, width, height: Math.floor(width * heightToWidthRatio), })} ${width}w` ) .join(', '); } /* eslint-disable hydrogen/prefer-image-component */ return ( <img {...rest} src={finalSrc} width={width} height={height} alt={alt ?? ''} loading={loading ?? 'lazy'} srcSet={finalSrcset} /> ); /* eslint-enable hydrogen/prefer-image-component */ } type InternalShopifySrcSetGeneratorsParams = Simplify< ShopifyLoaderOptions & { src: ImageType['url']; widths?: (HtmlImageProps['width'] | ImageType['width'])[]; loader?: (params: ShopifyLoaderParams) => string; } >; // based on the default width sizes used by the Shopify liquid HTML tag img_tag plus a 2560 width to account for 2k resolutions // reference: https://shopify.dev/api/liquid/filters/html-filters#image_tag const IMG_SRC_SET_SIZES = [352, 832, 1200, 1920, 2560]; function internalImageSrcSet({ src, width, crop, scale, widths, loader, }: InternalShopifySrcSetGeneratorsParams) { const hasCustomWidths = widths && Array.isArray(widths); if (hasCustomWidths && widths.some((size) => isNaN(size as number))) throw new Error(`<Image/>: the 'widths' must be an array of numbers`); let setSizes = hasCustomWidths ? widths : IMG_SRC_SET_SIZES; if ( !hasCustomWidths && width && width < IMG_SRC_SET_SIZES[IMG_SRC_SET_SIZES.length - 1] ) setSizes = IMG_SRC_SET_SIZES.filter((size) => size <= width); const srcGenerator = loader ? loader : addImageSizeParametersToUrl; return setSizes .map( (size) => `${srcGenerator({ src, width: size, crop, scale, })} ${size}w` ) .join(', '); }
the_stack
import "../AsyncSupport"; import "../XMLDomInit"; import xmldom from "xmldom"; import test from "ava"; import sinon from "sinon"; import GrimoireInterface from "../../src/Interface/GrimoireInterface"; import Constants from "../../src/Base/Constants"; import Component from "../../src/Node/Component"; import GomlParser from "../../src/Node/GomlParser"; import GomlLoader from "../../src/Node/GomlLoader"; import NSIdentity from "../../src/Base/NSIdentity"; import GomlNode from "../../src/Node/GomlNode"; import Attribute from "../../src/Node/Attribute"; declare namespace global { let Node: any; let document: any; let rootNode: any; } global.Node = { ELEMENT_NODE: 1 }; test.beforeEach(async () => { GrimoireInterface.clear(); const parser = new DOMParser(); const htmlDoc = parser.parseFromString("<html></html>", "text/html"); global.document = htmlDoc; GrimoireInterface.registerNode("goml"); GrimoireInterface.registerNode("scenes"); GrimoireInterface.registerNode("scene"); GrimoireInterface.registerComponent("Test", { attributes: {}, valueTest: "Test"}); GrimoireInterface.registerComponent("Test2", { attributes: {}, valueTest: "Test2"}); await GrimoireInterface.resolvePlugins(); }); test("Add component works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); node.addComponent("Test"); node.addComponent("Test2"); node.addComponent("Test"); t.truthy(node.getComponents("Test").length === 2); t.truthy(node.getComponents("Test2").length === 1); const a = node.getComponent("Test") as any; t.truthy(a.valueTest === "Test"); const b = node.getComponent("Test2") as any; t.truthy(b.valueTest === "Test2"); }); test("Remove component actually delete specified insatnce", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); node.addComponent("Test"); node.addComponent("Test2"); node.addComponent("Test"); const a = node.getComponent("Test") as any; node.removeComponent(a); t.truthy(node.getComponent("Test")); t.truthy(node.getComponents("Test").length === 1); }); test("Remove components should delete specified all components in node", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); node.addComponent("Test"); node.addComponent("Test"); node.addComponent("Test"); t.truthy(node.getComponents("Test").length === 3); node.removeComponents("Test"); t.truthy(node.getComponents("Test").length === 0); }); test("addChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); node.addChild(node2, null, null); t.truthy(node.children[0].id === node2.id); t.truthy(node.children.length === 2); }); test("delete method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); node.addChild(node2, null, null); node2.addChild(node3, null, null); node2.remove(); t.truthy(node.children.length === 0); t.truthy(node2.parent === null); t.truthy(node2.deleted === true); t.truthy(node3.deleted === true); t.truthy(node3.parent === null); }); test("removeChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.removeChild(node2); t.truthy(node2.deleted === true); t.truthy(node3.deleted === true); }); test("detachChild method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.detachChild(node2); t.truthy(node.children.length === 0); t.truthy(node2.deleted === false); t.truthy(node3.parent.id === node2.id); t.truthy(node3.deleted === false); }); test("detach method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); node.addChild(node2, null, null); node2.addChild(node3, null, null); node2.detach(); try { node.detach(); } catch (err) { t.truthy(err.message === "root Node cannot be detached."); } t.truthy(node.children.length === 0); t.truthy(node2.deleted === false); t.truthy(node3.parent.id === node2.id); t.truthy(node3.deleted === false); }); test("getComponents method works correctly", t => { GrimoireInterface.registerComponent("TestComponent", { attributes: { attr1: { converter: "String", default: "testAttr" } } }); GrimoireInterface.registerNode("test-node", ["TestComponent"]); const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("test-node"), null); const components = node.getComponents(); t.truthy(components.length === 2); }); test("setMounted method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null); node.addChild(node2, null, null); node2.addChild(node3, null, null); node.setMounted(true); t.truthy(node.mounted === true); t.truthy(node2.mounted === true); t.truthy(node3.mounted === true); }); test("index method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2); t.truthy(node2.index === 0); }); test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); GrimoireInterface.registerComponent("TestComponent1", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }); const component = GrimoireInterface.componentDeclarations.get("TestComponent1").generateInstance(); node._addComponentDirectly(component, true); const components = node.getComponents<Component>(); t.truthy(components.length === 2); t.truthy(components[1].name.name === "TestComponent1"); t.truthy(component.isDefaultComponent); }); test("addComponent method works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); GrimoireInterface.registerComponent("TestComponent1", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }); const component = node.addComponent("TestComponent1", { testAttr1: "testValue" }); const components = node.getComponents<Component>(); t.truthy(components.length === 2); t.truthy(components[1].name.name === "TestComponent1"); t.truthy(components[1].getAttribute("testAttr1") === "testValue"); t.truthy(component.isDefaultComponent === false); }); test("getComponent method overload works correctly", async t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); GrimoireInterface.registerComponent("TestComponent1", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }); GrimoireInterface.registerComponent("TestComponent2", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }, "TestComponent1"); await GrimoireInterface.resolvePlugins(); node.addComponent("TestComponent2"); t.truthy(node.getComponent<Component>("TestComponent2").name.name === "TestComponent2"); t.truthy(node.getComponent<Component>("TestComponent1").name.name === "TestComponent2"); }); test("getComponents method overload works correctly", t => { const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null); node.addChild(node2, null, null); GrimoireInterface.registerComponent("TestComponent1", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }); GrimoireInterface.registerComponent("TestComponent2", { attributes: { testAttr1: { converter: "String", default: "thisistest" } } }); node.addComponent("TestComponent1"); node.addComponent("TestComponent2"); const components = node.getComponents(); t.truthy(components.length === 3); }); // test("addAttribute method works correctly", t => { // const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null); // GrimoireInterface.registerComponent("TestComponent1", { // attributes: { // testAttr1: { // converter: "String", // default: "thisistest" // } // } // }); // const component = GrimoireInterface.componentDeclarations.get("TestComponent1").generateInstance(); // const attr = new Attribute("testAttr", { // converter: "String", // default: "thisistest" // }, component); // });
the_stack
// tslint:disable:max-line-length import * as azure from "@pulumi/azure"; import * as cloud from "@pulumi/cloud"; import * as pulumi from "@pulumi/pulumi"; import { RunError } from "@pulumi/pulumi/errors"; import * as shared from "./shared"; import * as docker from "@pulumi/docker"; import * as utils from "./utils"; import * as azureContainerSDK from "azure-arm-containerinstance"; import * as msrest from "ms-rest-azure"; export class Service extends pulumi.ComponentResource implements cloud.Service { public readonly name: string; public readonly group: azure.containerservice.Group; public readonly endpoints: pulumi.Output<cloud.Endpoints>; public readonly defaultEndpoint: pulumi.Output<cloud.Endpoint>; public readonly getEndpoint: (containerName?: string, containerPort?: number) => Promise<cloud.Endpoint>; constructor(name: string, args: cloud.ServiceArguments, opts?: pulumi.ResourceOptions) { let containers: cloud.Containers; if (args.image || args.build || args.function) { if (args.containers) { throw new Error( "Exactly one of image, build, function, or containers must be used, not multiple"); } containers = { "default": args }; } else if (args.containers) { containers = args.containers; } else { throw new Error( "Missing one of image, build, function, or containers, specifying this service's containers"); } const replicas = args.replicas === undefined ? 1 : args.replicas; if (replicas !== 1) { throw new RunError("Only a single replicable is supported in Azure currently."); } super("cloud:service:Service", name, { }, opts); const { group, endpoints, defaultEndpoint } = createGroup( this, name, args.host, containers); this.group = group; this.endpoints = endpoints; this.defaultEndpoint = defaultEndpoint; this.getEndpoint = async (containerName, containerPort) => { return getEndpointHelper(endpoints.get(), containerName, containerPort); }; this.registerOutputs(); } } function getEndpointHelper( endpoints: cloud.Endpoints, containerName?: string, containerPort?: number): cloud.Endpoint { containerName = containerName || Object.keys(endpoints)[0]; if (!containerName) { throw new RunError(`No containers available in this service`); } const containerPorts = endpoints[containerName] || {}; containerPort = containerPort || +Object.keys(containerPorts)[0]; if (!containerPort) { throw new RunError(`No ports available in service container ${containerName}`); } const endpoint = containerPorts[containerPort]; if (!endpoint) { throw new RunError(`No exposed port for ${containerName} port ${containerPort}`); } return endpoint; } // AzureContainer and AzureCredentials are just extracted sub-portions of // azure.containerservice.GroupArgs. This was done to make it easy to type check small // objets as we're building them up before making the final Group. interface AzureContainer { commands?: pulumi.Input<string[]>; cpu: pulumi.Input<number>; environmentVariables?: pulumi.Input<{ [key: string]: any; }>; image: pulumi.Input<string>; memory: pulumi.Input<number>; name: pulumi.Input<string>; ports?: azure.types.input.containerservice.GroupContainer["ports"]; protocol?: pulumi.Input<string>; volumes?: pulumi.Input<pulumi.Input<{ mountPath: pulumi.Input<string>; name: pulumi.Input<string>; readOnly?: pulumi.Input<boolean>; shareName: pulumi.Input<string>; storageAccountKey: pulumi.Input<string>; storageAccountName: pulumi.Input<string>; }>[]>; } interface AzureCredentials { password: pulumi.Input<string>; server: pulumi.Input<string>; username: pulumi.Input<string>; } interface GroupInfo { group: azure.containerservice.Group; endpoints: pulumi.Output<cloud.Endpoints>; defaultEndpoint: pulumi.Output<cloud.Endpoint>; } interface ExposedPorts { [name: string]: { [port: string]: number; }; } function createGroup( parent: pulumi.Resource, name: string, props: cloud.HostProperties | undefined, containers: cloud.Containers): GroupInfo { const disallowedChars = /[^-a-zA-Z0-9]/g; props = props || {}; const azureContainers: AzureContainer[] = []; let credentials: AzureCredentials[] | undefined; let firstContainerName: string | undefined; let firstContainerPort: number | undefined; const exposedPorts: ExposedPorts = {}; for (const containerName of Object.keys(containers)) { const container = containers[containerName]; if (firstContainerName === undefined) { firstContainerName = containerName; } const ports = container.ports; let hostPortNumber: number | undefined; let targetPortNumber: number | undefined; let protocol: string | undefined; let isPublic: boolean | undefined; if (ports) { if (ports.length >= 2) { throw new RunError("Only zero or one port can be provided with a container: " + containerName); } if (ports.length === 1) { const port = ports[0]; hostPortNumber = port.port; targetPortNumber = port.targetPort !== undefined ? port.targetPort : hostPortNumber; protocol = port.protocol; if (targetPortNumber !== hostPortNumber) { throw new RunError("Mapping a host port to a different target port is not supported in Azure currently."); } if (containerName === firstContainerName) { firstContainerPort = targetPortNumber; } const external = port.external === undefined ? false : port.external; if (isPublic === undefined) { // first port we're seeing. set the isPublic value based on that. isPublic = external; } else if (isPublic !== external) { // have an existing port. Values have to match. throw new RunError("All ports must have a matching [external] value."); } } } if (isPublic === false) { throw new RunError("Only public ip address types are supported by Azure currently."); } const { imageOptions, registry } = computeImageOptionsAndRegistry(this, container); const memoryInGB = pulumi.output(container.memoryReservation).apply( r => r === undefined ? 1 : r / 1024); const qualifiedName = (name + "-" + containerName).replace(disallowedChars, "-"); azureContainers.push({ name: qualifiedName, cpu: pulumi.output(container.cpu).apply(c => c === undefined ? 1 : c), memory: memoryInGB, ports: [{ port: targetPortNumber, }], protocol: protocol, image: imageOptions.image, environmentVariables: imageOptions.environment, commands: container.command, }); credentials = credentials || (registry ? [{ password: registry.adminPassword, server: registry.loginServer, username: registry.adminUsername }] : undefined); if (targetPortNumber !== undefined) { exposedPorts[containerName] = { [targetPortNumber]: hostPortNumber! }; } } const group = new azure.containerservice.Group( name.replace(disallowedChars, "-"), { containers: azureContainers, location: shared.location, resourceGroupName: shared.globalResourceGroupName, osType: getOS(props), imageRegistryCredentials: credentials, ipAddressType: "Public", }, { parent: parent }); const endpoints = getEndpoints(exposedPorts, group); const defaultEndpoint = firstContainerName === undefined || firstContainerPort === undefined ? pulumi.output<cloud.Endpoint>(undefined!) : endpoints.apply( ep => getEndpointHelper(ep)); return { group, endpoints, defaultEndpoint }; } function getEndpoints(ports: ExposedPorts, group: azure.containerservice.Group): pulumi.Output<cloud.Endpoints> { return pulumi.all(utils.apply(ports, targetPortToHostPort => { const inner: pulumi.Output<{ [port: string]: cloud.Endpoint }> = pulumi.all(utils.apply(targetPortToHostPort, hostPort => group.ipAddress.apply(ip => ({ port: hostPort, hostname: ip, })))); return inner; })); } /** * A Task represents a container which can be [run] dynamically whenever (and as many times as) * needed. */ export class Task extends pulumi.ComponentResource implements cloud.Task { public readonly run: (options?: cloud.TaskRunOptions) => Promise<void>; constructor(name: string, container: cloud.Container, opts?: pulumi.ResourceOptions) { super("cloud:task:Task", name, { }, opts); if (container.ports && container.ports.length > 0) { throw new RunError("Tasks should not be given any [ports] in their Container definition."); } const { imageOptions, registry } = computeImageOptionsAndRegistry(this, container); const globalResourceGroupName = shared.globalResourceGroupName; const memory = pulumi.output(container.memoryReservation); // Require the client credentials at deployment time so we can fail up-front if they are not // provided. const config = new pulumi.Config("cloud-azure"); const subscriptionId = config.require("subscriptionId"); const clientId = config.require("clientId"); const clientSecret = config.require("clientSecret"); const tenantId = config.require("tenantId"); this.run = async (options) => { try { options = options || {}; // For now, we use Service Principal Authentication: // https://github.com/Azure/azure-sdk-for-node/blob/master/Documentation/Authentication.md#service-principal-authentication // // We should consider supporting other forms (including Managed Service Identity) in // the future. const clientCredentials: any = await new Promise((resolve, reject) => { msrest.loginWithServicePrincipalSecret( clientId, clientSecret, tenantId, (err, credentials) => { if (err) { return reject(err); } resolve(credentials); }, ); }); const client = new azureContainerSDK.ContainerInstanceManagementClient( clientCredentials, subscriptionId); // Join the environment options specified by the image, along with any options // provided by the caller of [Task.run]. const imageOpts = imageOptions.get(); let envMap = imageOpts.environment; if (options.environment) { envMap = Object.assign(options.environment, envMap); } // Convert the environment to the form that azure needs. const env = Object.keys(envMap).map(k => ({ name: k, value: envMap[k] })); const containerCredentials = registry ? [{ server: registry.loginServer.get(), username: registry.adminUsername.get(), password: registry.adminPassword.get() }] : undefined; const uniqueName = createUniqueContainerName(name); const group = await client.containerGroups.createOrUpdate( globalResourceGroupName.get(), uniqueName, { location: shared.location, osType: getOS(options.host), containers: [{ name: uniqueName, image: imageOpts.image, environmentVariables: env, resources: { requests: { cpu: 1, memoryInGB: memory.get() || 1, }, }, }], imageRegistryCredentials: containerCredentials, // We specify 'Never' as the restart policy because we want a Task to // launch, execute once, and be done. Note: this means that the account // will generally fill up with terminated container instances. This Azure // feedback issue tracks Azure adding a facility for these to be // automatically cleaned up: // https://feedback.azure.com/forums/602224-azure-container-instances/suggestions/34066633-support-auto-delete-of-aci-when-container-exits-no // // In the meantime, we should consider if we should have some mechanism that // does this on behalf of the user. For example, we could store the name // of this ephemeral instance somewhere. Then, with each Task.run we could // enumerate that list and attempt to cleanup any terminated instances. restartPolicy: "Never", }); } catch (err) { console.log("Error: " + JSON.stringify(err, null, 2)); throw err; } }; this.registerOutputs(); } } function getOS(props: cloud.HostProperties | undefined) { return props && props.os ? props.os : "Linux"; } function createUniqueContainerName(name: string) { const uniqueName = name + shared.sha1hash(Math.random().toString()); // Azure requires container names to be all lowercase. return uniqueName.toLowerCase(); } export class SharedVolume extends pulumi.ComponentResource implements cloud.SharedVolume { public readonly kind = "SharedVolume"; public readonly name: string; constructor(name: string, opts?: pulumi.ResourceOptions) { super("cloud:volume:Volume", name, {}, opts); throw new Error("Method not implemented."); this.registerOutputs({ kind: this.kind, name: this.name }); } } export class HostPathVolume implements cloud.HostPathVolume { public readonly kind = "HostPathVolume"; public readonly path: string; constructor(path: string) { this.path = path; } } function getBuildImageName(build: string | cloud.ContainerBuild) { // Produce a hash of the build context and use that for the image name. let buildSig: string; if (typeof build === "string") { buildSig = build; } else { buildSig = build.context || "."; if (build.dockerfile) { buildSig += `;dockerfile=${build.dockerfile}`; } if (build.args) { for (const arg of Object.keys(build.args)) { buildSig += `;arg[${arg}]=${build.args[arg]}`; } } } // The container name must contain no more than 63 characters and must match the regex // '[a-z0-9]([-a-z0-9]*[a-z0-9])?' (e.g. 'my-name')." const imageName = shared.createNameWithStackInfo(`container-${shared.sha1hash(buildSig)}`, 63, "-"); const disallowedChars = /[^-a-zA-Z0-9]/g; return imageName.replace(disallowedChars, "-"); } let globalRegistry: azure.containerservice.Registry | undefined; function getOrCreateGlobalRegistry(): azure.containerservice.Registry { if (!globalRegistry) { globalRegistry = new azure.containerservice.Registry("global", { resourceGroupName: shared.globalResourceGroupName, location: shared.location, // We need the admin account enabled so that we can grab the name/password to send to // docker. We could consider an approach whereby this was not enabled, but it was // conditionally enabled/disabled on demand when needed. adminEnabled: true, sku: "Standard", }, { parent: shared.getGlobalInfrastructureResource() }); } return globalRegistry; } // buildImageCache remembers the digests for all past built images, keyed by image name. const buildImageCache = new Map<string, pulumi.Output<string>>(); interface ImageOptions { image: string; environment: Record<string, string>; } function computeImageOptionsAndRegistry( parent: pulumi.Resource, container: cloud.Container) { // Start with a copy from the container specification. const preEnv: Record<string, pulumi.Input<string>> = Object.assign({}, container.environment || {}); if (container.build) { return computeImageFromBuild(parent, preEnv, container.build); } else if (container.image) { return { imageOptions: createImageOptions(container.image, preEnv), registry: undefined }; } else if (container.function) { return { imageOptions: computeImageFromFunction(container.function, preEnv), registry: undefined }; } else { throw new RunError("Invalid container definition: `image`, `build`, or `function` must be provided"); } } function computeImageFromBuild( parent: pulumi.Resource, preEnv: Record<string, pulumi.Input<string>>, build: string | cloud.ContainerBuild) { const imageName = getBuildImageName(build); const registry = getOrCreateGlobalRegistry(); // This is a container to build; produce a name, either user-specified or auto-computed. pulumi.log.debug(`Building container image at '${build}'`, registry); const dockerRegistry = pulumi.output({ registry: registry.loginServer, username: registry.adminUsername, password: registry.adminPassword, }); const imageOptions = pulumi.all([registry.loginServer, dockerRegistry]).apply(([loginServer, dockerRegistry]) => computeImageFromBuildWorker(preEnv, build, imageName, loginServer + "/" + imageName, dockerRegistry, parent)); return { imageOptions, registry }; } function computeImageFromBuildWorker( preEnv: Record<string, pulumi.Input<string>>, build: string | cloud.ContainerBuild, imageName: string, repositoryUrl: string, dockerRegistry: docker.Registry, logResource: pulumi.Resource): pulumi.Output<ImageOptions> { let uniqueImageName = buildImageCache.get(imageName); // See if we've already built this. if (uniqueImageName) { uniqueImageName.apply(d => pulumi.log.debug(` already built: ${imageName} (${d})`, logResource)); } else { // If we haven't, build and push the local build context to the azure docker repository. // Then return the unique name given to this image in that repository. The name will change // if the image changes ensuring the TaskDefinition get's replaced IFF the built image // changes. uniqueImageName = docker.buildAndPushImage( imageName, build, repositoryUrl, logResource, async () => dockerRegistry); uniqueImageName.apply(d => pulumi.log.debug(` build complete: ${imageName} (${d})`, logResource)); } return createImageOptions(uniqueImageName, preEnv); } function computeImageFromFunction( func: () => void, preEnv: Record<string, pulumi.Input<string>>): pulumi.Output<ImageOptions> { // TODO[pulumi/pulumi-cloud#85]: Put this in a real Pulumi-owned Docker image. // TODO[pulumi/pulumi-cloud#86]: Pass the full local zipped folder through to the container (via S3?) preEnv.PULUMI_SRC = pulumi.runtime.serializeFunction(func).then(v => v.text); // TODO[pulumi/pulumi-cloud#85]: move this to a Pulumi Docker Hub account. return createImageOptions("lukehoban/nodejsrunner", preEnv); } function createImageOptions( image: pulumi.Input<string>, environment: Record<string, pulumi.Input<string>>): pulumi.Output<ImageOptions> { return pulumi.output({ image, environment }); }
the_stack
import axios, {AxiosRequestConfig} from 'axios'; import BigNumber from 'bignumber.js'; import {PinoLogger} from 'nestjs-pino'; import {Request} from 'express'; import { Currency, SignatureId, EgldBasicTransaction, egldGetGasPrice, egldGetGasLimit, generateAddressFromXPub, generatePrivateKeyFromMnemonic, generateWallet, TransactionHash, EgldEsdtTransaction, EgldSendTransaction, prepareEgldSignedTransaction, prepareEgldDeployEsdtSignedTransaction, prepareEgldMintEsdtSignedTransaction, prepareEgldBurnEsdtSignedTransaction, prepareEgldPauseEsdtSignedTransaction, prepareEgldSpecialRoleEsdtOrNftSignedTransaction, prepareEgldFreezeOrWipeOrOwvershipEsdtSignedTransaction, prepareEgldControlChangesEsdtSignedTransaction, prepareEgldTransferEsdtSignedTransaction, prepareEgldDeployNftOrSftSignedTransaction, prepareEgldCreateNftOrSftSignedTransaction, prepareEgldTransferNftCreateRoleSignedTransaction, prepareEgldStopNftCreateSignedTransaction, prepareEgldAddOrBurnNftQuantitySignedTransaction, prepareEgldFreezeNftSignedTransaction, prepareEgldWipeNftSignedTransaction, prepareEgldTransferNftSignedTransaction, } from '@tatumio/tatum'; import {BroadcastOrStoreKMSTransaction} from '@tatumio/blockchain-connector-common' import {EgldError} from './EgldError'; // EGLD docs: // https://docs.elrond.com/developers/esdt-tokens/#issuance-of-fungible-esdt-tokens export abstract class EgldService { private static mapBlock(block: any) { return { nonce: block.nonce, round: block.round, hash: block.hash, prevBlockHash: block.prevBlockHash, epoch: block.epoch, numTxs: block.numTxs, shardBlocks: (block.shardBlocks || []).map(EgldService.mapShardBlock), transactions: (block.transactions || []).map(EgldService.mapInBlockTransaction), }; } private static mapShardBlock(block: any) { return { hash: block.hash, nonce: block.nonce, shard: block.shard, }; } private static mapInBlockTransaction(tx: any) { return { type: tx.type, hash: tx.hash, nonce: tx.nonce, value: tx.value, receiver: tx.receiver, sender: tx.sender, gasPrice: tx.gasPrice, gasLimit: tx.gasLimit, data: tx.data, signature: tx.signature, status: tx.status, }; }; private static mapTransaction(tx: any) { return { type: tx.type, nonce: tx.nonce, round: tx.round, epoch: tx.epoch, value: tx.value, receiver: tx.receiver, sender: tx.sender, gasPrice: tx.gasPrice, gasLimit: tx.gasLimit, data: tx.data, signature: tx.signature, sourceShard: tx.sourceShard, destinationShard: tx.destinationShard, blockNonce: tx.blockNonce, blockHash: tx.blockHash, miniblockHash: tx.miniblockHash, timestamp: tx.timestamp, status: tx.status, hyperblockNonce: tx.hyperblockNonce, hyperblockHash: tx.hyperblockHash, receipt: EgldService.mapReceipt(tx.receipt || []), smartContractResults: (tx.smartContractResults || []).map(EgldService.mapSmartContractResults) }; }; private static mapReceipt(rx: any) { return { value: rx.value, sender: rx.sender, data: rx.data, txHash: rx.txHash, }; } private static mapSmartContractResults(sx: any) { return { hash: sx.hash, nonce: sx.nonce, value: sx.value, receiver: sx.receiver, sender: sx.sender, data: sx.data, prevTxHash: sx.prevTxHash, originalTxHash: sx.originalTxHash, gasLimit: sx.gasLimit, gasPrice: sx.gasPrice, callType: sx.callType, logs: sx.logs || null, }; } protected constructor(protected readonly logger: PinoLogger) { } protected abstract isTestnet(): Promise<boolean> protected abstract getNodesUrl(testnet: boolean): Promise<string[]> protected abstract storeKMSTransaction(txData: string, currency: string, signatureId: string[], index?: number): Promise<string>; protected abstract completeKMSTransaction(txId: string, signatureId: string): Promise<void>; private async getFirstNodeUrl(testnet: boolean): Promise<string> { const nodes = await this.getNodesUrl(testnet); if (nodes.length === 0) { new EgldError('Nodes url array must have at least one element.', 'egld.nodes.url'); } return nodes[0]; } public async getClient(testnet: boolean): Promise<string> { return await this.getFirstNodeUrl(testnet); } public async broadcast(txData: string, signatureId?: string, withdrawalId?: string): Promise<{ txId: string, failed?: boolean, }> { this.logger.info(`Broadcast tx for EGLD with data '${txData}'`); const t = await this.isTestnet(); let result = {txId: undefined}; try { const {txHash} = (await axios.post(`${await this.getFirstNodeUrl(t)}/transaction/send`, txData, {headers: {'content-type': 'text/plain'}})).data.data; result.txId = txHash; } catch (e) { new EgldError(`Unable to broadcast transaction due to ${e.message}.`, 'egld.broadcast.failed'); throw e; } if (signatureId) { try { await this.completeKMSTransaction(result.txId, signatureId); } catch (e) { this.logger.error(e); return {txId: result.txId, failed: true}; } } return result; } public async getCurrentBlock(testnet?: boolean): Promise<number> { const t = testnet === undefined ? await this.isTestnet() : testnet; try { const {status} = (await axios.get(`${await this.getFirstNodeUrl(t)}/network/status/4294967295`, {headers: {'Content-Type': 'application/json'}})).data.data; return status?.erd_highest_final_nonce; } catch (e) { this.logger.error(e); throw e; } } public async getBlock(hash: string | number, testnet?: boolean) { const t = testnet === undefined ? await this.isTestnet() : testnet; try { const isHash = typeof hash === 'string' && hash.length >= 64; const block = (await axios.get(`${await this.getFirstNodeUrl(t)}/hyperblock/${isHash ? 'by-hash' : 'by-nonce'}/${hash}`, {headers: {'Content-Type': 'application/json'}})).data.data.hyperblock; return EgldService.mapBlock(block); } catch (e) { this.logger.error(e); throw e; } } public async getTransaction(txId: string, testnet?: boolean) { const t = testnet === undefined ? await this.isTestnet() : testnet; try { const { transaction } = (await axios.get(`${await this.getFirstNodeUrl(t)}/transaction/${txId}?withResults=true`, {headers: {'Content-Type': 'application/json'}})).data.data; return EgldService.mapTransaction({...transaction, hash: txId}); } catch (e) { this.logger.error(e); throw new EgldError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found'); } } public async getTransactionCount(address: string) { const t = await this.isTestnet(); try { const {nonce} = (await axios.get(`${await this.getFirstNodeUrl(t)}/address/${address}/nonce`, {headers: {'Content-Type': 'application/json'}})).data.data; return nonce; } catch (e) { this.logger.error(e); throw new EgldError('Transactions count for account not found.', 'accountNonceTx.not.found'); } } public async getTransactionsByAccount(address: string, pageSize?: string, offset?: string, count?: string) { const t = await this.isTestnet(); try { const {transactions} = (await axios.get(`${await this.getFirstNodeUrl(t)}/address/${address}/transactions`, {headers: {'Content-Type': 'application/json'}})).data.data; return transactions; } catch (e) { this.logger.error(e); throw new EgldError('Transactions count for account not found.', 'accountNonceTx.not.found'); } } private async broadcastOrStoreKMSTransaction({ transactionData, signatureId, index }: BroadcastOrStoreKMSTransaction) { if (signatureId) { return { signatureId: await this.storeKMSTransaction(transactionData, Currency.EGLD, [signatureId], index), }; } return this.broadcast(transactionData); } public async nodeMethod(req: Request, key: string) { const node = await this.getFirstNodeUrl(await this.isTestnet()); const path = req.url; const baseURL = node; const [_, url] = path.split(`/${key}/`); const config = { method: req.method || 'GET', url, baseURL, headers: { 'content-type': 'application/json', }, ...(Object.keys(req.body).length ? {data: req.body} : {}), }; try { return (await axios.request(config as AxiosRequestConfig)).data; } catch (e) { this.logger.error(e.response ? e.response.data?.message : e); throw new EgldError(`Unable to communicate with blockchain. ${e.response ? e.response.data?.message : e}`, 'egld.failed'); } } public async generateWallet(mnemonic?: string) { return generateWallet(Currency.EGLD, await this.isTestnet(), mnemonic); } public async generatePrivateKey(mnemonic: string, index: number) { const key = await generatePrivateKeyFromMnemonic(Currency.EGLD, await this.isTestnet(), mnemonic, index); return {key}; } public async generateAddress(mnem: string, derivationIndex: string): Promise<{ address: string }> { const address = await generateAddressFromXPub(Currency.EGLD, await this.isTestnet(), mnem, parseInt(derivationIndex)); return {address}; } public async estimateGas(body: EgldBasicTransaction) { const tx: EgldBasicTransaction = { ...body, data: body.data ? Buffer.from(body.data as string).toString('base64') : undefined, }; return { gasLimit: await egldGetGasLimit(tx), gasPrice: await egldGetGasPrice(), }; } public async getBalance(address: string): Promise<{ balance: string }> { const t = await this.isTestnet(); try { const {balance} = (await axios.get(`${await this.getFirstNodeUrl(t)}/address/${address}/balance`, {headers: {'Content-Type': 'application/json'}})).data.data; return {balance: new BigNumber(balance).dividedBy(1e+18).toString()}; } catch (e) { this.logger.error(e); throw new EgldError('Balance for account not found.', 'accountBalance.not.found'); } } public async getBalanceErc20(address: string, tokenId: string): Promise<{ balance: string }> { const t = await this.isTestnet(); try { const {balance} = (await axios.get(`${await this.getFirstNodeUrl(t)}/address/${address}/esdt/${tokenId}`, {headers: {'Content-Type': 'application/json'}})).data.data.tokenData; return {balance: new BigNumber(balance).dividedBy(1e+18).toString()}; } catch (e) { this.logger.error(e); throw new EgldError('Erc20 balance for account not found.', 'accountBalanceErc20.not.found'); } } public async sendEgldTransaction(transfer: EgldEsdtTransaction): Promise<TransactionHash | SignatureId> { const transactionData = await prepareEgldSignedTransaction(transfer, await this.getFirstNodeUrl(await this.isTestnet())); return this.broadcastOrStoreKMSTransaction({ transactionData, signatureId: transfer.signatureId, index: transfer.index }); } // these methods are not implemented: // public async pauseSmartContract(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldPauseEsdtSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async specialRoleSmartContract(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldSpecialRoleEsdtOrNftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async freezeOrWipeOrOwvershipSmartContract(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldFreezeOrWipeOrOwvershipEsdtSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } public async invokeSmartContractMethod(tx: EgldEsdtTransaction) { const transactionData = await prepareEgldTransferEsdtSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); return this.broadcastOrStoreKMSTransaction({ transactionData, signatureId: tx.signatureId, index: tx.index }); } // these methods are moveded: // public async deployNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldDeployNftOrSftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async createNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldCreateNftOrSftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // these methods are not implemented: // public async roleTransferNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldTransferNftCreateRoleSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async stopNftCreate(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldStopNftCreateSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async addOrBurnNftQuantity(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldAddOrBurnNftQuantitySignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async freezeNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldFreezeNftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // public async wipeNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldWipeNftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } // these methods are moveded: // public async transferNft(tx: EgldEsdtTransaction) { // const transactionData = await prepareEgldTransferNftSignedTransaction(tx, await this.getFirstNodeUrl(await this.isTestnet())); // return this.broadcastOrStoreKMSTransaction({ // transactionData, // signatureId: tx.signatureId, // index: tx.index // }); // } }
the_stack
import NaviMetadataSerializer from '../../../serializers/metadata/base.js'; import CARDINALITY_SIZES from '../../../utils/enums/cardinality-sizes.js'; import upperFirst from 'lodash/upperFirst.js'; import { DataType } from '../../../models/metadata/function-parameter.js'; import type { FunctionParameterMetadataPayload } from '../../../models/metadata/function-parameter.js'; import type { Cardinality } from '../../../utils/enums/cardinality-sizes.js'; import type { RawColumnType } from '../../../models/metadata/column.js'; import type { TableMetadataPayload } from '../../../models/metadata/table.js'; import type MetricMetadataModel from '../../../models/metadata/metric.js'; import type { MetricMetadataPayload } from '../../../models/metadata/metric.js'; import type DimensionMetadataModel from '../../../models/metadata/dimension.js'; import type TimeDimensionMetadataModel from '../../../models/metadata/time-dimension.js'; import type { TimeDimensionMetadataPayload } from '../../../models/metadata/time-dimension.js'; import type ColumnFunctionMetadataModel from '../../../models/metadata/column-function.js'; import type { ColumnFunctionMetadataPayload } from '../../../models/metadata/column-function.js'; import type { MetadataModelMap, EverythingMetadataPayload } from '../../../serializers/metadata/interface.js'; import ElideDimensionMetadataModel from '../../../models/metadata/elide/dimension.js'; import { ElideDimensionMetadataPayload, ValueSourceType } from '../../../models/metadata/elide/dimension.js'; import type { Grain } from '../../../utils/date.js'; import { TableSource } from '../../../models/metadata/dimension.js'; import { Config, getInjector } from '../../../models/native-with-create.js'; import { ClientConfig } from '../../../config/datasources.js'; import invariant from 'tiny-invariant'; type Edge<T> = { node: T; cursor: string; }; export type Connection<T> = { edges: Edge<T>[]; pageInfo?: any; // TODO: Better pageInfo type }; type ElideCardinality = Uppercase<'unknown' | 'tiny' | 'small' | 'medium' | 'large' | 'huge'>; type ColumnNode = { id: string; name: string; friendlyName: string; description: string; category: string; valueType: string; tags: string[]; columnType: RawColumnType; expression: string; arguments: Connection<ElideArgument>; }; export type MetricNode = ColumnNode & { defaultFormat: string }; type ElideArgument = { id: string; name: string; description: string; type: DataType; values: string[]; valueSourceType: ValueSourceType; tableSource: Connection<ElideTableSource>; defaultValue: string; }; export type ElideTableSource = { suggestionColumns: Connection<Partial<DimensionNode>>; valueSource: Connection<Partial<DimensionNode>>; }; export type DimensionNode = ColumnNode & { cardinality: ElideCardinality; valueSourceType: ValueSourceType; tableSource: Connection<ElideTableSource> | null; values: string[]; }; export type TimeDimensionNode = DimensionNode & { supportedGrains: Connection<TimeDimensionGrainNode>; timeZone: string; }; export type TimeDimensionGrainNode = { id: string; expression: string; grain: string; }; export type NamespaceNode = { id: string; name: string; friendlyName: string; description: string; }; type TableNode = { id: string; name: string; friendlyName: string; description: string; category: string; cardinality: ElideCardinality; isFact: boolean; namespace: Connection<NamespaceNode>; metrics: Connection<MetricNode>; dimensions: Connection<DimensionNode>; timeDimensions: Connection<TimeDimensionNode>; }; export interface TablePayload { data?: { table: Connection<TableNode>; }; error?: { message: string; }; } function isPresent<T>(t: T | undefined | null | void): t is T { return t !== undefined && t !== null; } export default class ElideMetadataSerializer extends NaviMetadataSerializer { private namespace = 'normalizer-generated'; @Config('client') declare clientConfig: ClientConfig; protected createDimensionModel(payload: ElideDimensionMetadataPayload): DimensionMetadataModel { return new ElideDimensionMetadataModel(getInjector(this), payload); } /** * Transform the elide metadata into a shape that our internal data models can use * @private * @method _normalizeTableConnection - normalizes the table connection object * @param {Object} tableConnection - table connection with array of edges to table nodes * @param {string} source - datasource of the payload * @returns {Object} - tables and their associated columns models */ _normalizeTableConnection(tableConnection: Connection<TableNode>, source: string): EverythingMetadataPayload { const edges = tableConnection.edges || []; let metrics: MetricMetadataModel[] = []; let dimensions: DimensionMetadataModel[] = []; let timeDimensions: TimeDimensionMetadataModel[] = []; let columnFunctions: ColumnFunctionMetadataModel[] = []; const tablePayloads = edges.map(({ node: table }) => { const newTable: TableMetadataPayload = { id: table.id, name: table.friendlyName, category: table.category, description: table.description, cardinality: this._normalizeCardinality(table.cardinality), isFact: table.isFact ?? true, metricIds: [], dimensionIds: [], timeDimensionIds: [], requestConstraintIds: [], source, }; const newTableMetrics = this._normalizeTableMetrics(table.metrics, table.id, source); const newTableDimensions = this._normalizeTableDimensions(table.dimensions, table.id, source); const newTableTimeDimensionsAndColFuncs = this._normalizeTableTimeDimensions( table.timeDimensions, table.id, source ); const newTableTimeDimensions = newTableTimeDimensionsAndColFuncs.map((obj) => obj.timeDimension); const newTableTimeDimensionColFuncs = newTableTimeDimensionsAndColFuncs.map((obj) => obj.columnFunction); newTable.metricIds = newTableMetrics.map((m) => m.metricModel.id); newTable.dimensionIds = newTableDimensions.map((d) => d.dimensionModel.id); newTable.timeDimensionIds = newTableTimeDimensions.map((d) => d.id); metrics = [...metrics, ...newTableMetrics.map((m) => m.metricModel)]; dimensions = [...dimensions, ...newTableDimensions.map((d) => d.dimensionModel)]; timeDimensions = [...timeDimensions, ...newTableTimeDimensions]; columnFunctions = [ ...columnFunctions, ...newTableTimeDimensionColFuncs, ...newTableMetrics.map((m) => m.columnFunction), ...newTableDimensions.map((m) => m.columnFunction), ].filter(isPresent); return newTable; }); return { tables: tablePayloads.map(this.createTableModel.bind(this)), metrics, dimensions, timeDimensions, columnFunctions, requestConstraints: [], }; } /** * @private * @method _normalizeTableMetrics - normalizes the MetricConnection JSON response * @param {Connection<MetricNode>} metricConnection - MetricConnection JSON * @param {string} source - datasource name * @returns {Object[]} - metric models */ _normalizeTableMetrics( metricConnection: Connection<MetricNode>, tableId: string, source: string ): { metricModel: MetricMetadataModel; columnFunction: ColumnFunctionMetadataModel | null; }[] { return metricConnection.edges.map(({ node }) => { const columnFunction = this.createColumnFunction(node.id, node.arguments, source); const payload: MetricMetadataPayload = { id: node.id, name: node.friendlyName, description: node.description, category: node.category, valueType: node.valueType, tableId, source, tags: node.tags, defaultFormat: node.defaultFormat, isSortable: true, type: node.columnType, expression: node.expression, columnFunctionId: columnFunction?.id, }; return { metricModel: this.createMetricModel(payload), columnFunction, }; }); } /** * @private * @method _normalizeDimensions - normalizes the Connection<DimensionNode> JSON response * @param {Connection<DimensionNode>} dimensionConnection - Connection<DimensionNode> JSON * @param {string} source - datasource name * @returns dimension models */ _normalizeTableDimensions( dimensionConnection: Connection<DimensionNode>, tableId: string, source: string ): { dimensionModel: DimensionMetadataModel; columnFunction: ColumnFunctionMetadataModel | null; }[] { return dimensionConnection.edges.map((edge: Edge<DimensionNode>) => { const { node } = edge; const columnFunction = this.createColumnFunction(node.id, node.arguments, source); const cardinality = this._normalizeCardinality(node.cardinality); const tableSource = node.tableSource?.edges[0]; const payload: ElideDimensionMetadataPayload = { id: node.id, name: node.friendlyName, description: node.description, ...(cardinality ? { cardinality } : {}), category: node.category, valueType: node.valueType, tableId, source, tags: node.tags, isSortable: true, type: node.columnType, expression: node.expression, valueSourceType: node.valueSourceType, tableSource: tableSource ? { valueSource: tableSource.node.valueSource.edges[0].node.id, suggestionColumns: tableSource.node.suggestionColumns.edges.map((e) => ({ id: e.node.id as string })), } : undefined, values: node.values, columnFunctionId: columnFunction?.id, }; return { dimensionModel: this.createDimensionModel(payload), columnFunction, }; }); } /** * @private * @method _normalizeTableTimeDimensions - normalizes the TimeConnection<DimensionNode> JSON response * @param {TimeConnection<DimensionNode>} timeConnection<DimensionNode> - TimeConnection<DimensionNode> JSON * @param {string} source - datasource name * @returns timeDimension models */ _normalizeTableTimeDimensions( timeDimensionConnection: Connection<TimeDimensionNode>, tableId: string, source: string ): { timeDimension: TimeDimensionMetadataModel; columnFunction: ColumnFunctionMetadataModel }[] { return timeDimensionConnection.edges.map((edge: Edge<TimeDimensionNode>) => { const { node } = edge; const supportedGrains = node.supportedGrains.edges.map((edge) => edge.node); const columnFunctionPayload = this.createTimeGrainColumnFunction(node.id, supportedGrains, source); const timeDimensionPayload: TimeDimensionMetadataPayload = { id: node.id, name: node.friendlyName, description: node.description, category: node.category, valueType: node.valueType, tableId, columnFunctionId: columnFunctionPayload.id, source, tags: node.tags, supportedGrains: node.supportedGrains.edges .map(({ node }) => node) .map(({ expression, grain }) => ({ id: this.normalizeTimeGrain(grain), expression, grain })), timeZone: node.timeZone, isSortable: true, type: node.columnType, expression: node.expression, valueSourceType: node.valueSourceType, }; return { timeDimension: this.createTimeDimensionModel(timeDimensionPayload), columnFunction: this.createColumnFunctionModel(columnFunctionPayload), }; }); } /** * Normalize raw elide time grains */ private normalizeTimeGrain(rawGrain: string): Grain { const grain = rawGrain.toLowerCase() as Grain | 'isoweek'; return 'isoweek' === grain ? 'isoWeek' : grain; } /** * @param timeDimensionId * @param grainNodes * @param dataSourceName * @returns new column function with the supported grains as parameters */ private createTimeGrainColumnFunction( timeDimensionId: string, grainNodes: TimeDimensionGrainNode[], dataSourceName: string ): ColumnFunctionMetadataPayload { const grainIds = grainNodes.map((g) => g.grain.toLowerCase()); const grains = grainIds.sort().join(','); const columnFunctionId = `${this.namespace}:timeGrain(column=${timeDimensionId};grains=${grains})`; let defaultValue; const { defaultTimeGrain } = this.clientConfig; if (defaultTimeGrain && grainIds.includes(defaultTimeGrain)) { defaultValue = defaultTimeGrain; } else { defaultValue = grainIds[0]; } return { id: columnFunctionId, name: 'Time Grain', source: dataSourceName, description: 'Time Grain', _parametersPayload: [ { id: 'grain', name: 'Time Grain', description: 'The time grain to group dates by', source: dataSourceName, defaultValue, valueType: DataType.TEXT, valueSourceType: ValueSourceType.ENUM, _localValues: grainNodes.map((grain) => { const grainName = grain.grain.toLowerCase(); return { id: grainName, description: upperFirst(grainName), name: grainName, }; }), }, ], }; } /** * Normalize column arguments as a column function */ private createColumnFunction( columnId: string, columnArguments: Connection<ElideArgument>, source: string ): ColumnFunctionMetadataModel | null { // do not create a column function if arguments are not present if (columnArguments.edges.length === 0) { return null; } const id = `${this.namespace}:elide-${source}:column=${columnId}`; const _parametersPayload: FunctionParameterMetadataPayload[] = columnArguments.edges.map(({ node }) => ({ id: node.name, name: node.name, description: node.description, source, valueType: node.type, valueSourceType: node.valueSourceType, tableSource: this.normalizeTableSource(node.tableSource?.edges?.[0]?.node), defaultValue: node.defaultValue, _localValues: node.values.map((v) => ({ id: v, name: v })), })); const payload: ColumnFunctionMetadataPayload = { id, name: 'Column Arguments', description: 'Column Arguments', source, _parametersPayload, }; return this.createColumnFunctionModel(payload); } /** * Normalizes elide table source to internal table source shape */ private normalizeTableSource(tableSource: ElideTableSource): TableSource | undefined { if (tableSource) { const valueSource = tableSource.valueSource.edges?.[0].node.id; return valueSource ? { valueSource } : undefined; } return undefined; } /** * Normalizes elide cardinalities to navi sizes */ _normalizeCardinality(elideCardinality?: ElideCardinality): Cardinality | undefined { const cardinality = elideCardinality?.toLowerCase() as Lowercase<ElideCardinality> | undefined; if (cardinality === 'tiny' || cardinality === 'small') { return CARDINALITY_SIZES[0]; } else if (cardinality === 'medium') { return CARDINALITY_SIZES[1]; } else if (cardinality === 'large' || cardinality === 'huge') { return CARDINALITY_SIZES[2]; } return undefined; } private supportedTypes = new Set<keyof MetadataModelMap>(['everything']); normalize<K extends keyof MetadataModelMap>( type: K, rawPayload: TablePayload, dataSourceName: string ): MetadataModelMap[K] { invariant( this.supportedTypes.has(type), `ElideMetadataSerializer only supports normalizing type: ${[...this.supportedTypes]}` ); if (rawPayload.error || !rawPayload.data) { throw new Error(rawPayload?.error?.message ?? 'Error Fetching Metadata'); } const normalized: MetadataModelMap['everything'] = this._normalizeTableConnection( rawPayload.data.table, dataSourceName ); return normalized as MetadataModelMap[K]; } }
the_stack
import { InanoSQLAdapter, InanoSQLTable, InanoSQLPlugin, InanoSQLInstance } from "@nano-sql/core/lib/interfaces"; import { generateID, deepSet, chainAsync, allAsync, blankTableDefinition } from "@nano-sql/core/lib/utilities"; import * as redis from "redis"; const noClient = `No Redis client!`; export class Redis implements InanoSQLAdapter { plugin: InanoSQLPlugin = { name: "Redis Adapter", version: 2.07 }; nSQL: InanoSQLInstance; private _id: string; private _db: redis.RedisClient; private _tableConfigs: { [tableName: string]: InanoSQLTable; } constructor(public connectArgs?: redis.ClientOpts, public getClient?: (redisClient: redis.RedisClient) => void) { this.connectArgs = this.connectArgs || {}; this._tableConfigs = {}; } connect(id: string, complete: () => void, error: (err: any) => void) { this._db = redis.createClient(this.connectArgs); this._db.on("ready", () => { if (!this._db) { error(noClient); return; } if (this.getClient) { this.getClient(this._db); } complete(); }); this._db.on("error", error); } key(tableName: string, key: any): string { return this._id + "." + tableName + "." + key; } createTable(tableName: string, tableData: InanoSQLTable, complete: () => void, error: (err: any) => void) { this._tableConfigs[tableName] = tableData; complete(); } dropTable(table: string, complete: () => void, error: (err: any) => void) { if (!this._db) { error(noClient); return; } this._db.del(this.key("_ai_", table), () => { // delete AI let ptr = "0"; const getNextPage = () => { if (!this._db) { error(noClient); return; } this._db.zscan(this.key("_index_", table), ptr, (err, result) => { if (err) { error(err); return; } if (!result[1].length && result[0] !== "0") { ptr = result[0]; getNextPage(); return; } const PKS = (result[1] || []).filter((v, i) => i % 2 === 0); chainAsync(PKS, (pk, i, next, err) => { if (!this._db) { error(noClient); return; } // clear table contents this._db.del(this.key(table, pk), (delErr) => { if (delErr) { err(delErr); return; } next(); }) }).then(() => { if (result[0] === "0") { if (!this._db) { error(noClient); return; } // done reading index, delete it this._db.del(this.key("_index_", table), (delErr) => { if (delErr) { error(delErr); return; } complete(); }); } else { ptr = result[0]; getNextPage(); } }).catch(error); }); } getNextPage(); }) } disconnect(complete: () => void, error: (err: any) => void) { if (!this._db) { error(noClient); return; } this._db.on("end", () => { this._db = undefined; complete(); }) this._db.quit(); } write(table: string, pk: any, row: { [key: string]: any }, complete: (pk: any) => void, error: (err: any) => void) { new Promise((res, rej) => { // get current auto incremenet value if (!this._db) { error(noClient); return; } if (this._tableConfigs[table].ai) { this._db.get(this.key("_ai_", table), (err, result) => { if (err) { rej(err); return; } res(parseInt(result) || 0); }); } else { res(0); } }).then((AI: number) => { pk = pk || generateID(this._tableConfigs[table].pkType, AI + 1); return new Promise((res, rej) => { if (!this._db) { error(noClient); return; } if (typeof pk === "undefined") { rej(new Error("Can't add a row without a primary key!")); return; } if (this._tableConfigs[table].ai && pk > AI) { // need to increment ai to database this._db.incr(this.key("_ai_", table), (err, result) => { if (err) { rej(err); return; } res(result || 0); }); } else { res(pk); } }); }).then((primaryKey: any) => { deepSet(this._tableConfigs[table].pkCol, row, primaryKey); return allAsync(["_index_", "_table_"], (item, i, next, err) => { if (!this._db) { error(noClient); return; } switch (item) { case "_index_": // update index this._db.zadd(this.key("_index_", table), this._tableConfigs[table].isPkNum ? parseFloat(primaryKey) : 0, primaryKey, (error) => { if (error) { err(error); return; } next(primaryKey); }); break; case "_table_": // update row value this._db.set(this.key(table, String(primaryKey)), JSON.stringify(row), (error) => { if (error) { err(error); return; } next(primaryKey); }); break; } }); }).then((result: any[]) => { complete(result[0]) }).catch(error); } read(table: string, pk: any, complete: (row: { [key: string]: any } | undefined) => void, error: (err: any) => void) { if (!this._db) { error(noClient); return; } this._db.get(this.key(table, String(pk)), (err, result) => { if (err) { error(err); return; } complete(result ? JSON.parse(result) : undefined); }) } readZIndex(table: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, complete: (index: any[]) => void, error: (err: any) => void): void { if (!this._db) { error(noClient); return; } switch (type) { case "offset": if (reverse) { this._db.zrevrange(this.key("_index_", table), offsetOrLow + 1, offsetOrLow + limitOrHigh, (err, results) => { if (err) { error(err); return; } complete(results); }); } else { this._db.zrange(this.key("_index_", table), offsetOrLow, offsetOrLow + limitOrHigh - 1, (err, results) => { if (err) { error(err); return; } complete(results); }); } break; case "all": this.getTableIndex(table, (index) => { if (reverse) { complete(index.reverse()); } else { complete(index); } }, error); break; case "range": if (this._tableConfigs[table].isPkNum) { this._db.zrangebyscore(this.key("_index_", table), offsetOrLow, limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } else { this._db.zrangebylex(this.key("_index_", table), "[" + offsetOrLow, "[" + limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } break; } } readMulti(table: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, onRow: (row: { [key: string]: any }, i: number) => void, complete: () => void, error: (err: any) => void) { this.readZIndex(table, type, offsetOrLow, limitOrHigh, reverse, (primaryKeys) => { let page = 0; // get the records in batches so we don't block redis const getPage = () => { if (!this._db) { error(noClient); return; } const PKS = primaryKeys.slice((page * 100), (page * 100) + 100); if (!PKS.length) { complete(); return; } this._db.mget(PKS.map(pk => this.key(table, pk)), (err, rows) => { if (err) { error(err); return; } rows.forEach((row, i) => { onRow(JSON.parse(row), i + (page * 500)) }); page++; getPage(); }); } getPage(); }, error); } delete(table: string, pk: any, complete: () => void, error: (err: any) => void) { allAsync(["_index_", "_table_"], (item, i, next, err) => { if (!this._db) { error(noClient); return; } switch (item) { case "_index_": // update index this._db.zrem(this.key("_index_", table), pk, (error) => { if (error) { err(error); return; } next(); }); break; case "_table_": // remove row value this._db.del(this.key(table, String(pk)), (error) => { if (error) { err(error); return; } next(); }); break; } }).then(complete).catch(error); } maybeMapIndex(table: string, index: any[]): any[] { if (this._tableConfigs[table].isPkNum) return index.map(i => parseFloat(i)); return index; } getTableIndex(table: string, complete: (index: any[]) => void, error: (err: any) => void) { let ptr = "0"; let index: any[] = []; if (!this._db) { error(noClient); return; } const cb = (err, result) => { if (err) { error(err); return; } complete(this.maybeMapIndex(table, result)); }; this._db.zrangebyscore(this.key("_index_", table), "-inf", "+inf", cb); } getTableIndexLength(table: string, complete: (length: number) => void, error: (err: any) => void) { let count: number = 0; if (!this._db) { error(noClient); return; } this._db.zcount(this.key("_index_", table), "-inf", "+inf", (err, result) => { if (err) { error(err); return; } complete(result); }); } createIndex(tableId: string, index: string, type: string, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; this.createTable(indexName, { ...blankTableDefinition, pkType: type, pkCol: ["id"], isPkNum: ["float", "int", "number"].indexOf(type) !== -1 }, () => { complete(); }, error); } deleteIndex(tableId: string, index: string, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; this.dropTable(indexName, complete, error); } addIndexValue(tableId: string, index: string, rowID: any, indexKey: any, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; if (!this._db) { error(noClient); return; } return allAsync(["_index_", "_table_"], (item, i, next, err) => { if (!this._db) { error(noClient); return; } switch (item) { case "_index_": // update index this._db.zadd(this.key("_index_", indexName), this._tableConfigs[indexName].isPkNum ? parseFloat(indexKey) : 0, indexKey, (error) => { if (error) { err(error); return; } next(); }); break; case "_table_": // update row value const isNum = typeof rowID === "number"; this._db.zadd(this.key(indexName, indexKey), 0, (isNum ? "num:" : "") + rowID, (error, result) => { if (error) { err(error); return; } next(); }); break; } }).then(complete).catch(error); } deleteIndexValue(tableId: string, index: string, rowID: any, indexKey: any, complete: () => void, error: (err: any) => void) { if (!this._db) { error(noClient); return; } const indexName = `_idx_${tableId}_${index}`; const isNum = typeof rowID === "number"; this._db.zrem(this.key(indexName, indexKey), (isNum ? "num:" : "") + rowID, (err, result) => { if (err) { error(err); return; } let cnt = 0; this.readIndexKey(tableId, index, indexKey, () => { cnt++; }, () => { if (cnt > 0) { complete(); } else { this._db.del(this.key(indexName, indexKey), (err, result) => { if (err) { error(err); return; } complete(); }); } }, error); }); } readIndexKey(tableId: string, index: string, indexKey: any, onRowPK: (pk: any) => void, complete: () => void, error: (err: any) => void) { if (!this._db) { error(noClient); return; } const indexName = `_idx_${tableId}_${index}`; this._db.zrangebylex(this.key(indexName, indexKey), "-", "+", (err, result) => { if (err) { error(err); return; } if (!result) { complete(); return; } result.forEach((value, i) => { onRowPK(value.indexOf("num:") === 0 ? parseFloat(value.replace("num:", "")) : value); }) complete(); }) } readIndexKeys(tableId: string, index: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, onRowPK: (key: any, id: any) => void, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; this.readZIndex(indexName, type, offsetOrLow, limitOrHigh, reverse, (primaryKeys) => { let page = 0; if (!this._db) { error(noClient); return; } chainAsync(primaryKeys, (indexKey, i, pkNext, pkErr) => { if (!this._db) { error(noClient); return; } this._db.zrangebylex(this.key(indexName, indexKey), "-", "+", (err, result) => { if (err) { error(err); return; } if (!result) { pkNext(); return; } result.forEach((value, i) => { onRowPK(value.indexOf("num:") === 0 ? parseFloat(value.replace("num:", "")) : value, i); }) pkNext(); }) }).then(() => { complete(); }) }, error); } }
the_stack
import { Column } from "../../entities/column"; import { RowNode } from "../../entities/rowNode"; import { Beans } from "./../beans"; import { Component } from "../../widgets/component"; import { ICellEditorComp, ICellEditorParams } from "../../interfaces/iCellEditor"; import { ICellRendererComp } from "./../cellRenderers/iCellRenderer"; import { CheckboxSelectionComponent } from "./../checkboxSelectionComponent"; import { RowCtrl } from "./../row/rowCtrl"; import { RowDragComp } from "./../row/rowDragComp"; import { PopupEditorWrapper } from "./../cellEditors/popupEditorWrapper"; import { DndSourceComp } from "./../dndSourceComp"; import { TooltipParentComp } from "../../widgets/customTooltipFeature"; import { setAriaColIndex, setAriaDescribedBy, setAriaSelected, setAriaExpanded, setAriaRole } from "../../utils/aria"; import { escapeString } from "../../utils/string"; import { missing } from "../../utils/generic"; import { addStylesToElement, clearElement, removeFromParent } from "../../utils/dom"; import { isBrowserIE } from "../../utils/browser"; import { CellCtrl, ICellComp } from "./cellCtrl"; import { UserCompDetails } from "../../components/framework/userComponentFactory"; import { _ } from "../../utils"; export class CellComp extends Component implements TooltipParentComp { private eCellWrapper: HTMLElement | null; private eCellValue: HTMLElement; private beans: Beans; private column: Column; private rowNode: RowNode; private eRow: HTMLElement; private includeSelection: boolean; private includeRowDrag: boolean; private includeDndSource: boolean; private forceWrapper: boolean; private checkboxSelectionComp: CheckboxSelectionComponent | undefined; private dndSourceComp: DndSourceComp | undefined; private rowDraggingComp: RowDragComp | undefined; private hideEditorPopup: Function | null | undefined; private cellEditorPopupWrapper: PopupEditorWrapper | undefined; private cellEditor: ICellEditorComp | null | undefined; private cellEditorGui: HTMLElement | null; private cellRenderer: ICellRendererComp | null | undefined; private cellRendererGui: HTMLElement | null; private cellRendererClass: any; private autoHeightCell: boolean; private rowCtrl: RowCtrl | null; private scope: any = null; private cellCtrl: CellCtrl; private firstRender: boolean; // for angular 1 only private angularCompiledElement: any; // every time we go into edit mode, or back again, this gets incremented. // it's the components way of dealing with the async nature of framework components, // so if a framework component takes a while to be created, we know if the object // is still relevant when creating is finished. eg we could click edit / un-edit 20 // times before the first React edit component comes back - we should discard // the first 19. private rendererVersion = 0; private editorVersion = 0; constructor(scope: any, beans: Beans, cellCtrl: CellCtrl, autoHeightCell: boolean, printLayout: boolean, eRow: HTMLElement, editingRow: boolean) { super(); this.scope = scope; this.beans = beans; this.column = cellCtrl.getColumn(); this.rowNode = cellCtrl.getRowNode(); this.rowCtrl = cellCtrl.getRowCtrl(); this.autoHeightCell = autoHeightCell; this.eRow = eRow; this.setTemplate(/* html */`<div comp-id="${this.getCompId()}"/>`); const eGui = this.getGui(); const style = eGui.style; this.eCellValue = eGui; const setAttribute = (name: string, value: string | null | undefined, element?: HTMLElement) => { const actualElement = element ? element : eGui; if (value != null && value != '') { actualElement.setAttribute(name, value); } else { actualElement.removeAttribute(name); } }; const compProxy: ICellComp = { addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on), setUserStyles: styles => addStylesToElement(eGui, styles), setAriaSelected: selected => setAriaSelected(eGui, selected), setAriaExpanded: selected => setAriaExpanded(eGui, selected), getFocusableElement: () => this.getFocusableElement(), setLeft: left => style.left = left, setWidth: width => style.width = width, setAriaColIndex: index => setAriaColIndex(this.getGui(), index), setHeight: height => style.height = height, setZIndex: zIndex => style.zIndex = zIndex, setTabIndex: tabIndex => setAttribute('tabindex', tabIndex.toString()), setRole: role => setAriaRole(eGui, role), setColId: colId => setAttribute('col-id', colId), setTitle: title => setAttribute('title', title), setUnselectable: value => setAttribute('unselectable', value, this.eCellValue), setTransition: transition => style.transition = transition ? transition : '', setIncludeSelection: include => this.includeSelection = include, setIncludeRowDrag: include => this.includeRowDrag = include, setIncludeDndSource: include => this.includeDndSource = include, setForceWrapper: force => this.forceWrapper = force, setRenderDetails: (compDetails, valueToDisplay, force) => this.setRenderDetails(compDetails, valueToDisplay, force), setEditDetails: (compDetails, popup, position) => this.setEditDetails(compDetails, popup, position), getCellEditor: () => this.cellEditor || null, getCellRenderer: () => this.cellRenderer || null, getParentOfValue: () => this.eCellValue }; this.cellCtrl = cellCtrl; cellCtrl.setComp(compProxy, this.scope, this.getGui(), printLayout, editingRow); } private setRenderDetails(compDetails: UserCompDetails | undefined, valueToDisplay: any, forceNewCellRendererInstance: boolean): void { // this can happen if the users asks for the cell to refresh, but we are not showing the vale as we are editing const isInlineEditing = this.cellEditor && !this.cellEditorPopupWrapper; if (isInlineEditing) { return; } // this means firstRender will be true for one pass only, as it's initialised to undefined this.firstRender = this.firstRender == null; const usingAngular1Template = this.isUsingAngular1Template(); // if display template has changed, means any previous Cell Renderer is in the wrong location const controlWrapperChanged = this.setupControlsWrapper(); // all of these have dependencies on the eGui, so only do them after eGui is set if (compDetails) { const neverRefresh = forceNewCellRendererInstance || controlWrapperChanged; const cellRendererRefreshSuccessful = neverRefresh ? false : this.refreshCellRenderer(compDetails); if (!cellRendererRefreshSuccessful) { this.destroyRenderer(); this.createCellRendererInstance(compDetails); } } else { this.destroyRenderer(); if (usingAngular1Template) { this.insertValueUsingAngular1Template(); } else { this.insertValueWithoutCellRenderer(valueToDisplay); } } this.cellCtrl.setupAutoHeight(this.getGui()); } private setEditDetails(compDetails: UserCompDetails | undefined, popup?: boolean, position?: string): void { if (compDetails) { this.createCellEditorInstance(compDetails, popup, position); } else { this.destroyEditor(); } } private removeControlsWrapper(): void { this.eCellValue = this.getGui(); this.eCellWrapper = null; this.checkboxSelectionComp = this.beans.context.destroyBean(this.checkboxSelectionComp); this.dndSourceComp = this.beans.context.destroyBean(this.dndSourceComp); this.rowDraggingComp = this.beans.context.destroyBean(this.rowDraggingComp); } // returns true if wrapper was changed private setupControlsWrapper(): boolean { const usingWrapper = this.includeRowDrag || this.includeDndSource || this.includeSelection || this.forceWrapper; const changed = true; const notChanged = false; this.addOrRemoveCssClass('ag-cell-value', !usingWrapper); // turn wrapper on if (usingWrapper && !this.eCellWrapper) { this.addControlsWrapper(); return changed; } // turn wrapper off if (!usingWrapper && this.eCellWrapper) { this.removeControlsWrapper(); return changed; } return notChanged; } private addControlsWrapper(): void { const eGui = this.getGui(); eGui.innerHTML = /* html */ `<div ref="eCellWrapper" class="ag-cell-wrapper" role="presentation"> <span ref="eCellValue" class="ag-cell-value" role="presentation"></span> </div>`; this.eCellValue = this.getRefElement('eCellValue'); this.eCellWrapper = this.getRefElement('eCellWrapper'); if (!this.forceWrapper) { this.eCellValue.setAttribute('unselectable', 'on'); } const id = this.eCellValue.id = `cell-${this.getCompId()}`; const describedByIds: string[] = []; if (this.includeRowDrag) { this.rowDraggingComp = this.cellCtrl.createRowDragComp(); if (this.rowDraggingComp) { // put the checkbox in before the value this.eCellWrapper!.insertBefore(this.rowDraggingComp.getGui(), this.eCellValue); } } if (this.includeDndSource) { this.dndSourceComp = this.cellCtrl.createDndSource(); // put the checkbox in before the value this.eCellWrapper!.insertBefore(this.dndSourceComp.getGui(), this.eCellValue); } if (this.includeSelection) { this.checkboxSelectionComp = this.cellCtrl.createSelectionCheckbox(); this.eCellWrapper!.insertBefore(this.checkboxSelectionComp.getGui(), this.eCellValue); describedByIds.push(this.checkboxSelectionComp.getCheckboxId()); } describedByIds.push(id); setAriaDescribedBy(this.getGui(), describedByIds.join(' ')); } private createCellEditorInstance(compDetails: UserCompDetails, popup?: boolean, position?: string): void { const versionCopy = this.editorVersion; const cellEditorPromise = this.beans.userComponentFactory.createInstanceFromCompDetails(compDetails); if (!cellEditorPromise) { return; } // if empty, userComponentFactory already did a console message const { params } = compDetails; cellEditorPromise.then(c => this.afterCellEditorCreated(versionCopy, c!, params, popup, position)); // if we don't do this, and editor component is async, then there will be a period // when the component isn't present and keyboard navigation won't work - so example // of user hitting tab quickly (more quickly than renderers getting created) won't work const cellEditorAsync = missing(this.cellEditor); if (cellEditorAsync && params.cellStartedEdit) { this.cellCtrl.focusCell(true); } } private insertValueWithoutCellRenderer(valueToDisplay: any): void { const escapedValue = valueToDisplay != null ? escapeString(valueToDisplay) : null; if (escapedValue != null) { this.eCellValue.innerHTML = escapedValue; } else { clearElement(this.eCellValue); } } private insertValueUsingAngular1Template(): void { const { template, templateUrl } = this.column.getColDef(); let templateToInsert: string | undefined = undefined; if (template != null) { templateToInsert = template; } else if (templateUrl != null) { // first time this happens it will return nothing, as the template will still be loading async, // however once loaded it will refresh the cell and second time around it will be returned sync // as in cache. templateToInsert = this.beans.templateService.getTemplate(templateUrl, () => this.cellCtrl.refreshCell({forceRefresh: true})); } else { // should never happen, as we only enter this method when template or templateUrl exist } if (templateToInsert!=null) { this.eCellValue.innerHTML = templateToInsert; this.updateAngular1ScopeAndCompile(); } } private destroyEditorAndRenderer(): void { this.destroyRenderer(); this.destroyEditor(); } private destroyRenderer(): void { const {context} = this.beans; this.cellRenderer = context.destroyBean(this.cellRenderer); removeFromParent(this.cellRendererGui); this.cellRendererGui = null; this.rendererVersion++; } private destroyEditor(): void { const {context} = this.beans; if (this.hideEditorPopup) { this.hideEditorPopup(); } this.hideEditorPopup = undefined; this.cellEditor = context.destroyBean(this.cellEditor); this.cellEditorPopupWrapper = context.destroyBean(this.cellEditorPopupWrapper); removeFromParent(this.cellEditorGui); this.cellEditorGui = null; this.editorVersion++; } private refreshCellRenderer(compClassAndParams: UserCompDetails): boolean { if (this.cellRenderer == null || this.cellRenderer.refresh == null) { return false; } // if different Cell Renderer configured this time (eg user is using selector, and // returns different component) then don't refresh, force recreate of Cell Renderer if (this.cellRendererClass !== compClassAndParams.componentClass) { return false; } // take any custom params off of the user const result = this.cellRenderer.refresh(compClassAndParams.params); // NOTE on undefined: previous version of the cellRenderer.refresh() interface // returned nothing, if the method existed, we assumed it refreshed. so for // backwards compatibility, we assume if method exists and returns nothing, // that it was successful. return result === true || result === undefined; } private createCellRendererInstance(compClassAndParams: UserCompDetails): void { // never use task service if angularCompileRows=true, as that assume the cell renderers // are finished when the row is created. also we never use it if animation frame service // is turned off. // and lastly we never use it if doing auto-height, as the auto-height service checks the // row height directly after the cell is created, it doesn't wait around for the tasks to complete const angularCompileRows = this.beans.gridOptionsWrapper.isAngularCompileRows(); const suppressAnimationFrame = this.beans.gridOptionsWrapper.isSuppressAnimationFrame(); const useTaskService = !angularCompileRows && !suppressAnimationFrame && !this.autoHeightCell; const displayComponentVersionCopy = this.rendererVersion; const {componentClass} = compClassAndParams; const createCellRendererFunc = () => { const staleTask = this.rendererVersion !== displayComponentVersionCopy || !this.isAlive(); if (staleTask) { return; } // this can return null in the event that the user has switched from a renderer component to nothing, for example // when using a cellRendererSelect to return a component or null depending on row data etc const componentPromise = this.beans.userComponentFactory.createInstanceFromCompDetails(compClassAndParams); const callback = this.afterCellRendererCreated.bind(this, displayComponentVersionCopy, componentClass); if (componentPromise) { componentPromise.then(callback); } }; // we only use task service when rendering for first time, which means it is not used when doing edits. // if we changed this (always use task service) would make sense, however it would break tests, possibly // test of users. if (useTaskService && this.firstRender) { this.beans.animationFrameService.createTask(createCellRendererFunc, this.rowNode.rowIndex!, 'createTasksP2'); } else { createCellRendererFunc(); } } private isUsingAngular1Template(): boolean { const colDef = this.column.getColDef(); const res = colDef.template != null || colDef.templateUrl != null; return res; } public getCtrl(): CellCtrl { return this.cellCtrl; } public getRowCtrl(): RowCtrl | null { return this.rowCtrl; } public getCellRenderer(): ICellRendererComp | null | undefined { return this.cellRenderer; } public getCellEditor(): ICellEditorComp | null | undefined { return this.cellEditor; } private afterCellRendererCreated(cellRendererVersion: number, cellRendererClass: any, cellRenderer: ICellRendererComp): void { const staleTask = !this.isAlive() || cellRendererVersion !== this.rendererVersion; if (staleTask) { this.beans.context.destroyBean(cellRenderer); return; } this.cellRenderer = cellRenderer; this.cellRendererClass = cellRendererClass; this.cellRendererGui = this.cellRenderer.getGui(); if (this.cellRendererGui != null) { clearElement(this.eCellValue); this.eCellValue.appendChild(this.cellRendererGui); this.updateAngular1ScopeAndCompile(); } } private afterCellEditorCreated(requestVersion: number, cellEditor: ICellEditorComp, params: ICellEditorParams, popup?: boolean, position?: string): void { // if editingCell=false, means user cancelled the editor before component was ready. // if versionMismatch, then user cancelled the edit, then started the edit again, and this // is the first editor which is now stale. const staleComp = requestVersion !== this.editorVersion; if (staleComp) { this.beans.context.destroyBean(cellEditor); return; } const editingCancelledByUserComp = cellEditor.isCancelBeforeStart && cellEditor.isCancelBeforeStart(); if (editingCancelledByUserComp) { this.beans.context.destroyBean(cellEditor); this.cellCtrl.stopEditing(); return; } if (!cellEditor.getGui) { console.warn(`AG Grid: cellEditor for column ${this.column.getId()} is missing getGui() method`); this.beans.context.destroyBean(cellEditor); return; } this.cellEditor = cellEditor; this.cellEditorGui = cellEditor.getGui(); const cellEditorInPopup = popup || (cellEditor.isPopup !== undefined && cellEditor.isPopup()); if (cellEditorInPopup) { if (!popup) { this.cellCtrl.hackSayEditingInPopup(); } this.addPopupCellEditor(params, position); } else { this.addInCellEditor(); } if (cellEditor.afterGuiAttached) { cellEditor.afterGuiAttached(); } } private addInCellEditor(): void { const eGui = this.getGui(); // if focus is inside the cell, we move focus to the cell itself // before removing it's contents, otherwise errors could be thrown. if (eGui.contains(document.activeElement)) { eGui.focus(); } this.destroyRenderer(); this.removeControlsWrapper(); this.clearCellElement(); if (this.cellEditorGui) { eGui.appendChild(this.cellEditorGui); } } private addPopupCellEditor(params: ICellEditorParams, position?: string): void { if (this.beans.gridOptionsWrapper.isFullRowEdit()) { console.warn('AG Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both ' + '- either turn off fullRowEdit, or stop using popup editors.'); } const cellEditor = this.cellEditor!; // if a popup, then we wrap in a popup editor and return the popup this.cellEditorPopupWrapper = this.beans.context.createBean(new PopupEditorWrapper(params)); const ePopupGui = this.cellEditorPopupWrapper.getGui(); if (this.cellEditorGui) { ePopupGui.appendChild(this.cellEditorGui); } const popupService = this.beans.popupService; const useModelPopup = this.beans.gridOptionsWrapper.isStopEditingWhenCellsLoseFocus(); // see if position provided by colDef, if not then check old way of method on cellComp const positionToUse = position != null ? position : cellEditor.getPopupPosition ? cellEditor.getPopupPosition() : 'over'; const positionParams = { column: this.column, rowNode: this.rowNode, type: 'popupCellEditor', eventSource: this.getGui(), ePopup: ePopupGui, keepWithinBounds: true }; const positionCallback = position === 'under' ? popupService.positionPopupUnderComponent.bind(popupService, positionParams) : popupService.positionPopupOverComponent.bind(popupService, positionParams); const translate = this.beans.gridOptionsWrapper.getLocaleTextFunc(); const addPopupRes = popupService.addPopup({ modal: useModelPopup, eChild: ePopupGui, closeOnEsc: true, closedCallback: () => { this.cellCtrl.onPopupEditorClosed(); }, anchorToElement: this.getGui(), positionCallback, ariaLabel: translate('ariaLabelCellEditor', 'Cell Editor') }); if (addPopupRes) { this.hideEditorPopup = addPopupRes.hideFunc; } } public detach(): void { this.eRow.removeChild(this.getGui()); } // if the row is also getting destroyed, then we don't need to remove from dom, // as the row will also get removed, so no need to take out the cells from the row // if the row is going (removing is an expensive operation, so only need to remove // the top part) // // note - this is NOT called by context, as we don't wire / unwire the CellComp for performance reasons. public destroy(): void { this.cellCtrl.stopEditing(); this.destroyEditorAndRenderer(); this.removeControlsWrapper(); if (this.angularCompiledElement) { this.angularCompiledElement.remove(); this.angularCompiledElement = undefined; } super.destroy(); } private clearCellElement(): void { const eGui = this.getGui(); // if focus is inside the cell, we move focus to the cell itself // before removing it's contents, otherwise errors could be thrown. if (eGui.contains(document.activeElement) && !isBrowserIE()) { eGui.focus({ preventScroll: true }); } clearElement(eGui); } private updateAngular1ScopeAndCompile() { if (this.beans.gridOptionsWrapper.isAngularCompileRows() && this.scope) { this.scope.data = { ...this.rowNode.data }; if (this.angularCompiledElement) { this.angularCompiledElement.remove(); } this.angularCompiledElement = this.beans.$compile(this.eCellValue.children)(this.scope); // because this.scope is set, we are guaranteed GridBodyComp is vanilla JS, ie it's GridBodyComp.ts from AG Stack and and not react this.beans.ctrlsService.getGridBodyCtrl().requestAngularApply(); } } }
the_stack
import { Prim, Expr, StringLiteral, IntLiteral } from "./micheline"; import { decodeBase58Check, encodeBase58Check } from "./base58"; import { MichelsonData, MichelsonDataPair, MichelsonType, MichelsonTypePair } from "./michelson-types"; export type Tuple<N extends number, T> = N extends 1 ? [T] : N extends 2 ? [T, T] : N extends 3 ? [T, T, T] : N extends 4 ? [T, T, T, T] : N extends 5 ? [T, T, T, T, T] : N extends 6 ? [T, T, T, T, T, T] : N extends 7 ? [T, T, T, T, T, T, T] : N extends 8 ? [T, T, T, T, T, T, T, T] : T[]; type RequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>; type OmitProp<T, K extends keyof T> = Omit<T, K> & { [P in K]?: undefined }; export type ReqArgs<T extends Prim> = RequiredProp<T, "args">; export type NoArgs<T extends Prim> = OmitProp<T, "args">; export type NoAnnots<T extends Prim> = OmitProp<T, "annots">; export type Nullable<T> = { [P in keyof T]: T[P] | null }; export class MichelsonError<T extends Expr = Expr> extends Error { /** * @param val Value of a AST node caused the error * @param path Path to a node caused the error * @param message An error message */ constructor(public val: T, message?: string) { super(message); Object.setPrototypeOf(this, MichelsonError.prototype); } } export function isMichelsonError<T extends Expr = Expr>(err: any): err is MichelsonError<T> { return err instanceof MichelsonError; } export class MichelsonTypeError extends MichelsonError<MichelsonType | MichelsonType[]> { public data?: Expr; /** * @param val Value of a type node caused the error * @param data Value of a data node caused the error * @param message An error message */ constructor(val: MichelsonType | MichelsonType[], data?: Expr, message?: string) { super(val, message); if (data !== undefined) { this.data = data; } Object.setPrototypeOf(this, MichelsonTypeError.prototype); } } // Ad hoc big integer parser export class LongInteger { private neg = false; private buf: number[] = []; private append(c: number) { let i = 0; while (c !== 0 || i < this.buf.length) { const m = (this.buf[i] || 0) * 10 + c; this.buf[i++] = m % 256; c = Math.floor(m / 256); } } constructor(arg?: string | number) { if (arg === undefined) { return; } if (typeof arg === "string") { for (let i = 0; i < arg.length; i++) { let c = arg.charCodeAt(i); if (i === 0 && c === 0x2d) { this.neg = true; } else { if (c < 0x30 || c > 0x39) { throw new Error(`unexpected character in integer constant: ${arg[i]}`); } this.append(c - 0x30); } } } else if (arg < 0) { this.neg = true; this.append(-arg); } else { this.append(arg); } } cmp(arg: LongInteger): number { if (this.neg !== arg.neg) { return (arg.neg ? 1 : 0) - (this.neg ? 1 : 0); } else { let ret = 0; if (this.buf.length !== arg.buf.length) { ret = this.buf.length < arg.buf.length ? -1 : 1; } else if (this.buf.length !== 0) { let i = arg.buf.length - 1; while (i >= 0 && this.buf[i] === arg.buf[i]) { i--; } ret = i < 0 ? 0 : this.buf[i] < arg.buf[i] ? -1 : 1; } return !this.neg ? ret : ret === 0 ? 0 : -ret; } } get sign(): number { return this.buf.length === 0 ? 0 : this.neg ? -1 : 1; } } export function parseBytes(s: string): number[] | null { const ret: number[] = []; for (let i = 0; i < s.length; i += 2) { const x = parseInt(s.slice(i, i + 2), 16); if (Number.isNaN(x)) { return null; } ret.push(x); } return ret; } export function compareBytes(a: number[] | Uint8Array, b: number[] | Uint8Array): number { if (a.length !== b.length) { return a.length < b.length ? -1 : 1; } else if (a.length !== 0) { let i = 0; while (i < a.length && a[i] === b[i]) { i++; } return i === a.length ? 0 : a[i] < b[i] ? -1 : 1; } else { return 0; } } export function isDecimal(x: string): boolean { try { // tslint:disable-next-line: no-unused-expression new LongInteger(x); return true; } catch { return false; } } export function isNatural(x: string): boolean { try { return new LongInteger(x).sign >= 0; } catch { return false; } } export interface UnpackedAnnotations { f?: string[]; t?: string[]; v?: string[]; } export interface UnpackAnnotationsOptions { specialVar?: boolean; // CAR, CDR emptyVar?: boolean; specialFields?: boolean; // PAIR, LEFT, RIGHT emptyFields?: boolean; } const annRe = /^(@%|@%%|%@|[@:%]([_0-9a-zA-Z][_0-9a-zA-Z\.%@]*)?)$/; export function unpackAnnotations(p: Prim | Expr[], opt?: UnpackAnnotationsOptions): UnpackedAnnotations { if (Array.isArray(p)) { return {}; } let field: string[] | undefined; let type: string[] | undefined; let vars: string[] | undefined; if (p.annots !== undefined) { for (const v of p.annots) { if (v.length !== 0) { if (!annRe.test(v) || (!opt?.specialVar && (v === "@%" || v === "@%%")) || (!opt?.specialFields && v === "%@")) { throw new MichelsonError(p, `${p.prim}: unexpected annotation: ${v}`); } switch (v[0]) { case "%": if (opt?.emptyFields || v.length > 1) { field = field || []; field.push(v); } break; case ":": if (v.length > 1) { type = type || []; type.push(v); } break; case "@": if (opt?.emptyVar || v.length > 1) { vars = vars || []; vars.push(v); } break; } } } } return { f: field, t: type, v: vars }; } export type TezosIDType = "BlockHash" | "OperationHash" | "OperationListHash" | "OperationListListHash" | "ProtocolHash" | "ContextHash" | "ED25519PublicKeyHash" | "SECP256K1PublicKeyHash" | "P256PublicKeyHash" | "ContractHash" | "CryptoboxPublicKeyHash" | "ED25519Seed" | "ED25519PublicKey" | "SECP256K1SecretKey" | "P256SecretKey" | "ED25519EncryptedSeed" | "SECP256K1EncryptedSecretKey" | "P256EncryptedSecretKey" | "SECP256K1PublicKey" | "P256PublicKey" | "SECP256K1Scalar" | "SECP256K1Element" | "ED25519SecretKey" | "ED25519Signature" | "SECP256K1Signature" | "P256Signature" | "GenericSignature" | "ChainID"; export type TezosIDPrefix = [number, number[]]; // payload length, prefix export const tezosPrefix: Record<TezosIDType, TezosIDPrefix> = { BlockHash: [32, [1, 52]], // B(51) OperationHash: [32, [5, 116]], // o(51) OperationListHash: [32, [133, 233]], // Lo(52) OperationListListHash: [32, [29, 159, 109]], // LLo(53) ProtocolHash: [32, [2, 170]], // P(51) ContextHash: [32, [79, 199]], // Co(52) ED25519PublicKeyHash: [20, [6, 161, 159]], // tz1(36) SECP256K1PublicKeyHash: [20, [6, 161, 161]], // tz2(36) P256PublicKeyHash: [20, [6, 161, 164]], // tz3(36) ContractHash: [20, [2, 90, 121]], // KT1(36) CryptoboxPublicKeyHash: [16, [153, 103]], // id(30) ED25519Seed: [32, [13, 15, 58, 7]], // edsk(54) ED25519PublicKey: [32, [13, 15, 37, 217]], // edpk(54) SECP256K1SecretKey: [32, [17, 162, 224, 201]], // spsk(54) P256SecretKey: [32, [16, 81, 238, 189]], // p2sk(54) ED25519EncryptedSeed: [56, [7, 90, 60, 179, 41]], // edesk(88) SECP256K1EncryptedSecretKey: [56, [9, 237, 241, 174, 150]], // spesk(88) P256EncryptedSecretKey: [56, [9, 48, 57, 115, 171]], // p2esk(88) SECP256K1PublicKey: [33, [3, 254, 226, 86]], // sppk(55) P256PublicKey: [33, [3, 178, 139, 127]], // p2pk(55) SECP256K1Scalar: [33, [38, 248, 136]], // SSp(53) SECP256K1Element: [33, [5, 92, 0]], // GSp(54) ED25519SecretKey: [64, [43, 246, 78, 7]], // edsk(98) ED25519Signature: [64, [9, 245, 205, 134, 18]], // edsig(99) SECP256K1Signature: [64, [13, 115, 101, 19, 63]], // spsig1(99) P256Signature: [64, [54, 240, 44, 52]], // p2sig(98) GenericSignature: [64, [4, 130, 43]], // sig(96) ChainID: [4, [87, 82, 0]], }; export function checkDecodeTezosID<T extends TezosIDType[]>(id: string, ...types: T): [T[number], number[]] | null { const buf = decodeBase58Check(id); for (const t of types) { const [plen, p] = tezosPrefix[t]; if (buf.length === plen + p.length) { let i = 0; while (i < p.length && buf[i] === p[i]) { i++; } if (i === p.length) { return [t, buf.slice(p.length)]; } } } return null; } export function encodeTezosID(id: TezosIDType, data: number[] | Uint8Array): string { const [plen, p] = tezosPrefix[id]; if (data.length !== plen) { throw new Error(`incorrect data length for ${id}: ${data.length}`); } return encodeBase58Check([...p, ...data]); } // reassemble comb pair for transparent comparison etc. non-recursive! type PairTypeOrDataPrim<I extends "pair" | "Pair"> = I extends "pair" ? Extract<MichelsonTypePair<MichelsonType[]>, Prim> : Extract<MichelsonDataPair<MichelsonData[]>, Prim>; export function unpackComb<I extends "pair" | "Pair">(id: I, v: I extends "pair" ? MichelsonTypePair<MichelsonType[]> : MichelsonDataPair<MichelsonData[]>): PairTypeOrDataPrim<I> { const vv: MichelsonTypePair<MichelsonType[]> | MichelsonDataPair<MichelsonData[]> = v; const args = Array.isArray(vv) ? vv : vv.args; if (args.length === 2) { // it's a way to make a union of two interfaces not an interface with two independent properties of union types const ret = id === "pair" ? { prim: "pair", args, } : { prim: "Pair", args, }; return ret as PairTypeOrDataPrim<I>; } return { ...(Array.isArray(vv) ? { prim: id } : vv), args: [ args[0], { prim: id, args: args.slice(1), }, ], } as PairTypeOrDataPrim<I>; } export function isPairType(t: MichelsonType): t is MichelsonTypePair<MichelsonType[]> { return Array.isArray(t) || t.prim === "pair"; } export function isPairData(d: Expr): d is MichelsonDataPair<MichelsonData[]> { return Array.isArray(d) || "prim" in d && d.prim === "Pair"; } const rfc3339Re = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])[T ]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):([0-5][0-9]))$/; export function parseDate(a: StringLiteral | IntLiteral): Date | null { if ("string" in a) { if (isNatural(a.string)) { return new Date(parseInt(a.string, 10)); } else if (rfc3339Re.test(a.string)) { const x = new Date(a.string); if (!Number.isNaN(x.valueOf)) { return x; } } } else if (isNatural(a.int)) { return new Date(parseInt(a.int, 10)); } return null; } export function parseHex(s: string): number[] { const res: number[] = []; for (let i = 0; i < s.length; i += 2) { const ss = s.slice(i, i + 2); const x = parseInt(ss, 16); if (Number.isNaN(x)) { throw new Error(`can't parse hex byte: ${ss}`); } res.push(x); } return res; } export function hexBytes(bytes: number[]): string { return bytes.map(x => ((x >> 4) & 0xf).toString(16) + (x & 0xf).toString(16)).join(""); }
the_stack
import mermaid from 'mermaid'; import moment from 'moment'; import { DurableOrchestrationStatus, HistoryEvent } from '../DurableOrchestrationStatus'; import { MermaidDiagramTabState } from './MermaidDiagramTabState'; import { CancelToken } from '../../CancelToken'; import { dfmContextInstance } from '../../DfmContext'; type LineTextAndMetadata = { nextLine: string, functionName?: string, instanceId?: string, parentInstanceId?: string, duration?: number, widthPercentage?: number }; // State of Gantt Diagram tab on OrchestrationDetails view export class GanttDiagramTabState extends MermaidDiagramTabState { readonly name: string = "Gantt Chart"; protected buildDiagram(details: DurableOrchestrationStatus, history: HistoryEvent[], cancelToken: CancelToken): Promise<void> { return new Promise<void>((resolve, reject) => { Promise.all(this.renderOrchestration(details.instanceId, details.name, history, true)).then(arrayOfArrays => { if (cancelToken.isCancelled) { resolve(); return; } const lines = arrayOfArrays.flat(); const linesWithMetadata = lines.filter(l => !!l.functionName); this._diagramCode = 'gantt \n' + `title ${details.name}(${details.instanceId}) \n` + 'dateFormat YYYY-MM-DDTHH:mm:ss.SSS \n' + lines.map(item => item.nextLine).join(''); // Very much unknown, why this line is needed. Without it sometimes the diagrams fail to re-render this._diagramSvg = ''; try { mermaid.render('mermaidSvgId', this._diagramCode, (svg) => { svg = this.injectFunctionNameAttributes(svg, linesWithMetadata); svg = this.adjustIntervalsSmallerThanOneSecond(svg, linesWithMetadata); this._diagramSvg = svg; resolve(); }); } catch (err) { reject(err); } }, reject); }); } // Adds data-function-name attributes to diagram lines, so that Function names can be further used by rendering private injectFunctionNameAttributes(svg: string, linesWithMetadata: LineTextAndMetadata[]): string { return svg.replace(new RegExp(`<(rect|text) id="task([0-9]+)(-text)?"`, 'gi'), (match, tagName, taskIndex) => { const oneBasedLineIndex = parseInt(taskIndex); if (oneBasedLineIndex <= 0 || oneBasedLineIndex > linesWithMetadata.length) { return match; } const lineMetadata = linesWithMetadata[oneBasedLineIndex - 1]; if (!lineMetadata.functionName) { return match; } return match + ` data-function-name="${lineMetadata.functionName}"`; }); } // Workaround for mermaid being unable to render intervals shorter than 1 second private adjustIntervalsSmallerThanOneSecond(svg: string, linesWithMetadata: LineTextAndMetadata[]): string { return svg.replace(new RegExp(`<rect id="task([0-9]+)" [^>]+ width="([0-9]+)"`, 'gi'), (match, taskIndex, activityWidth) => { const oneBasedLineIndex = parseInt(taskIndex); if (oneBasedLineIndex <= 0 || oneBasedLineIndex > linesWithMetadata.length) { return match; } const activityMetadata = linesWithMetadata[oneBasedLineIndex - 1]; if (!activityMetadata.parentInstanceId || !activityMetadata.widthPercentage || (activityMetadata.duration > 10000)) { return match; } // now we need to figure out the width (in pixels) of parent orchestration line const orchIndex = linesWithMetadata.findIndex(l => l.instanceId === activityMetadata.parentInstanceId); if (orchIndex < 0) { return match; } const orchMatch = new RegExp(`<rect id="task${orchIndex + 1}" [^>]+ width="([0-9]+)"`, 'i').exec(svg); if (!orchMatch) { return match; } const orchWidth = parseInt(orchMatch[1]); const newActivityWidth = activityMetadata.widthPercentage > 1 ? orchWidth : Math.ceil(orchWidth * activityMetadata.widthPercentage); return match.replace(`width="${activityWidth}"`, `width="${newActivityWidth.toFixed(0)}"`) }); } private renderOrchestration(orchestrationId: string, orchestrationName: string, historyEvents: HistoryEvent[], isParentOrchestration: boolean): Promise<LineTextAndMetadata[]>[] { const results: Promise<LineTextAndMetadata[]>[] = []; const startedEvent = historyEvents.find(event => event.EventType === 'ExecutionStarted'); const completedEvent = historyEvents.find(event => event.EventType === 'ExecutionCompleted'); var needToAddAxisFormat = isParentOrchestration; var nextLine: string; var orchDuration = 0; if (!!startedEvent && !!completedEvent) { if (needToAddAxisFormat) { const longerThanADay = completedEvent.DurationInMs > 86400000; nextLine = longerThanADay ? 'axisFormat %Y-%m-%d %H:%M \n' : 'axisFormat %H:%M:%S \n'; results.push(Promise.resolve([{ nextLine }])); needToAddAxisFormat = false; } nextLine = isParentOrchestration ? '' : `section ${orchestrationName}(${this.escapeTitle(orchestrationId)}) \n`; var lineName = this.formatDuration(completedEvent.DurationInMs); if (!lineName) { lineName = this.formatLineName(orchestrationName); } nextLine += `${lineName}: ${isParentOrchestration ? '' : 'active,'} ${this.formatDateTime(startedEvent.Timestamp)}, ${this.formatDurationInSeconds(completedEvent.DurationInMs)} \n`; results.push(Promise.resolve([{ nextLine, functionName: orchestrationName, instanceId: orchestrationId }])); orchDuration = completedEvent.DurationInMs; } if (needToAddAxisFormat) { nextLine = 'axisFormat %H:%M:%S \n'; results.push(Promise.resolve([{ nextLine }])); } for (var event of historyEvents) { var eventTimestamp = event.ScheduledTime; // Sometimes activity timestamp might appear to be earlier than orchestration start (due to machine time difference, I assume), // and that breaks the diagram if (!!startedEvent && (Date.parse(eventTimestamp) < Date.parse(startedEvent.Timestamp))) { eventTimestamp = startedEvent.Timestamp; } switch (event.EventType) { case 'SubOrchestrationInstanceCompleted': case 'SubOrchestrationInstanceFailed': if (!!event.SubOrchestrationId) { const subOrchestrationId = event.SubOrchestrationId; const subOrchestrationName = event.FunctionName; results.push(new Promise<LineTextAndMetadata[]>((resolve, reject) => { this._loadHistory(subOrchestrationId).then(history => { Promise.all(this.renderOrchestration(subOrchestrationId, subOrchestrationName, history, false)).then(sequenceLines => { resolve(sequenceLines.flat()); }, reject); }, err => { console.log(`Failed to load ${subOrchestrationName}. ${err.message}`); resolve([{ nextLine: `%% Failed to load ${this.formatLineName(subOrchestrationName)}. ${err.message} \n` }]); }); })); nextLine = `section ${orchestrationName}(${this.escapeTitle(orchestrationId)}) \n`; results.push(Promise.resolve([{ nextLine }])); } break; case 'TaskCompleted': nextLine = `${this.formatLineName(event.FunctionName)} ${this.formatDuration(event.DurationInMs)}: done, ${this.formatDateTime(eventTimestamp)}, ${this.formatDurationInSeconds(event.DurationInMs)} \n`; results.push(Promise.resolve([{ nextLine, functionName: event.FunctionName, parentInstanceId: orchestrationId, duration: event.DurationInMs, widthPercentage: orchDuration ? event.DurationInMs / orchDuration : 0 }])); break; case 'TaskFailed': nextLine = `${this.formatLineName(event.FunctionName)} ${this.formatDuration(event.DurationInMs)}: crit, ${this.formatDateTime(eventTimestamp)}, ${this.formatDurationInSeconds(event.DurationInMs)} \n`; results.push(Promise.resolve([{ nextLine, functionName: event.FunctionName, parentInstanceId: orchestrationId, duration: event.DurationInMs, widthPercentage: orchDuration ? event.DurationInMs / orchDuration : 0 }])); break; case 'TimerFired': nextLine = `[TimerFired]: done, ${this.formatDateTime(event.Timestamp)}, 1s \n`; results.push(Promise.resolve([{ nextLine, functionName: orchestrationName, parentInstanceId: orchestrationId, duration: 1, widthPercentage: 0.0001 }])); break; } } return results; } private formatDateTime(utcDateTimeString: string): string { if (!dfmContextInstance.showTimeAsLocal) { return utcDateTimeString.substr(0, 23); } return moment(utcDateTimeString).format('YYYY-MM-DDTHH:mm:ss.SSS') } private formatLineName(name: string): string { return name.replace(/:/g, '-'); } }
the_stack
import { Nullable } from "../../types"; import { Scene } from "../../scene"; import { Matrix, Vector3, Vector4 } from "../../Maths/math.vector"; import { Color4 } from '../../Maths/math.color'; import { Mesh, _CreationDataStorage } from "../mesh"; import { VertexData } from "../mesh.vertexData"; import { CreateTiledPlaneVertexData } from "./tiledPlaneBuilder"; /** * Creates the VertexData for a tiled box * @param options an object used to set the following optional parameters for the box, required but can be empty * * faceTiles sets the pattern, tile size and number of tiles for a face * * faceUV an array of 6 Vector4 elements used to set different images to each box side * * faceColors an array of 6 Color3 elements used to set different colors to each box side * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * @returns the VertexData of the box */ export function CreateTiledBoxVertexData(options: { pattern?: number, size?: number, width?: number, height?: number, depth?: number, tileSize?: number, tileWidth?: number, tileHeight?: number, faceUV?: Vector4[], faceColors?: Color4[], alignHorizontal?: number, alignVertical?: number, sideOrientation?: number }): VertexData { var nbFaces = 6; var faceUV: Vector4[] = options.faceUV || new Array<Vector4>(6); var faceColors = options.faceColors; var flipTile = options.pattern || Mesh.NO_FLIP; var width = options.width || options.size || 1; var height = options.height || options.size || 1; var depth = options.depth || options.size || 1; var tileWidth = options.tileWidth || options.tileSize || 1; var tileHeight = options.tileHeight || options.tileSize || 1; var alignH = options.alignHorizontal || 0; var alignV = options.alignVertical || 0; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; // default face colors and UV if undefined for (var f = 0; f < nbFaces; f++) { if (faceUV[f] === undefined) { faceUV[f] = new Vector4(0, 0, 1, 1); } if (faceColors && faceColors[f] === undefined) { faceColors[f] = new Color4(1, 1, 1, 1); } } var halfWidth = width / 2; var halfHeight = height / 2; var halfDepth = depth / 2; var faceVertexData: Array<VertexData> = []; for (var f = 0; f < 2; f++) { //front and back faceVertexData[f] = CreateTiledPlaneVertexData({ pattern: flipTile, tileWidth: tileWidth, tileHeight: tileHeight, width: width, height: height, alignVertical: alignV, alignHorizontal: alignH, sideOrientation: sideOrientation }); } for (var f = 2; f < 4; f++) { //sides faceVertexData[f] = CreateTiledPlaneVertexData({ pattern: flipTile, tileWidth: tileWidth, tileHeight: tileHeight, width: depth, height: height, alignVertical: alignV, alignHorizontal: alignH, sideOrientation: sideOrientation }); } var baseAlignV = alignV; if (alignV === Mesh.BOTTOM) { baseAlignV = Mesh.TOP; } else if (alignV === Mesh.TOP) { baseAlignV = Mesh.BOTTOM; } for (var f = 4; f < 6; f++) { //top and bottom faceVertexData[f] = CreateTiledPlaneVertexData({ pattern: flipTile, tileWidth: tileWidth, tileHeight: tileHeight, width: width, height: depth, alignVertical: baseAlignV, alignHorizontal: alignH, sideOrientation: sideOrientation }); } var positions: Array<number> = []; var normals: Array<number> = []; var uvs: Array<number> = []; var indices: Array<number> = []; var colors: Array<number> = []; var facePositions: Array<Array<Vector3>> = []; var faceNormals: Array<Array<Vector3>> = []; var newFaceUV: Array<Array<number>> = []; var len: number = 0; var lu: number = 0; var li: number = 0; for (var f = 0; f < nbFaces; f++) { var len = faceVertexData[f].positions!.length; facePositions[f] = []; faceNormals[f] = []; for (var p = 0; p < len / 3; p++) { facePositions[f].push(new Vector3(faceVertexData[f].positions![3 * p], faceVertexData[f].positions![3 * p + 1], faceVertexData[f].positions![3 * p + 2])); faceNormals[f].push(new Vector3(faceVertexData[f].normals![3 * p], faceVertexData[f].normals![3 * p + 1], faceVertexData[f].normals![3 * p + 2])); } // uvs lu = faceVertexData[f].uvs!.length; newFaceUV[f] = []; for (var i = 0; i < lu; i += 2) { newFaceUV[f][i] = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * faceVertexData[f].uvs![i]; newFaceUV[f][i + 1] = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * faceVertexData[f].uvs![i + 1]; } uvs = uvs.concat(newFaceUV[f]); indices = indices.concat(<Array<number>>faceVertexData[f].indices!.map((x: number) => x + li)); li += facePositions[f].length; if (faceColors) { for (var c = 0; c < 4; c++) { colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); } } } var vec0 = new Vector3(0, 0, halfDepth); var mtrx0 = Matrix.RotationY(Math.PI); positions = facePositions[0].map((entry) => Vector3.TransformNormal(entry, mtrx0).add(vec0)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] ); normals = faceNormals[0].map((entry) => Vector3.TransformNormal(entry, mtrx0)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] ); positions = positions.concat(facePositions[1].map((entry) => entry.subtract(vec0)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); normals = normals.concat(faceNormals[1].map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); var vec2 = new Vector3(halfWidth, 0, 0); var mtrx2 = Matrix.RotationY(-Math.PI / 2); positions = positions.concat(facePositions[2].map((entry) => Vector3.TransformNormal(entry, mtrx2).add(vec2)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); normals = normals.concat(faceNormals[2].map((entry) => Vector3.TransformNormal(entry, mtrx2)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); var mtrx3 = Matrix.RotationY(Math.PI / 2); positions = positions.concat(facePositions[3].map((entry) => Vector3.TransformNormal(entry, mtrx3).subtract(vec2)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); normals = normals.concat(faceNormals[3].map((entry) => Vector3.TransformNormal(entry, mtrx3)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); var vec4 = new Vector3(0, halfHeight, 0); var mtrx4 = Matrix.RotationX(Math.PI / 2); positions = positions.concat(facePositions[4].map((entry) => Vector3.TransformNormal(entry, mtrx4).add(vec4)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); normals = normals.concat(faceNormals[4].map((entry) => Vector3.TransformNormal(entry, mtrx4)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); var mtrx5 = Matrix.RotationX(-Math.PI / 2); positions = positions.concat(facePositions[5].map((entry) => Vector3.TransformNormal(entry, mtrx5).subtract(vec4)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); normals = normals.concat(faceNormals[5].map((entry) => Vector3.TransformNormal(entry, mtrx5)).map((entry) => [entry.x, entry.y, entry.z]).reduce( (accumulator: Array<number>, currentValue) => accumulator.concat(currentValue), [] )); // sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; if (faceColors) { var totalColors = (sideOrientation === VertexData.DOUBLESIDE) ? colors.concat(colors) : colors; vertexData.colors = totalColors; } return vertexData; } /** * Creates a box mesh * faceTiles sets the pattern, tile size and number of tiles for a face * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) * * Please read this tutorial : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the box mesh */ export function CreateTiledBox(name: string, options: { pattern?: number, width?: number, height?: number, depth?: number, tileSize?: number, tileWidth?: number, tileHeight?: number, alignHorizontal?: number, alignVertical?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, updatable?: boolean }, scene: Nullable<Scene> = null): Mesh { var box = new Mesh(name, scene); options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); box._originalBuilderSideOrientation = options.sideOrientation; var vertexData = CreateTiledBoxVertexData(options); vertexData.applyToMesh(box, options.updatable); return box; } /** * Class containing static functions to help procedurally build meshes * @deprecated use CreateTildeBox instead */ export const TiledBoxBuilder = { CreateTiledBox }; VertexData.CreateTiledBox = CreateTiledBoxVertexData;
the_stack
import * as React from 'react'; import { classNamesFunction, css, KeyCodes, getRTL, initializeComponentRef } from '@fluentui/utilities'; import { AnimationDirection } from '../Calendar/Calendar.types'; import { CalendarDayGrid } from '../CalendarDayGrid/CalendarDayGrid'; import { compareDatePart, getStartDateOfWeek, addDays, addMonths, compareDates, FirstWeekOfYear, DateRangeType, DayOfWeek, DEFAULT_DATE_FORMATTING, } from '@fluentui/date-time-utilities'; import { Icon } from '../../Icon'; import { defaultWeeklyDayPickerStrings, defaultWeeklyDayPickerNavigationIcons } from './defaults'; import type { IProcessedStyleSet } from '@fluentui/style-utilities'; import type { IWeeklyDayPickerProps, IWeeklyDayPickerStyleProps, IWeeklyDayPickerStyles, } from './WeeklyDayPicker.types'; import type { ICalendarDayGrid } from '../CalendarDayGrid/CalendarDayGrid.types'; const getClassNames = classNamesFunction<IWeeklyDayPickerStyleProps, IWeeklyDayPickerStyles>(); export interface IWeeklyDayPickerState { /** The currently focused date in the week picker, but not necessarily selected */ navigatedDate: Date; /** The currently selected date in the calendar */ selectedDate: Date; /** Tracking whether we just toggled showFullMonth */ previousShowFullMonth: boolean; /** Whether to animate veritcally or horizontally */ animationDirection: AnimationDirection; } export class WeeklyDayPickerBase extends React.Component<IWeeklyDayPickerProps, IWeeklyDayPickerState> { public static defaultProps: IWeeklyDayPickerProps = { onSelectDate: undefined, initialDate: undefined, today: new Date(), firstDayOfWeek: DayOfWeek.Sunday, strings: defaultWeeklyDayPickerStrings, navigationIcons: defaultWeeklyDayPickerNavigationIcons, dateTimeFormatter: DEFAULT_DATE_FORMATTING, animationDirection: AnimationDirection.Horizontal, }; private _dayGrid = React.createRef<ICalendarDayGrid>(); private _focusOnUpdate: boolean; private _initialTouchX: number | undefined; public static getDerivedStateFromProps( nextProps: Readonly<IWeeklyDayPickerProps>, prevState: Readonly<IWeeklyDayPickerState>, ): Partial<IWeeklyDayPickerState> | null { const currentDate = nextProps.initialDate && !isNaN(nextProps.initialDate.getTime()) ? nextProps.initialDate : nextProps.today || new Date(); const showFullMonth = !!nextProps.showFullMonth; const newAnimationDirection = showFullMonth !== prevState.previousShowFullMonth ? AnimationDirection.Vertical : AnimationDirection.Horizontal; if (!compareDates(currentDate, prevState.selectedDate)) { return { selectedDate: currentDate, navigatedDate: currentDate, previousShowFullMonth: showFullMonth, animationDirection: newAnimationDirection, }; } return { selectedDate: currentDate, navigatedDate: prevState.navigatedDate, previousShowFullMonth: showFullMonth, animationDirection: newAnimationDirection, }; } public constructor(props: IWeeklyDayPickerProps) { super(props); initializeComponentRef(this); const currentDate = props.initialDate && !isNaN(props.initialDate.getTime()) ? props.initialDate : props.today || new Date(); this.state = { selectedDate: currentDate, navigatedDate: currentDate, previousShowFullMonth: !!props.showFullMonth, animationDirection: props.animationDirection!, }; this._focusOnUpdate = false; } public focus(): void { if (this._dayGrid && this._dayGrid.current) { this._dayGrid.current.focus(); } } public render(): JSX.Element { const { strings, dateTimeFormatter, firstDayOfWeek, minDate, maxDate, restrictedDates, today, styles, theme, className, showFullMonth, weeksToShow, ...calendarDayGridProps } = this.props; const classNames = getClassNames(styles, { theme: theme!, className: className, }); return ( <div className={classNames.root} onKeyDown={this._onWrapperKeyDown} onTouchStart={this._onTouchStart} onTouchMove={this._onTouchMove} aria-expanded={showFullMonth} > {this._renderPreviousWeekNavigationButton(classNames)} <CalendarDayGrid styles={styles} componentRef={this._dayGrid} strings={strings} selectedDate={this.state.selectedDate!} navigatedDate={this.state.navigatedDate!} firstDayOfWeek={firstDayOfWeek!} firstWeekOfYear={FirstWeekOfYear.FirstDay} dateRangeType={DateRangeType.Day} weeksToShow={showFullMonth ? weeksToShow : 1} dateTimeFormatter={dateTimeFormatter!} minDate={minDate} maxDate={maxDate} restrictedDates={restrictedDates} onSelectDate={this._onSelectDate} onNavigateDate={this._onNavigateDate} today={today} lightenDaysOutsideNavigatedMonth={showFullMonth} animationDirection={this.state.animationDirection} {...calendarDayGridProps} /> {this._renderNextWeekNavigationButton(classNames)} </div> ); } public componentDidUpdate(): void { if (this._focusOnUpdate) { this.focus(); this._focusOnUpdate = false; } } private _onSelectDate = (date: Date): void => { const { onSelectDate } = this.props; // don't set the navigated date on selection because selection never causes navigation this.setState({ selectedDate: date, }); this._focusOnUpdate = true; if (onSelectDate) { onSelectDate(date); } }; private _onNavigateDate = (date: Date, focusOnNavigatedDay: boolean): void => { const { onNavigateDate } = this.props; this.setState({ navigatedDate: date, }); this._focusOnUpdate = focusOnNavigatedDay; if (onNavigateDate) { onNavigateDate(date); } }; private _renderPreviousWeekNavigationButton = ( classNames: IProcessedStyleSet<IWeeklyDayPickerStyles>, ): JSX.Element => { const { minDate, firstDayOfWeek, navigationIcons } = this.props; const { navigatedDate } = this.state; const leftNavigationIcon = getRTL() ? navigationIcons!.rightNavigation : navigationIcons!.leftNavigation; // determine if previous week in bounds const prevWeekInBounds = minDate ? compareDatePart(minDate, getStartDateOfWeek(navigatedDate, firstDayOfWeek!)) < 0 : true; return ( <button className={css(classNames.navigationIconButton, { [classNames.disabledStyle]: !prevWeekInBounds, })} disabled={!prevWeekInBounds} aria-disabled={!prevWeekInBounds} onClick={prevWeekInBounds ? this._onSelectPrevDateRange : undefined} onKeyDown={prevWeekInBounds ? this._onButtonKeyDown(this._onSelectPrevDateRange) : undefined} title={this._createPreviousWeekAriaLabel()} type="button" > <Icon iconName={leftNavigationIcon} /> </button> ); }; private _renderNextWeekNavigationButton = (classNames: IProcessedStyleSet<IWeeklyDayPickerStyles>): JSX.Element => { const { maxDate, firstDayOfWeek, navigationIcons } = this.props; const { navigatedDate } = this.state; const rightNavigationIcon = getRTL() ? navigationIcons!.leftNavigation : navigationIcons!.rightNavigation; // determine if next week in bounds const nextWeekInBounds = maxDate ? compareDatePart(addDays(getStartDateOfWeek(navigatedDate, firstDayOfWeek!), 7), maxDate) < 0 : true; return ( <button className={css(classNames.navigationIconButton, { [classNames.disabledStyle]: !nextWeekInBounds, })} disabled={!nextWeekInBounds} aria-disabled={!nextWeekInBounds} onClick={nextWeekInBounds ? this._onSelectNextDateRange : undefined} onKeyDown={nextWeekInBounds ? this._onButtonKeyDown(this._onSelectNextDateRange) : undefined} title={this._createNextWeekAriaLabel()} type="button" > <Icon iconName={rightNavigationIcon} /> </button> ); }; private _onSelectPrevDateRange = () => { if (this.props.showFullMonth) { this._navigateDate(addMonths(this.state.navigatedDate, -1)); } else { this._navigateDate(addDays(this.state.navigatedDate, -7)); } }; private _onSelectNextDateRange = () => { if (this.props.showFullMonth) { this._navigateDate(addMonths(this.state.navigatedDate, 1)); } else { this._navigateDate(addDays(this.state.navigatedDate, 7)); } }; private _navigateDate = (date: Date) => { this.setState({ navigatedDate: date, }); if (this.props.onNavigateDate) { this.props.onNavigateDate(date); } }; private _onWrapperKeyDown = (ev: React.KeyboardEvent<HTMLElement>) => { // eslint-disable-next-line deprecation/deprecation switch (ev.which) { case KeyCodes.enter: ev.preventDefault(); break; case KeyCodes.backspace: ev.preventDefault(); break; default: break; } }; private _onButtonKeyDown = (callback: () => void): ((ev: React.KeyboardEvent<HTMLButtonElement>) => void) => { return (ev: React.KeyboardEvent<HTMLButtonElement>) => { // eslint-disable-next-line deprecation/deprecation switch (ev.which) { case KeyCodes.enter: callback(); break; } }; }; private _onTouchStart = (ev: React.TouchEvent<HTMLDivElement>) => { const touch = ev.touches[0]; if (touch) { this._initialTouchX = touch.clientX; } }; private _onTouchMove = (ev: React.TouchEvent<HTMLDivElement>) => { const isRtl = getRTL(); const touch = ev.touches[0]; if (touch && this._initialTouchX !== undefined && touch.clientX !== this._initialTouchX) { if ((touch.clientX - this._initialTouchX) * (isRtl ? -1 : 1) < 0) { // swipe right this._onSelectNextDateRange(); } else { // swipe left this._onSelectPrevDateRange(); } this._initialTouchX = undefined; } }; private _createPreviousWeekAriaLabel = () => { const { strings, showFullMonth, firstDayOfWeek } = this.props; const { navigatedDate } = this.state; let ariaLabel = undefined; if (showFullMonth && strings.prevMonthAriaLabel) { ariaLabel = strings.prevMonthAriaLabel + ' ' + strings.months[addMonths(navigatedDate!, -1).getMonth()]; } else if (!showFullMonth && strings.prevWeekAriaLabel) { const firstDayOfPreviousWeek = getStartDateOfWeek(addDays(navigatedDate!, -7), firstDayOfWeek!); const lastDayOfPreviousWeek = addDays(firstDayOfPreviousWeek, 6); ariaLabel = strings.prevWeekAriaLabel + ' ' + this._formatDateRange(firstDayOfPreviousWeek, lastDayOfPreviousWeek); } return ariaLabel; }; private _createNextWeekAriaLabel = () => { const { strings, showFullMonth, firstDayOfWeek } = this.props; const { navigatedDate } = this.state; let ariaLabel = undefined; if (showFullMonth && strings.nextMonthAriaLabel) { ariaLabel = strings.nextMonthAriaLabel + ' ' + strings.months[addMonths(navigatedDate!, 1).getMonth()]; } else if (!showFullMonth && strings.nextWeekAriaLabel) { const firstDayOfNextWeek = getStartDateOfWeek(addDays(navigatedDate!, 7), firstDayOfWeek!); const lastDayOfNextWeek = addDays(firstDayOfNextWeek, 6); ariaLabel = strings.nextWeekAriaLabel + ' ' + this._formatDateRange(firstDayOfNextWeek, lastDayOfNextWeek); } return ariaLabel; }; private _formatDateRange = (startDate: Date, endDate: Date) => { const { dateTimeFormatter, strings } = this.props; return `${dateTimeFormatter?.formatMonthDayYear(startDate, strings)} - ${dateTimeFormatter?.formatMonthDayYear( endDate, strings, )}`; }; }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://clouddebugger.googleapis.com/$discovery/rest?version=v2 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Stackdriver Debugger API v2 */ function load(name: "clouddebugger", version: "v2"): PromiseLike<void>; function load(name: "clouddebugger", version: "v2", callback: () => any): void; const controller: clouddebugger.ControllerResource; namespace clouddebugger { interface AliasContext { /** The alias kind. */ kind?: string; /** The alias name. */ name?: string; } interface Breakpoint { /** * Action that the agent should perform when the code at the * breakpoint location is hit. */ action?: string; /** * Condition that triggers the breakpoint. * The condition is a compound boolean expression composed using expressions * in a programming language at the source location. */ condition?: string; /** Time this breakpoint was created by the server in seconds resolution. */ createTime?: string; /** * Values of evaluated expressions at breakpoint time. * The evaluated expressions appear in exactly the same order they * are listed in the `expressions` field. * The `name` field holds the original expression text, the `value` or * `members` field holds the result of the evaluated expression. * If the expression cannot be evaluated, the `status` inside the `Variable` * will indicate an error and contain the error text. */ evaluatedExpressions?: Variable[]; /** * List of read-only expressions to evaluate at the breakpoint location. * The expressions are composed using expressions in the programming language * at the source location. If the breakpoint action is `LOG`, the evaluated * expressions are included in log statements. */ expressions?: string[]; /** * Time this breakpoint was finalized as seen by the server in seconds * resolution. */ finalTime?: string; /** Breakpoint identifier, unique in the scope of the debuggee. */ id?: string; /** * When true, indicates that this is a final result and the * breakpoint state will not change from here on. */ isFinalState?: boolean; /** * A set of custom breakpoint properties, populated by the agent, to be * displayed to the user. */ labels?: Record<string, string>; /** Breakpoint source location. */ location?: SourceLocation; /** Indicates the severity of the log. Only relevant when action is `LOG`. */ logLevel?: string; /** * Only relevant when action is `LOG`. Defines the message to log when * the breakpoint hits. The message may include parameter placeholders `$0`, * `$1`, etc. These placeholders are replaced with the evaluated value * of the appropriate expression. Expressions not referenced in * `log_message_format` are not logged. * * Example: `Message received, id = $0, count = $1` with * `expressions` = `[ message.id, message.count ]`. */ logMessageFormat?: string; /** The stack at breakpoint time. */ stackFrames?: StackFrame[]; /** * Breakpoint status. * * The status includes an error flag and a human readable message. * This field is usually unset. The message can be either * informational or an error message. Regardless, clients should always * display the text message back to the user. * * Error status indicates complete failure of the breakpoint. * * Example (non-final state): `Still loading symbols...` * * Examples (final state): * * &#42; `Invalid line number` referring to location * &#42; `Field f not found in class C` referring to condition */ status?: StatusMessage; /** E-mail address of the user that created this breakpoint */ userEmail?: string; /** * The `variable_table` exists to aid with computation, memory and network * traffic optimization. It enables storing a variable once and reference * it from multiple variables, including variables stored in the * `variable_table` itself. * For example, the same `this` object, which may appear at many levels of * the stack, can have all of its data stored once in this table. The * stack frame variables then would hold only a reference to it. * * The variable `var_table_index` field is an index into this repeated field. * The stored objects are nameless and get their name from the referencing * variable. The effective variable is a merge of the referencing variable * and the referenced variable. */ variableTable?: Variable[]; } interface CloudRepoSourceContext { /** An alias, which may be a branch or tag. */ aliasContext?: AliasContext; /** The name of an alias (branch, tag, etc.). */ aliasName?: string; /** The ID of the repo. */ repoId?: RepoId; /** A revision ID. */ revisionId?: string; } interface CloudWorkspaceId { /** * The unique name of the workspace within the repo. This is the name * chosen by the client in the Source API's CreateWorkspace method. */ name?: string; /** The ID of the repo containing the workspace. */ repoId?: RepoId; } interface CloudWorkspaceSourceContext { /** * The ID of the snapshot. * An empty snapshot_id refers to the most recent snapshot. */ snapshotId?: string; /** The ID of the workspace. */ workspaceId?: CloudWorkspaceId; } interface Debuggee { /** * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). */ agentVersion?: string; /** * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. */ description?: string; /** * References to the locations and revisions of the source code used in the * deployed application. * * NOTE: this field is experimental and can be ignored. */ extSourceContexts?: ExtendedSourceContext[]; /** Unique identifier for the debuggee generated by the controller service. */ id?: string; /** * If set to `true`, indicates that the agent should disable itself and * detach from the debuggee. */ isDisabled?: boolean; /** * If set to `true`, indicates that Controller service does not detect any * activity from the debuggee agents and the application is possibly stopped. */ isInactive?: boolean; /** * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. */ labels?: Record<string, string>; /** * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. */ project?: string; /** * References to the locations and revisions of the source code used in the * deployed application. */ sourceContexts?: SourceContext[]; /** * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. */ status?: StatusMessage; /** * Uniquifier to further distiguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distiguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. */ uniquifier?: string; } interface ExtendedSourceContext { /** Any source context. */ context?: SourceContext; /** Labels with user defined metadata. */ labels?: Record<string, string>; } interface FormatMessage { /** * Format template for the message. The `format` uses placeholders `$0`, * `$1`, etc. to reference parameters. `$$` can be used to denote the `$` * character. * * Examples: * * &#42; `Failed to load '$0' which helps debug $1 the first time it * is loaded. Again, $0 is very important.` * &#42; `Please pay $$10 to use $0 instead of $1.` */ format?: string; /** Optional parameters to be embedded into the message. */ parameters?: string[]; } interface GerritSourceContext { /** An alias, which may be a branch or tag. */ aliasContext?: AliasContext; /** The name of an alias (branch, tag, etc.). */ aliasName?: string; /** * The full project name within the host. Projects may be nested, so * "project/subproject" is a valid project name. * The "repo name" is hostURI/project. */ gerritProject?: string; /** The URI of a running Gerrit instance. */ hostUri?: string; /** A revision (commit) ID. */ revisionId?: string; } interface GetBreakpointResponse { /** * Complete breakpoint state. * The fields `id` and `location` are guaranteed to be set. */ breakpoint?: Breakpoint; } interface GitSourceContext { /** * Git commit hash. * required. */ revisionId?: string; /** Git repository URL. */ url?: string; } interface ListActiveBreakpointsResponse { /** * List of all active breakpoints. * The fields `id` and `location` are guaranteed to be set on each breakpoint. */ breakpoints?: Breakpoint[]; /** * A token that can be used in the next method call to block until * the list of breakpoints changes. */ nextWaitToken?: string; /** * If set to `true`, indicates that there is no change to the * list of active breakpoints and the server-selected timeout has expired. * The `breakpoints` field would be empty and should be ignored. */ waitExpired?: boolean; } interface ListBreakpointsResponse { /** * List of breakpoints matching the request. * The fields `id` and `location` are guaranteed to be set on each breakpoint. * The fields: `stack_frames`, `evaluated_expressions` and `variable_table` * are cleared on each breakpoint regardless of its status. */ breakpoints?: Breakpoint[]; /** * A wait token that can be used in the next call to `list` (REST) or * `ListBreakpoints` (RPC) to block until the list of breakpoints has changes. */ nextWaitToken?: string; } interface ListDebuggeesResponse { /** * List of debuggees accessible to the calling user. * The fields `debuggee.id` and `description` are guaranteed to be set. * The `description` field is a human readable field provided by agents and * can be displayed to users. */ debuggees?: Debuggee[]; } interface ProjectRepoId { /** The ID of the project. */ projectId?: string; /** The name of the repo. Leave empty for the default repo. */ repoName?: string; } interface RegisterDebuggeeRequest { /** * Debuggee information to register. * The fields `project`, `uniquifier`, `description` and `agent_version` * of the debuggee must be set. */ debuggee?: Debuggee; } interface RegisterDebuggeeResponse { /** * Debuggee resource. * The field `id` is guranteed to be set (in addition to the echoed fields). * If the field `is_disabled` is set to `true`, the agent should disable * itself by removing all breakpoints and detaching from the application. * It should however continue to poll `RegisterDebuggee` until reenabled. */ debuggee?: Debuggee; } interface RepoId { /** A combination of a project ID and a repo name. */ projectRepoId?: ProjectRepoId; /** A server-assigned, globally unique identifier. */ uid?: string; } interface SetBreakpointResponse { /** * Breakpoint resource. * The field `id` is guaranteed to be set (in addition to the echoed fileds). */ breakpoint?: Breakpoint; } interface SourceContext { /** A SourceContext referring to a revision in a cloud repo. */ cloudRepo?: CloudRepoSourceContext; /** A SourceContext referring to a snapshot in a cloud workspace. */ cloudWorkspace?: CloudWorkspaceSourceContext; /** A SourceContext referring to a Gerrit project. */ gerrit?: GerritSourceContext; /** A SourceContext referring to any third party Git repo (e.g. GitHub). */ git?: GitSourceContext; } interface SourceLocation { /** Line inside the file. The first line in the file has the value `1`. */ line?: number; /** Path to the source file within the source context of the target binary. */ path?: string; } interface StackFrame { /** * Set of arguments passed to this function. * Note that this might not be populated for all stack frames. */ arguments?: Variable[]; /** Demangled function name at the call site. */ function?: string; /** * Set of local variables at the stack frame location. * Note that this might not be populated for all stack frames. */ locals?: Variable[]; /** Source location of the call site. */ location?: SourceLocation; } interface StatusMessage { /** Status message text. */ description?: FormatMessage; /** Distinguishes errors from informational messages. */ isError?: boolean; /** Reference to which the message applies. */ refersTo?: string; } interface UpdateActiveBreakpointRequest { /** * Updated breakpoint information. * The field `id` must be set. * The agent must echo all Breakpoint specification fields in the update. */ breakpoint?: Breakpoint; } interface Variable { /** Members contained or pointed to by the variable. */ members?: Variable[]; /** Name of the variable, if any. */ name?: string; /** * Status associated with the variable. This field will usually stay * unset. A status of a single variable only applies to that variable or * expression. The rest of breakpoint data still remains valid. Variables * might be reported in error state even when breakpoint is not in final * state. * * The message may refer to variable name with `refers_to` set to * `VARIABLE_NAME`. Alternatively `refers_to` will be set to `VARIABLE_VALUE`. * In either case variable value and members will be unset. * * Example of error message applied to name: `Invalid expression syntax`. * * Example of information message applied to value: `Not captured`. * * Examples of error message applied to value: * * &#42; `Malformed string`, * &#42; `Field f not found in class C` * &#42; `Null pointer dereference` */ status?: StatusMessage; /** * Variable type (e.g. `MyClass`). If the variable is split with * `var_table_index`, `type` goes next to `value`. The interpretation of * a type is agent specific. It is recommended to include the dynamic type * rather than a static type of an object. */ type?: string; /** Simple value of the variable. */ value?: string; /** * Reference to a variable in the shared variable table. More than * one variable can reference the same variable in the table. The * `var_table_index` field is an index into `variable_table` in Breakpoint. */ varTableIndex?: number; } interface BreakpointsResource { /** * Returns the list of all active breakpoints for the debuggee. * * The breakpoint specification (`location`, `condition`, and `expressions` * fields) is semantically immutable, although the field values may * change. For example, an agent may update the location line number * to reflect the actual line where the breakpoint was set, but this * doesn't change the breakpoint semantics. * * This means that an agent does not need to check if a breakpoint has changed * when it encounters the same breakpoint on a successive call. * Moreover, an agent should remember the breakpoints that are completed * until the controller removes them from the active list to avoid * setting those breakpoints again. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Identifies the debuggee. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * If set to `true` (recommended), returns `google.rpc.Code.OK` status and * sets the `wait_expired` response field to `true` when the server-selected * timeout has expired. * * If set to `false` (deprecated), returns `google.rpc.Code.ABORTED` status * when the server-selected timeout has expired. */ successOnTimeout?: boolean; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * A token that, if specified, blocks the method call until the list * of active breakpoints has changed, or a server-selected timeout has * expired. The value should be set from the `next_wait_token` field in * the last response. The initial value should be set to `"init"`. */ waitToken?: string; }): Request<ListActiveBreakpointsResponse>; /** * Updates the breakpoint state or mutable fields. * The entire Breakpoint message must be sent back to the controller service. * * Updates to active breakpoint fields are only allowed if the new value * does not change the breakpoint specification. Updates to the `location`, * `condition` and `expressions` fields should not alter the breakpoint * semantics. These may only make changes such as canonicalizing a value * or snapping the location to the correct line of code. */ update(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Identifies the debuggee being debugged. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Breakpoint identifier, unique in the scope of the debuggee. */ id: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; } interface DebuggeesResource { /** * Registers the debuggee with the controller service. * * All agents attached to the same application must call this method with * exactly the same request content to get back the same stable `debuggee_id`. * Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` * is returned from any controller method. * * This protocol allows the controller service to disable debuggees, recover * from data loss, or change the `debuggee_id` format. Agents must handle * `debuggee_id` value changing upon re-registration. */ register(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<RegisterDebuggeeResponse>; breakpoints: BreakpointsResource; } interface ControllerResource { debuggees: DebuggeesResource; } interface BreakpointsResource { /** Deletes the breakpoint from the debuggee. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** ID of the breakpoint to delete. */ breakpointId: string; /** JSONP */ callback?: string; /** * The client version making the call. * Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). */ clientVersion?: string; /** ID of the debuggee whose breakpoint to delete. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Gets breakpoint information. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** ID of the breakpoint to get. */ breakpointId: string; /** JSONP */ callback?: string; /** * The client version making the call. * Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). */ clientVersion?: string; /** ID of the debuggee whose breakpoint to get. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GetBreakpointResponse>; /** Lists all breakpoints for the debuggee. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Only breakpoints with the specified action will pass the filter. */ "action.value"?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The client version making the call. * Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). */ clientVersion?: string; /** ID of the debuggee whose breakpoints to list. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * When set to `true`, the response includes the list of breakpoints set by * any user. Otherwise, it includes only breakpoints set by the caller. */ includeAllUsers?: boolean; /** * When set to `true`, the response includes active and inactive * breakpoints. Otherwise, it includes only active breakpoints. */ includeInactive?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * This field is deprecated. The following fields are always stripped out of * the result: `stack_frames`, `evaluated_expressions` and `variable_table`. */ stripResults?: boolean; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * A wait token that, if specified, blocks the call until the breakpoints * list has changed, or a server selected timeout has expired. The value * should be set from the last response. The error code * `google.rpc.Code.ABORTED` (RPC) is returned on wait timeout, which * should be called again with the same `wait_token`. */ waitToken?: string; }): Request<ListBreakpointsResponse>; /** Sets the breakpoint to the debuggee. */ set(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The client version making the call. * Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). */ clientVersion?: string; /** ID of the debuggee where the breakpoint is to be set. */ debuggeeId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<SetBreakpointResponse>; } interface DebuggeesResource { /** Lists all the debuggees that the user has access to. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The client version making the call. * Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). */ clientVersion?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** * When set to `true`, the result includes all debuggees. Otherwise, the * result includes only debuggees that are active. */ includeInactive?: boolean; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Project number of a Google Cloud project whose debuggees to list. */ project?: string; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListDebuggeesResponse>; breakpoints: BreakpointsResource; } interface DebuggerResource { debuggees: DebuggeesResource; } } }
the_stack
namespace ts.pxtc { export const placeholderChar = "◊"; export interface FunOverride { n: string; t: any; scale?: number; snippet?: string; } export const ts2PyFunNameMap: pxt.Map<FunOverride> = { "Math.trunc": { n: "int", t: ts.SyntaxKind.NumberKeyword, snippet: "int(0)" }, "Math.min": { n: "min", t: ts.SyntaxKind.NumberKeyword, snippet: "min(0, 0)" }, "Math.max": { n: "max", t: ts.SyntaxKind.NumberKeyword, snippet: "max(0, 0)" }, "Math.abs": { n: "abs", t: ts.SyntaxKind.NumberKeyword, snippet: "abs(0)" }, "console.log": { n: "print", t: ts.SyntaxKind.VoidKeyword, snippet: 'print(":)")' }, ".length": { n: "len", t: ts.SyntaxKind.NumberKeyword }, ".toLowerCase()": { n: "string.lower", t: ts.SyntaxKind.StringKeyword }, ".toUpperCase()": { n: "string.upper", t: ts.SyntaxKind.StringKeyword }, ".charCodeAt(0)": { n: "ord", t: ts.SyntaxKind.NumberKeyword }, "pins.createBuffer": { n: "bytearray", t: ts.SyntaxKind.Unknown }, "pins.createBufferFromArray": { n: "bytes", t: ts.SyntaxKind.Unknown }, "control.createBuffer": { n: "bytearray", t: ts.SyntaxKind.Unknown }, "control.createBufferFromArray": { n: "bytes", t: ts.SyntaxKind.Unknown }, "!!": { n: "bool", t: ts.SyntaxKind.BooleanKeyword }, "Array.indexOf": { n: "Array.index", t: ts.SyntaxKind.Unknown }, "Array.push": { n: "Array.append", t: ts.SyntaxKind.Unknown }, "parseInt": { n: "int", t: ts.SyntaxKind.NumberKeyword, snippet: 'int("0")' }, "_py.range": { n: "range", t: ts.SyntaxKind.Unknown, snippet: 'range(4)' } } export function emitPyTypeFromTypeNode(s: ts.TypeNode): string { if (!s || !s.kind) return null; switch (s.kind) { case ts.SyntaxKind.StringKeyword: return "str" case ts.SyntaxKind.NumberKeyword: // Note, "real" python expects this to be "float" or "int", we're intentionally diverging here return "number" case ts.SyntaxKind.BooleanKeyword: return "bool" case ts.SyntaxKind.VoidKeyword: return "None" case ts.SyntaxKind.FunctionType: return emitFuncPyType(s as ts.FunctionTypeNode) case ts.SyntaxKind.ArrayType: { let t = s as ts.ArrayTypeNode let elType = emitPyTypeFromTypeNode(t.elementType) return `List[${elType}]` } case ts.SyntaxKind.TypeReference: { let t = s as ts.TypeReferenceNode let nm = t.typeName && t.typeName.getText ? t.typeName.getText() : ""; return nm } case ts.SyntaxKind.AnyKeyword: return "any" default: pxt.tickEvent("depython.todo.tstypenodetopytype", { kind: s.kind }) return `` } // // TODO translate type // return s.getText() } export function emitPyTypeFromTsType(s: ts.Type): string { if (!s || !s.flags) return null; switch (s.flags) { case ts.TypeFlags.String: return "str" case ts.TypeFlags.Number: // Note: "real" python expects this to be "float" or "int", we're intentionally diverging here return "number" case ts.TypeFlags.Boolean: return "bool" case ts.TypeFlags.Void: return "None" case ts.TypeFlags.Any: return "any" default: pxt.tickEvent("depython.todo.tstypetopytype", { kind: s.flags }) return `` } } function emitFuncPyType(s: ts.FunctionTypeNode): string { let returnType = emitPyTypeFromTypeNode(s.type) let params = s.parameters .map(p => p.type) // python type syntax doesn't allow names .map(emitPyTypeFromTypeNode) // "Real" python expects this to be "Callable[[arg1, arg2], ret]", we're intentionally changing to "(arg1, arg2) -> ret" return `(${params.join(", ")}) -> ${returnType}` } function getSymbolKind(node: Node) { switch (node.kind) { case SK.MethodDeclaration: case SK.MethodSignature: return SymbolKind.Method; case SK.PropertyDeclaration: case SK.PropertySignature: case SK.GetAccessor: case SK.SetAccessor: return SymbolKind.Property; case SK.Constructor: case SK.FunctionDeclaration: return SymbolKind.Function; case SK.VariableDeclaration: return SymbolKind.Variable; case SK.ModuleDeclaration: return SymbolKind.Module; case SK.EnumDeclaration: return SymbolKind.Enum; case SK.EnumMember: return SymbolKind.EnumMember; case SK.ClassDeclaration: return SymbolKind.Class; case SK.InterfaceDeclaration: return SymbolKind.Interface; default: return SymbolKind.None } } function createSymbolInfo(typechecker: TypeChecker, qName: string, stmt: Node): SymbolInfo { function typeOf(tn: TypeNode, n: Node, stripParams = false): string { let t = typechecker.getTypeAtLocation(n) if (!t) return "None" if (stripParams) { t = t.getCallSignatures()[0].getReturnType() } const readableName = typechecker.typeToString(t, undefined, TypeFormatFlags.UseFullyQualifiedType) // TypeScript 2.0.0+ will assign constant variables numeric literal types which breaks the // type checking we do in the blocks // This can be a number literal '7' or a union type of them '0 | 1 | 2' if (/^\d/.test(readableName)) { return "number"; } if (readableName == "this") { return getFullName(typechecker, t.symbol); } return readableName; } let kind = getSymbolKind(stmt) if (kind != SymbolKind.None) { let decl: FunctionLikeDeclaration = stmt as any; let attributes = parseComments(decl) if (attributes.weight < 0) return null; let m = /^(.*)\.(.*)/.exec(qName) let hasParams = kind == SymbolKind.Function || kind == SymbolKind.Method let pkg: string = null let pkgs: string[] = null let src = getSourceFileOfNode(stmt) if (src) { let m = /^pxt_modules\/([^\/]+)/.exec(src.fileName) if (m) pkg = m[1] } let extendsTypes: string[] = undefined if (kind == SymbolKind.Class || kind == SymbolKind.Interface) { let cl = stmt as ClassLikeDeclaration extendsTypes = [] if (cl.heritageClauses) for (let h of cl.heritageClauses) { if (h.types) { for (let t of h.types) { extendsTypes.push(typeOf(t, t)) } } } } if (kind == SymbolKind.Enum || kind === SymbolKind.EnumMember) { (extendsTypes || (extendsTypes = [])).push("Number"); } let r: SymbolInfo = { kind, qName, namespace: m ? m[1] : "", name: m ? m[2] : qName, fileName: stmt.getSourceFile().fileName, attributes, pkg, pkgs, extendsTypes, retType: stmt.kind == SyntaxKind.Constructor ? "void" : kind == SymbolKind.Module ? "" : typeOf(decl.type, decl, hasParams), parameters: !hasParams ? null : Util.toArray(decl.parameters).map((p, i) => { let n = getName(p) let desc = attributes.paramHelp[n] || "" let minVal = attributes.paramMin && attributes.paramMin[n]; let maxVal = attributes.paramMax && attributes.paramMax[n]; let m = /\beg\.?:\s*(.+)/.exec(desc) let props: PropertyDesc[]; let parameters: PropertyDesc[]; if (p.type && p.type.kind === SK.FunctionType) { const callBackSignature = typechecker.getSignatureFromDeclaration(p.type as FunctionTypeNode); const callbackParameters = callBackSignature.getParameters(); if (attributes.mutate === "objectdestructuring") { assert(callbackParameters.length > 0); props = typechecker.getTypeAtLocation(callbackParameters[0].valueDeclaration).getProperties().map(prop => { return { name: prop.getName(), type: typechecker.typeToString(typechecker.getTypeOfSymbolAtLocation(prop, callbackParameters[0].valueDeclaration)) } }); } else { parameters = callbackParameters.map((sym, i) => { return { name: sym.getName(), type: typechecker.typeToString(typechecker.getTypeOfSymbolAtLocation(sym, p), undefined, TypeFormatFlags.UseFullyQualifiedType) }; }); } } let options: pxt.Map<PropertyOption> = {}; const paramType = typechecker.getTypeAtLocation(p); let isEnum = paramType && !!(paramType.flags & (TypeFlags.Enum | TypeFlags.EnumLiteral)); if (attributes.block && attributes.paramShadowOptions) { const argNames: string[] = [] attributes.block.replace(/%(\w+)/g, (f, n) => { argNames.push(n) return "" }); if (attributes.paramShadowOptions[argNames[i]]) { options['fieldEditorOptions'] = { value: attributes.paramShadowOptions[argNames[i]] } } } if (minVal) options['min'] = { value: minVal }; if (maxVal) options['max'] = { value: maxVal }; const pyTypeString = (p.type && emitPyTypeFromTypeNode(p.type)) || (paramType && emitPyTypeFromTsType(paramType)) || "unknown"; const initializer = p.initializer ? p.initializer.getText() : getExplicitDefault(attributes, n) || (p.questionToken ? "undefined" : undefined) return { name: n, description: desc, type: typeOf(p.type, p), pyTypeString, initializer, default: attributes.paramDefl[n], properties: props, handlerParameters: parameters, options: options, isEnum } }), snippet: ts.isFunctionLike(stmt) ? null : undefined } switch (r.kind) { case SymbolKind.EnumMember: r.pyName = U.snakify(r.name).toUpperCase() break case SymbolKind.Variable: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Function: r.pyName = U.snakify(r.name) break case SymbolKind.Enum: case SymbolKind.Class: case SymbolKind.Interface: case SymbolKind.Module: default: r.pyName = r.name break } if (stmt.kind === SK.GetAccessor || ((stmt.kind === SK.PropertyDeclaration || stmt.kind === SK.PropertySignature) && isReadonly(stmt as Declaration))) { r.isReadOnly = true } return r } return null; } export interface GenDocsOptions { package?: boolean; locs?: boolean; docs?: boolean; pxtsnippet?: pxt.SnippetConfig[]; // extract localizable strings from pxtsnippets.json files } export function genDocs(pkg: string, apiInfo: ApisInfo, options: GenDocsOptions = {}): pxt.Map<string> { pxt.debug(`generating docs for ${pkg}`) pxt.debug(JSON.stringify(Object.keys(apiInfo.byQName), null, 2)) const files: pxt.Map<string> = {}; const infos = Util.values(apiInfo.byQName); const enumMembers = infos.filter(si => si.kind == SymbolKind.EnumMember) .sort(compareSymbols); const snippetStrings: pxt.Map<string> = {}; const locStrings: pxt.Map<string> = {}; const jsdocStrings: pxt.Map<string> = {}; const writeLoc = (si: SymbolInfo) => { if (!options.locs || !si.qName) { return; } if (/^__/.test(si.name)) return; // skip functions starting with __ pxt.debug(`loc: ${si.qName}`) // must match blockly loader if (si.kind != SymbolKind.EnumMember) { const ns = ts.pxtc.blocksCategory(si); if (ns) locStrings[`{id:category}${ns}`] = ns; } if (si.attributes.jsDoc) jsdocStrings[si.qName] = si.attributes.jsDoc; if (si.attributes.block) locStrings[`${si.qName}|block`] = si.attributes.block; if (si.attributes.group) locStrings[`{id:group}${si.attributes.group}`] = si.attributes.group; if (si.attributes.subcategory) locStrings[`{id:subcategory}${si.attributes.subcategory}`] = si.attributes.subcategory; if (si.parameters) si.parameters.filter(pi => !!pi.description).forEach(pi => { jsdocStrings[`${si.qName}|param|${pi.name}`] = pi.description; }) } const mapLocs = (m: pxt.Map<string>, name: string) => { if (!options.locs) return; const locs: pxt.Map<string> = {}; Object.keys(m).sort().forEach(l => locs[l] = m[l]); files[pkg + name + "-strings.json"] = JSON.stringify(locs, null, 2); } for (const info of infos) { const isNamespace = info.kind == SymbolKind.Module; if (isNamespace) { if (!infos.filter(si => si.namespace == info.name && !!si.attributes.jsDoc)[0]) continue; // nothing in namespace if (!info.attributes.block) info.attributes.block = info.name; // reusing this field to store localized namespace name } writeLoc(info); } if (options.locs) enumMembers.forEach(em => { if (em.attributes.block) locStrings[`${em.qName}|block`] = em.attributes.block; if (em.attributes.jsDoc) locStrings[em.qName] = em.attributes.jsDoc; }); mapLocs(locStrings, ""); mapLocs(jsdocStrings, "-jsdoc"); // Localize pxtsnippets.json files if (options.pxtsnippet) { options.pxtsnippet.forEach(snippet => localizeSnippet(snippet, snippetStrings)); mapLocs(snippetStrings, "-snippet"); } return files; } function localizeSnippet(snippet: pxt.SnippetConfig, locs: pxt.Map<string>) { const localizableQuestionProperties = ['label', 'title', 'hint', 'errorMessage']; // TODO(jb) provide this elsewhere locs[snippet.label] = snippet.label; snippet.questions.forEach((question: pxt.Map<any>) => { localizableQuestionProperties.forEach((prop) => { if (question[prop]) { locs[question[prop]] = question[prop]; } }); }) } export function hasBlock(sym: SymbolInfo): boolean { return !!sym.attributes.block && !!sym.attributes.blockId; } let symbolKindWeight: pxt.Map<number>; export function compareSymbols(l: SymbolInfo, r: SymbolInfo): number { function cmpr(toValue: (s: SymbolInfo) => number) { const c = -toValue(l) + toValue(r) return c } // favor symbols with blocks let c = cmpr(s => hasBlock(s) ? 1 : -1); if (c) return c; // favor top-level symbols c = cmpr(s => !s.namespace ? 1 : -1) if (c) return c; // sort by symbol kind if (!symbolKindWeight) { symbolKindWeight = {}; symbolKindWeight[SymbolKind.Variable] = 100; symbolKindWeight[SymbolKind.Module] = 101; symbolKindWeight[SymbolKind.Function] = 99; symbolKindWeight[SymbolKind.Property] = 98; symbolKindWeight[SymbolKind.Method] = 97; symbolKindWeight[SymbolKind.Class] = 89; symbolKindWeight[SymbolKind.Enum] = 81; symbolKindWeight[SymbolKind.EnumMember] = 80; } c = cmpr(s => symbolKindWeight[s.kind] || 0) if (c) return c; // check for a weight attribute c = cmpr(s => s.attributes.weight || 50) if (c) return c; return U.strcmp(l.name, r.name); } export function getApiInfo(program: Program, jres?: pxt.Map<pxt.JRes>, legacyOnly = false): ApisInfo { return internalGetApiInfo(program, jres, legacyOnly).apis; } export function internalGetApiInfo(program: Program, jres?: pxt.Map<pxt.JRes>, legacyOnly = false) { const res: ApisInfo = { byQName: {}, jres: jres } const qNameToNode: pxt.Map<Declaration> = {}; const typechecker = program.getTypeChecker() const collectDecls = (stmt: Node) => { if (stmt.kind == SK.VariableStatement) { let vs = stmt as VariableStatement vs.declarationList.declarations.forEach(collectDecls) return } if (isExported(stmt as Declaration)) { if (!stmt.symbol) { console.warn("no symbol", stmt) return; } let qName = getFullName(typechecker, stmt.symbol) if (stmt.kind == SK.SetAccessor) qName += "@set" // otherwise we get a clash with the getter qNameToNode[qName] = stmt as Declaration; let si = createSymbolInfo(typechecker, qName, stmt) if (si) { let existing = U.lookup(res.byQName, qName) if (existing) { // we can have a function and an interface of the same name if (existing.kind == SymbolKind.Interface && si.kind != SymbolKind.Interface) { // save existing entry res.byQName[qName + "@type"] = existing } else if (existing.kind != SymbolKind.Interface && si.kind == SymbolKind.Interface) { res.byQName[qName + "@type"] = si si = existing } else { const foundSrc = existing.attributes._source?.trim(); const newSrc = si.attributes._source?.trim(); let source = foundSrc + "\n" + newSrc; // Avoid duplicating source if possible if (!!foundSrc && newSrc?.indexOf(foundSrc) >= 0) { source = newSrc; } else if (!!newSrc && foundSrc?.indexOf(newSrc) >= 0) { source = foundSrc; } si.attributes = parseCommentString(source); // Check if the colliding symbols are namespace definitions. The same namespace can be // defined in different packages/extensions, so we want to keep track of that information. // That way, we can make sure each cached extension has a copy of the namespace if (existing.kind === SymbolKind.Module) { // Reference the existing array of packages where this namespace has been defined si.pkgs = existing.pkgs || [] if (existing.pkg !== si.pkg) { if (!si.pkgs.find(element => element === existing.pkg)) { si.pkgs.push(existing.pkg) } } } if (existing.extendsTypes) { si.extendsTypes = si.extendsTypes || [] existing.extendsTypes.forEach(t => { if (si.extendsTypes.indexOf(t) === -1) { si.extendsTypes.push(t); } }) } } } if (stmt.parent && (stmt.parent.kind == SK.ClassDeclaration || stmt.parent.kind == SK.InterfaceDeclaration) && !isStatic(stmt as Declaration)) si.isInstance = true res.byQName[qName] = si } } if (stmt.kind == SK.ModuleDeclaration) { let mod = <ModuleDeclaration>stmt if (mod.body.kind == SK.ModuleBlock) { let blk = <ModuleBlock>mod.body blk.statements.forEach(collectDecls) } else if (mod.body.kind == SK.ModuleDeclaration) { collectDecls(mod.body) } } else if (stmt.kind == SK.InterfaceDeclaration) { let iface = stmt as InterfaceDeclaration iface.members.forEach(collectDecls) } else if (stmt.kind == SK.ClassDeclaration) { let iface = stmt as ClassDeclaration iface.members.forEach(collectDecls) } else if (stmt.kind == SK.EnumDeclaration) { let e = stmt as EnumDeclaration e.members.forEach(collectDecls) } } for (let srcFile of program.getSourceFiles()) { srcFile.statements.forEach(collectDecls) } let toclose: SymbolInfo[] = [] // store qName in symbols for (let qName in res.byQName) { let si = res.byQName[qName] si.qName = qName; si.attributes._source = null if (si.extendsTypes && si.extendsTypes.length) toclose.push(si) let jrname = si.attributes.jres if (jrname) { if (jrname == "true") jrname = qName let jr = U.lookup(jres || {}, jrname) if (jr && jr.icon && !si.attributes.iconURL) { si.attributes.iconURL = jr.icon } if (jr && jr.data && !si.attributes.jresURL) { si.attributes.jresURL = "data:" + jr.mimeType + ";base64," + jr.data } } if (si.pyName) { let override = U.lookup(ts2PyFunNameMap, si.qName); if (override && override.n) { si.pyQName = override.n; si.pySnippet = override.snippet; si.pySnippetName = override.n; si.pySnippetWithMarkers = undefined; } else if (si.namespace) { let par = res.byQName[si.namespace] if (par) { si.pyQName = par.pyQName + "." + si.pyName } else { // shouldn't happen pxt.log("namespace missing: " + si.namespace) si.pyQName = si.namespace + "." + si.pyName } } else { si.pyQName = si.pyName } } } // transitive closure of inheritance let closed: pxt.Map<boolean> = {} let closeSi = (si: SymbolInfo) => { if (U.lookup(closed, si.qName)) return; closed[si.qName] = true let mine: pxt.Map<boolean> = {} mine[si.qName] = true for (let e of si.extendsTypes || []) { mine[e] = true let psi = res.byQName[e] if (psi) { closeSi(psi) for (let ee of psi.extendsTypes) mine[ee] = true } } si.extendsTypes = Object.keys(mine) } toclose.forEach(closeSi) if (legacyOnly) { // conflicts with pins.map() delete res.byQName["Array.map"] } return { apis: res, decls: qNameToNode } } export function getFullName(typechecker: TypeChecker, symbol: Symbol): string { if ((symbol as any).isBogusSymbol) return symbol.name return typechecker.getFullyQualifiedName(symbol); } } namespace ts.pxtc.service { let emptyOptions: CompileOptions = { fileSystem: {}, sourceFiles: [], target: { isNative: false, hasHex: false, switches: {} } } class Host implements LanguageServiceHost { opts = emptyOptions; fileVersions: pxt.Map<number> = {}; projectVer = 0; pxtModulesOK: string = null; getProjectVersion() { return this.projectVer + "" } setFile(fn: string, cont: string) { if (this.opts.fileSystem[fn] != cont) { this.fileVersions[fn] = (this.fileVersions[fn] || 0) + 1 this.opts.fileSystem[fn] = cont this.projectVer++ } } reset() { this.setOpts(emptyOptions) this.pxtModulesOK = null } setOpts(o: CompileOptions) { Util.iterMap(o.fileSystem, (fn, v) => { if (this.opts.fileSystem[fn] != v) { this.fileVersions[fn] = (this.fileVersions[fn] || 0) + 1 } }); // shallow copy, but deep copy the file system this.opts = { ...o, fileSystem: { ...o.fileSystem, }, } this.projectVer++ } getCompilationSettings(): CompilerOptions { return getTsCompilerOptions(this.opts) } getScriptFileNames(): string[] { return this.opts.sourceFiles.filter(f => U.endsWith(f, ".ts")); } getScriptVersion(fileName: string): string { return (this.fileVersions[fileName] || 0).toString() } getScriptSnapshot(fileName: string): IScriptSnapshot { let f = this.opts.fileSystem[fileName] if (f != null) return ScriptSnapshot.fromString(f) else return null } getNewLine() { return "\n" } getCurrentDirectory(): string { return "." } getDefaultLibFileName(options: CompilerOptions): string { return "no-default-lib.d.ts" } log(s: string): void { console.log("LOG", s) } trace(s: string): void { console.log("TRACE", s) } error(s: string): void { console.error("ERROR", s) } useCaseSensitiveFileNames(): boolean { return true } // resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; // directoryExists?(directoryName: string): boolean; } interface CachedApisInfo { apis: ApisInfo; decls: pxt.Map<Declaration>; } export interface CompletionSymbol { symbol: SymbolInfo; weight: number; } // compiler service context export let service: LanguageService; export let host: Host; export let lastApiInfo: CachedApisInfo | undefined; export let lastGlobalNames: pxt.Map<SymbolInfo> | undefined; export let lastBlocksInfo: BlocksInfo; export let lastLocBlocksInfo: BlocksInfo; // don't export, fuse is internal only let lastFuse: Fuse<SearchInfo>; let lastProjectFuse: Fuse<ProjectSearchInfo>; export let builtinItems: SearchInfo[]; export let blockDefinitions: pxt.Map<pxt.blocks.BlockDefinition>; export let tbSubset: pxt.Map<boolean | string>; function fileDiags(fn: string) { if (!/\.ts$/.test(fn)) return [] let d = service.getSyntacticDiagnostics(fn) if (!d || !d.length) d = service.getSemanticDiagnostics(fn) if (!d) d = [] return d } export function blocksInfoOp(apisInfoLocOverride: pxtc.ApisInfo, bannedCategories: string[]) { if (apisInfoLocOverride) { if (!lastLocBlocksInfo) { lastLocBlocksInfo = getBlocksInfo(apisInfoLocOverride, bannedCategories); } return lastLocBlocksInfo; } else { if (!lastBlocksInfo) { lastBlocksInfo = getBlocksInfo(lastApiInfo.apis, bannedCategories); } return lastBlocksInfo; } } export function getLastApiInfo(opts: CompileOptions) { if (!lastApiInfo) lastApiInfo = internalGetApiInfo(service.getProgram(), opts.jres) return lastApiInfo; } export function addApiInfo(opts: CompileOptions) { if (!opts.apisInfo) { const info = getLastApiInfo(opts); opts.apisInfo = U.clone(info.apis) } } export function cloneCompileOpts(opts: CompileOptions) { let newOpts = pxt.U.flatClone(opts) newOpts.fileSystem = pxt.U.flatClone(newOpts.fileSystem) return newOpts } export interface ServiceOps { reset: () => void; setOptions: (v: OpArg) => void; syntaxInfo: (v: OpArg) => SyntaxInfo; getCompletions: (v: OpArg) => CompletionInfo; compile: (v: OpArg) => CompileResult; decompile: (v: OpArg) => CompileResult; pydecompile: (v: OpArg) => transpile.TranspileResult; decompileSnippets: (v: OpArg) => string[]; assemble: (v: OpArg) => { words: number[]; }; py2ts: (v: OpArg) => transpile.TranspileResult; fileDiags: (v: OpArg) => KsDiagnostic[]; allDiags: () => CompileResult; format: (v: OpArg) => { formatted: string; pos: number; }; apiInfo: () => ApisInfo; snippet: (v: OpArg) => string; blocksInfo: (v: OpArg) => BlocksInfo; apiSearch: (v: OpArg) => SearchInfo[]; projectSearch: (v: OpArg) => ProjectSearchInfo[]; projectSearchClear: () => void; }; export type OpRes = string | void | SyntaxInfo | CompletionInfo | CompileResult | transpile.TranspileResult | { words: number[]; } | KsDiagnostic[] | { formatted: string; pos: number; } | ApisInfo | BlocksInfo | ProjectSearchInfo[] | {}; export type OpError = { errorMessage: string }; export type OpResOrError = OpRes | OpError; export function IsOpErr(res: OpResOrError): res is OpError { return !!(res as OpError).errorMessage; } const operations: ServiceOps = { reset: () => { service = ts.createLanguageService(host) lastApiInfo = undefined lastGlobalNames = undefined host.reset() }, setOptions: v => { host.setOpts(v.options) }, syntaxInfo: v => { let src: string = v.fileContent if (v.fileContent) { host.setFile(v.fileName, v.fileContent); } let opts = cloneCompileOpts(host.opts) opts.fileSystem[v.fileName] = src addApiInfo(opts); opts.syntaxInfo = { position: v.position, type: v.infoType }; const isPython = opts.target.preferredEditor == pxt.PYTHON_PROJECT_NAME; const isSymbolReq = opts.syntaxInfo.type === "symbol"; const isSignatureReq = opts.syntaxInfo.type === "signature"; if (isPython) { let res = transpile.pyToTs(opts) if (res.globalNames) lastGlobalNames = res.globalNames } else { // typescript opts.ast = true; host.setOpts(opts) const res = runConversionsAndCompileUsingService() const prog = service.getProgram() const tsAst = prog.getSourceFile(v.fileName) const tc = prog.getTypeChecker() if (isSymbolReq || isSignatureReq) { let tsNode = findInnerMostNodeAtPosition(tsAst, v.position); if (tsNode) { if (isSymbolReq) { const symbol = tc.getSymbolAtLocation(tsNode); if (symbol) { let pxtSym = getPxtSymbolFromTsSymbol(symbol, opts.apisInfo, tc) opts.syntaxInfo.symbols = [pxtSym]; opts.syntaxInfo.beginPos = tsNode.getStart(); opts.syntaxInfo.endPos = tsNode.getEnd(); } } else if (isSignatureReq) { const pxtCall = tsNode?.pxt?.callInfo if (pxtCall) { const pxtSym = opts.apisInfo.byQName[pxtCall.qName] opts.syntaxInfo.symbols = [pxtSym]; opts.syntaxInfo.beginPos = tsNode.getStart(); opts.syntaxInfo.endPos = tsNode.getEnd(); const tsCall = getParentCallExpression(tsNode) if (tsCall) { const argIdx = findCurrentCallArgIdx(tsCall, tsNode, v.position) opts.syntaxInfo.auxResult = argIdx } } } } } } if (isSymbolReq && !opts.syntaxInfo.symbols?.length) { const possibleKeyword = getWordAtPosition(v.fileContent, v.position); if (possibleKeyword) { // In python if range() is used in a for-loop, we don't convert // it to a function call when going to TS (we just convert it to // a regular for-loop). Because our symbol detection is based off // of the TS, we won't get a symbol result for range at this position // in the file. This special case makes sure we return the same help // as a standalone call to range(). if (isPython && possibleKeyword.text === "range") { const apiInfo = getLastApiInfo(opts).apis; if (apiInfo.byQName["_py.range"]) { opts.syntaxInfo.symbols = [apiInfo.byQName["_py.range"]]; opts.syntaxInfo.beginPos = possibleKeyword.start; opts.syntaxInfo.endPos = possibleKeyword.end; } } else { const help = getHelpForKeyword(possibleKeyword.text, isPython); if (help) { opts.syntaxInfo.auxResult = { documentation: help, displayString: displayStringForKeyword(possibleKeyword.text, isPython), }; opts.syntaxInfo.beginPos = possibleKeyword.start; opts.syntaxInfo.endPos = possibleKeyword.end; } } } } if (opts.syntaxInfo.symbols?.length) { const apiInfo = getLastApiInfo(opts).apis; if (isPython) { opts.syntaxInfo.symbols = opts.syntaxInfo.symbols.map(s => { // symbol info gathered during the py->ts compilation phase // is less precise than the symbol info created when doing // a pass over ts, so we prefer the latter if available return apiInfo.byQName[s.qName] || s }) } if (isSymbolReq) { opts.syntaxInfo.auxResult = opts.syntaxInfo.symbols.map(s => displayStringForSymbol(s, isPython, apiInfo)) } } return opts.syntaxInfo }, getCompletions: v => { return getCompletions(v) }, compile: v => { host.setOpts(v.options) const res = runConversionsAndCompileUsingService() timesToMs(res); return res }, decompile: v => { host.setOpts(v.options) return decompile(service.getProgram(), v.options, v.fileName, false); }, pydecompile: v => { host.setOpts(v.options) return transpile.tsToPy(service.getProgram(), v.fileName); }, decompileSnippets: v => { host.setOpts(v.options) return decompileSnippets(service.getProgram(), v.options, false); }, assemble: v => { return { words: processorInlineAssemble(host.opts.target, v.fileContent) } }, py2ts: v => { addApiInfo(v.options) return transpile.pyToTs(v.options) }, fileDiags: v => patchUpDiagnostics(fileDiags(v.fileName)), allDiags: () => { // not comapatible with incremental compilation // host.opts.noEmit = true // TODO: "allDiags" sounds like it's just reading state // but it's actually kicking off a full compile. We should // do better about caching and returning cached results from // previous compiles. let res = runConversionsAndCompileUsingService(); timesToMs(res); if (host.opts.target.switches.time) console.log("DIAG-TIME", res.times) return res }, format: v => { const formatOptions = v.format; return pxtc.format(formatOptions.input, formatOptions.pos); }, apiInfo: () => { lastBlocksInfo = undefined; lastFuse = undefined; if (host.opts === emptyOptions) { // Host was reset, don't load apis with empty options return undefined; } lastApiInfo = internalGetApiInfo(service.getProgram(), host.opts.jres); return lastApiInfo.apis; }, snippet: v => { const o = v.snippet; if (!lastApiInfo) return undefined; const fn = lastApiInfo.apis.byQName[o.qName]; const n = lastApiInfo.decls[o.qName]; if (!fn || !n || !ts.isFunctionLike(n)) return undefined; const isPython = !!o.python // determine which names are taken for auto-generated variable names let takenNames: pxt.Map<SymbolInfo> = {} if (isPython && lastGlobalNames) { takenNames = lastGlobalNames } else { takenNames = lastApiInfo.apis.byQName } const { bannedCategories, screenSize } = v.runtime; const { apis } = lastApiInfo; const blocksInfo = blocksInfoOp(apis, bannedCategories); const checker = service && service.getProgram().getTypeChecker(); const snippetContext = { apis, blocksInfo, takenNames, bannedCategories, screenSize, checker, } const snippetNode = getSnippet(snippetContext, fn, n as FunctionLikeDeclaration, isPython) const snippet = snippetStringify(snippetNode) return snippet }, blocksInfo: v => blocksInfoOp(v as any, v.blocks && v.blocks.bannedCategories), apiSearch: v => { const SEARCH_RESULT_COUNT = 7; const search = v.search; const blockInfo = blocksInfoOp(search.localizedApis, v.blocks && v.blocks.bannedCategories); // caches if (search.localizedStrings) { pxt.Util.setLocalizedStrings(search.localizedStrings); } // Computes the preferred tooltip or block text to use for search (used for blocks that have multiple tooltips or block texts) const computeSearchProperty = (tooltipOrBlock: string | pxt.Map<string>, preferredSearch: string, blockDef: pxt.blocks.BlockDefinition): string => { if (!tooltipOrBlock) { return undefined; } if (typeof tooltipOrBlock === "string") { // There is only one tooltip or block text; use it return tooltipOrBlock; } if (preferredSearch) { // The block definition specifies a preferred tooltip / block text to use for search; use it return (<any>tooltipOrBlock)[preferredSearch]; } // The block definition does not specify which tooltip or block text to use for search; join all values with a space return Object.keys(tooltipOrBlock).map(k => (<pxt.Map<string>>tooltipOrBlock)[k]).join(" "); }; // Fill default parameters in block string const computeBlockString = (symbol: SymbolInfo): string => { if (symbol.attributes?._def) { let block = []; const blockDef = symbol.attributes._def; const compileInfo = pxt.blocks.compileInfo(symbol); // Construct block string from parsed blockdef for (let part of blockDef.parts) { switch (part.kind) { case "label": block.push(part.text); break; case "param": // In order, preference default value, var name, param name, blockdef param name let actualParam = compileInfo.definitionNameToParam[part.name]; block.push(actualParam?.defaultValue || part.varName || actualParam?.actualName || part.name); break; } } return block.join(" "); } return symbol.attributes.block; } // Join parameter jsdoc into a string const computeParameterString = (symbol: SymbolInfo): string => { const paramHelp = symbol.attributes?.paramHelp; if (paramHelp) { Object.keys(paramHelp).map(p => paramHelp[p]).join(" "); } return ""; } if (!builtinItems) { builtinItems = []; blockDefinitions = pxt.blocks.blockDefinitions(); for (const id in blockDefinitions) { const blockDef = blockDefinitions[id]; if (blockDef.operators) { for (const op in blockDef.operators) { const opValues = blockDef.operators[op]; opValues.forEach(v => builtinItems.push({ id, name: blockDef.name, jsdoc: typeof blockDef.tooltip === "string" ? <string>blockDef.tooltip : (<pxt.Map<string>>blockDef.tooltip)[v], block: v, field: [op, v], builtinBlock: true })); } } else { builtinItems.push({ id, name: blockDef.name, jsdoc: computeSearchProperty(blockDef.tooltip, blockDef.tooltipSearch, blockDef), block: computeSearchProperty(blockDef.block, blockDef.blockTextSearch, blockDef), builtinBlock: true }); } } } let subset: SymbolInfo[]; const fnweight = (fn: ts.pxtc.SymbolInfo): number => { const fnw = fn.attributes.weight || 50; const nsInfo = blockInfo.apis.byQName[fn.namespace]; const nsw = nsInfo ? (nsInfo.attributes.weight || 50) : 50; const ad = (nsInfo ? nsInfo.attributes.advanced : false) || fn.attributes.advanced const weight = (nsw * 1000 + fnw) * (ad ? 1 : 1e6); return weight; } if (!lastFuse || search.subset) { const weights: pxt.Map<number> = {}; let builtinSearchSet: SearchInfo[] = []; if (search.subset) { tbSubset = search.subset; builtinSearchSet = builtinItems.filter(s => !!tbSubset[s.id]); } if (tbSubset) { subset = blockInfo.blocks.filter(s => !!tbSubset[s.attributes.blockId]); } else { subset = blockInfo.blocks; builtinSearchSet = builtinItems; } let searchSet: SearchInfo[] = subset.map(s => { const mappedSi: SearchInfo = { id: s.attributes.blockId, qName: s.qName, name: s.name, namespace: s.namespace, block: computeBlockString(s), params: computeParameterString(s), jsdoc: s.attributes.jsDoc, localizedCategory: tbSubset && typeof tbSubset[s.attributes.blockId] === "string" ? tbSubset[s.attributes.blockId] as string : undefined, }; return mappedSi; }); // filter out built-ins from the main search set as those // should come from the built-in search set let builtinBlockIds: pxt.Map<Boolean> = {} builtinSearchSet.forEach(b => builtinBlockIds[b.id] = true) searchSet = searchSet.filter(b => !(b.id in builtinBlockIds)); let mw = 0; subset.forEach(b => { const w = weights[b.qName] = fnweight(b); mw = Math.max(mw, w); }); searchSet = searchSet.concat(builtinSearchSet); const fuseOptions = { shouldSort: true, threshold: 0.6, location: 0, distance: 100, maxPatternLength: 16, minMatchCharLength: 2, findAllMatches: false, caseSensitive: false, keys: [ { name: 'name', weight: 0.3 }, { name: 'namespace', weight: 0.1 }, { name: 'localizedCategory', weight: 0.1 }, { name: 'block', weight: 0.4375 }, { name: 'params', weight: 0.0625 }, { name: 'jsdoc', weight: 0.0625 } ], sortFn: function (a: any, b: any): number { const wa = a.qName ? 1 - weights[a.item.qName] / mw : 1; const wb = b.qName ? 1 - weights[b.item.qName] / mw : 1; // allow 10% wiggle room for weights return a.score * (1 + wa / 10) - b.score * (1 + wb / 10); } }; lastFuse = new Fuse(searchSet, fuseOptions); } const fns = lastFuse.search(search.term); return fns.slice(0, SEARCH_RESULT_COUNT); }, projectSearch: v => { const search = v.projectSearch; const searchSet = search.headers; if (!lastProjectFuse) { const fuseOptions = { shouldSort: true, threshold: 0.6, location: 0, distance: 100, maxPatternLength: 16, minMatchCharLength: 2, findAllMatches: false, caseSensitive: false, keys: [ { name: 'name', weight: 0.3 } ] }; lastProjectFuse = new Fuse(searchSet, fuseOptions); } const fns = lastProjectFuse.search(search.term); return fns; }, projectSearchClear: () => { lastProjectFuse = undefined; } } export function runConversionsAndCompileUsingService(): CompileResult { addApiInfo(host.opts) const prevFS = U.flatClone(host.opts.fileSystem); let res = runConversionsAndStoreResults(host.opts); if (res?.globalNames) { lastGlobalNames = res.globalNames } const newFS = host.opts.fileSystem host.opts.fileSystem = prevFS for (let k of Object.keys(newFS)) host.setFile(k, newFS[k]) // update version numbers if (res.diagnostics.length == 0) { host.opts.skipPxtModulesEmit = false host.opts.skipPxtModulesTSC = false const currKey = host.opts.target.isNative ? "native" : "js" if (!host.opts.target.switches.noIncr && host.pxtModulesOK) { host.opts.skipPxtModulesTSC = true if (host.opts.noEmit) host.opts.skipPxtModulesEmit = true else if (host.opts.target.isNative) host.opts.skipPxtModulesEmit = false // don't cache emit when debugging pxt_modules/* else if (host.pxtModulesOK == "js" && (!host.opts.breakpoints || host.opts.justMyCode)) host.opts.skipPxtModulesEmit = true } let ts2asm = compile(host.opts, service) res = { sourceMap: res.sourceMap, ...ts2asm, } if (res.needsFullRecompile || ((!res.success || res.diagnostics.length) && host.opts.clearIncrBuildAndRetryOnError)) { pxt.debug("triggering full recompile") pxt.tickEvent("compile.fullrecompile") host.opts.skipPxtModulesEmit = false; ts2asm = compile(host.opts, service); res = { sourceMap: res.sourceMap, ...ts2asm, } } if (res.diagnostics.every(d => !isPxtModulesFilename(d.fileName))) host.pxtModulesOK = currKey if (res.ast) { // keep api info up to date after each compile let ai = internalGetApiInfo(res.ast); if (ai) lastApiInfo = ai } } return res; } export function performOperation<T extends keyof ServiceOps>(op: T, arg: OpArg): OpResOrError { init(); let res: OpResOrError = null; if (operations.hasOwnProperty(op)) { try { let opFn = operations[op] res = opFn(arg) || {} } catch (e) { res = { errorMessage: e.stack } } } else { res = { errorMessage: "No such operation: " + op } } return res } function init() { if (!service) { host = new Host() service = ts.createLanguageService(host) } } }
the_stack
import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { LucidRow, LucidModel, ModelAdapterOptions } from '@ioc:Adonis/Lucid/Orm' import { FactoryModelContract, FactoryContextContract, FactoryBuilderContract, } from '@ioc:Adonis/Lucid/Factory' import { FactoryModel } from './FactoryModel' import { FactoryContext } from './FactoryContext' /** * Factory builder exposes the API to create/persist factory model instances. */ export class FactoryBuilder implements FactoryBuilderContract<FactoryModelContract<LucidModel>> { /** * Relationships to setup. Do note: It is possible to load one relationship * twice. A practical use case is to apply different states. For example: * * Make user with "3 active posts" and "2 draft posts" */ private withRelations: { name: string count?: number callback?: (factory: any) => void }[] = [] /** * Belongs to relationships are treated different, since they are * persisted before the parent model */ private withBelongsToRelations: { name: string count?: number callback?: (factory: any) => void }[] = [] /** * The current index. Updated by `makeMany` and `createMany` */ private currentIndex = 0 /** * Custom attributes to pass to model merge method */ private attributes: any /** * States to apply. One state can be applied only once and hence * a set is used. */ private appliedStates: Set<string> = new Set() /** * Custom context passed using `useCtx` method. It not defined, we will * create one inline inside `create` and `make` methods */ private ctx?: FactoryContextContract /** * Instead of relying on the `FactoryModelContract`, we rely on the * `FactoryModel`, since it exposes certain API's required for * the runtime operations and those API's are not exposed * on the interface to keep the API clean */ constructor(public model: FactoryModel<LucidModel>, private options?: ModelAdapterOptions) {} /** * Returns factory state */ private async getCtx(isStubbed: boolean) { if (isStubbed === true) { return new FactoryContext(isStubbed, undefined) } const client = this.model.model.$adapter.modelConstructorClient(this.model.model, this.options) const trx = await client.transaction() return new FactoryContext(isStubbed, trx) } /** * Returns attributes to merge for a given index */ private getMergeAttributes(index: number) { return Array.isArray(this.attributes) ? this.attributes[index] : this.attributes } /** * Returns a new model instance with filled attributes */ private async getModelInstance(ctx: FactoryContextContract): Promise<LucidRow> { const modelAttributes = await this.model.define(ctx) const modelInstance = this.model.newUpModelInstance(modelAttributes, ctx) this.model.mergeAttributes(modelInstance, this.getMergeAttributes(this.currentIndex), ctx) return modelInstance } /** * Apply states by invoking state callback */ private async applyStates(modelInstance: LucidRow, ctx: FactoryContextContract) { for (let state of this.appliedStates) { await this.model.getState(state)(modelInstance, ctx) } } /** * Compile factory by instantiating model instance, applying merge * attributes, apply state */ private async compile( isStubbed: boolean, callback?: (model: LucidRow, ctx: FactoryContextContract) => void ) { /** * Use pre-defined ctx or create a new one */ const ctx = this.ctx || (await this.getCtx(isStubbed)) /** * Newup the model instance */ const modelInstance = await this.getModelInstance(ctx) /** * Apply state */ this.applyStates(modelInstance, ctx) /** * Invoke custom callback (if defined) */ typeof callback === 'function' && callback(modelInstance, ctx) return { modelInstance, ctx, } } /** * Makes relationship instances. Call [[createRelation]] to * also persist them. */ private async makeRelations(modelInstance: LucidRow, ctx: FactoryContextContract) { for (let { name, count, callback } of this.withRelations) { const relation = this.model.getRelation(name) await relation.useCtx(ctx).make(modelInstance, callback, count) } } /** * Makes and persists relationship instances */ private async createRelations( modelInstance: LucidRow, ctx: FactoryContextContract, cycle: 'before' | 'after' ) { const relationships = cycle === 'before' ? this.withBelongsToRelations : this.withRelations for (let { name, count, callback } of relationships) { const relation = this.model.getRelation(name) await relation.useCtx(ctx).create(modelInstance, callback, count) } } /** * Define custom database connection */ public connection(connection: string): this { this.options = this.options || {} this.options.connection = connection return this } /** * Define custom query client */ public client(client: QueryClientContract): this { this.options = this.options || {} this.options.client = client return this } /** * Define custom context. Usually called by the relationships * to share the parent context with relationship factory */ public useCtx(ctx: FactoryContextContract): this { this.ctx = ctx return this } /** * Load relationship */ public with(name: string, count?: number, callback?: (factory: never) => void): this { const relation = this.model.getRelation(name) if (relation.relation.type === 'belongsTo') { this.withBelongsToRelations.push({ name, count, callback }) return this } this.withRelations.push({ name, count, callback }) return this } /** * Apply one or more states. Multiple calls to apply a single * state will be ignored */ public apply(...states: string[]): this { states.forEach((state) => this.appliedStates.add(state)) return this } /** * Fill custom set of attributes. They are passed down to the newUp * method of the factory */ public merge(attributes: any) { this.attributes = attributes return this } /** * Make model instance. Relationships are not processed with the make function. */ public async make(callback?: (model: LucidRow, ctx: FactoryContextContract) => void) { const { modelInstance, ctx } = await this.compile(true, callback) await this.model.hooks.exec('after', 'make', this, modelInstance, ctx) return modelInstance } /** * Returns a model instance without persisting it to the database. * Relationships are still loaded and states are also applied. */ public async makeStubbed(callback?: (model: LucidRow, ctx: FactoryContextContract) => void) { const { modelInstance, ctx } = await this.compile(true, callback) await this.model.hooks.exec('after', 'make', this, modelInstance, ctx) await this.model.hooks.exec('before', 'makeStubbed', this, modelInstance, ctx) const id = modelInstance.$primaryKeyValue || this.model.manager.getNextId(modelInstance) modelInstance[this.model.model.primaryKey] = id /** * Make relationships. The relationships will be not persisted */ await this.makeRelations(modelInstance, ctx) /** * Fire the after hook */ await this.model.hooks.exec('after', 'makeStubbed', this, modelInstance, ctx) return modelInstance } /** * Similar to make, but also persists the model instance to the * database. */ public async create(callback?: (model: LucidRow, ctx: FactoryContextContract) => void) { const { modelInstance, ctx } = await this.compile(false, callback) await this.model.hooks.exec('after', 'make', this, modelInstance, ctx) /** * Fire the before hook */ await this.model.hooks.exec('before', 'create', this, modelInstance, ctx) try { modelInstance.$trx = ctx.$trx /** * Create belongs to relationships before calling the save method. Even though * we can update the foriegn key after the initial insert call, we avoid it * for cases, where FK is a not nullable. */ await this.createRelations(modelInstance, ctx, 'before') /** * Persist model instance */ await modelInstance.save() /** * Create relationships. */ await this.createRelations(modelInstance, ctx, 'after') /** * Fire after hook before the transaction is committed, so that * hook can run db operations using the same transaction */ await this.model.hooks.exec('after', 'create', this, modelInstance, ctx) if (!this.ctx && ctx.$trx) { await ctx.$trx.commit() } return modelInstance } catch (error) { if (!this.ctx && ctx.$trx) { await ctx.$trx.rollback() } throw error } } /** * Create many of factory model instances */ public async makeStubbedMany( count: number, callback?: (model: LucidRow, ctx: FactoryContextContract) => void ) { let modelInstances: LucidRow[] = [] const counter = new Array(count).fill(0).map((_, i) => i) for (let index of counter) { this.currentIndex = index modelInstances.push(await this.makeStubbed(callback)) } return modelInstances } /** * Create and persist many of factory model instances */ public async createMany( count: number, callback?: (model: LucidRow, state: FactoryContextContract) => void ) { let modelInstances: LucidRow[] = [] const counter = new Array(count).fill(0).map((_, i) => i) for (let index of counter) { this.currentIndex = index modelInstances.push(await this.create(callback)) } return modelInstances } /** * Create many of the factory model instances */ public async makeMany( count: number, callback?: (model: LucidRow, state: FactoryContextContract) => void ) { let modelInstances: LucidRow[] = [] const counter = new Array(count).fill(0).map((_, i) => i) for (let index of counter) { this.currentIndex = index modelInstances.push(await this.make(callback)) } return modelInstances } }
the_stack
import * as React from 'react'; import { composeEventHandlers } from '@radix-ui/primitive'; import { Primitive } from '@radix-ui/react-primitive'; import { createContext } from '@radix-ui/react-context'; import { useBodyPointerEvents } from '@radix-ui/react-use-body-pointer-events'; import { useCallbackRef } from '@radix-ui/react-use-callback-ref'; import { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown'; import type * as Radix from '@radix-ui/react-primitive'; // We need to compute the total count of layers AND a running count of all layers // in order to find which layer is the deepest one. // This is use to only dismiss the deepest layer when using the escape key // because we bind the key listener to document so cannot take advantage of event.stopPropagation() const [TotalLayerCountProvider, useTotalLayerCount] = createTotalLayerCount(); const [RunningLayerCountProvider, usePreviousRunningLayerCount] = createRunningLayerCount(); // We need to compute the total count of layers which set `disableOutsidePointerEvents` to `true` AND // a running count of all the layers which set `disableOutsidePointerEvents` to `true` in order to determine // which layers should be dismissed when interacting outside. // (ie. all layers that do not have a child layer which sets `disableOutsidePointerEvents` to `true`) const [ TotalLayerCountWithDisabledOutsidePointerEventsProvider, useTotalLayerCountWithDisabledOutsidePointerEvents, ] = createTotalLayerCount('TotalLayerCountWithDisabledOutsidePointerEventsProvider'); const [ RunningLayerCountWithDisabledOutsidePointerEventsProvider, usePreviousRunningLayerCountWithDisabledOutsidePointerEvents, ] = createRunningLayerCount('RunningLayerCountWithDisabledOutsidePointerEventsProvider'); /* ------------------------------------------------------------------------------------------------- * DismissableLayer * -----------------------------------------------------------------------------------------------*/ const DISMISSABLE_LAYER_NAME = 'DismissableLayer'; type DismissableLayerElement = DismissableLayerImplElement; interface DismissableLayerProps extends DismissableLayerImplProps {} const DismissableLayer = React.forwardRef<DismissableLayerElement, DismissableLayerProps>( (props, forwardedRef) => { const runningLayerCount = usePreviousRunningLayerCount(); const isRootLayer = runningLayerCount === 0; const layer = <DismissableLayerImpl {...props} ref={forwardedRef} />; // if it's the root layer, we wrap it with our necessary root providers // (effectively we wrap the whole tree of nested layers) return isRootLayer ? ( <TotalLayerCountProvider> <TotalLayerCountWithDisabledOutsidePointerEventsProvider> {layer} </TotalLayerCountWithDisabledOutsidePointerEventsProvider> </TotalLayerCountProvider> ) : ( layer ); } ); DismissableLayer.displayName = DISMISSABLE_LAYER_NAME; /* -----------------------------------------------------------------------------------------------*/ type DismissableLayerImplElement = React.ElementRef<typeof Primitive.div>; type PrimitiveDivProps = Radix.ComponentPropsWithoutRef<typeof Primitive.div>; interface DismissableLayerImplProps extends PrimitiveDivProps { /** * When `true`, hover/focus/click interactions will be disabled on elements outside * the `DismissableLayer`. Users will need to click twice on outside elements to * interact with them: once to close the `DismissableLayer`, and again to trigger the element. */ disableOutsidePointerEvents?: boolean; /** * Event handler called when the escape key is down. * Can be prevented. */ onEscapeKeyDown?: (event: KeyboardEvent) => void; /** * Event handler called when the a `pointerdown` event happens outside of the `DismissableLayer`. * Can be prevented. */ onPointerDownOutside?: (event: PointerDownOutsideEvent) => void; /** * Event handler called when the focus moves outside of the `DismissableLayer`. * Can be prevented. */ onFocusOutside?: (event: FocusOutsideEvent) => void; /** * Event handler called when an interaction happens outside the `DismissableLayer`. * Specifically, when a `pointerdown` event happens outside or focus moves outside of it. * Can be prevented. */ onInteractOutside?: (event: PointerDownOutsideEvent | FocusOutsideEvent) => void; /** Callback called when the `DismissableLayer` should be dismissed */ onDismiss?: () => void; } const DismissableLayerImpl = React.forwardRef< DismissableLayerImplElement, DismissableLayerImplProps >((props, forwardedRef) => { const { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props; const totalLayerCount = useTotalLayerCount(); const prevRunningLayerCount = usePreviousRunningLayerCount(); const runningLayerCount = prevRunningLayerCount + 1; const isDeepestLayer = runningLayerCount === totalLayerCount; const totalLayerCountWithDisabledOutsidePointerEvents = useTotalLayerCountWithDisabledOutsidePointerEvents(disableOutsidePointerEvents); const prevRunningLayerCountWithDisabledOutsidePointerEvents = usePreviousRunningLayerCountWithDisabledOutsidePointerEvents(); const runningLayerCountWithDisabledOutsidePointerEvents = prevRunningLayerCountWithDisabledOutsidePointerEvents + (disableOutsidePointerEvents ? 1 : 0); const containsChildLayerWithDisabledOutsidePointerEvents = runningLayerCountWithDisabledOutsidePointerEvents < totalLayerCountWithDisabledOutsidePointerEvents; // Disable pointer-events on `document.body` when at least one layer is disabling outside pointer events useBodyPointerEvents({ disabled: disableOutsidePointerEvents }); // Dismiss on escape useEscapeKeydown((event) => { // Only dismiss if it's the deepest layer. his is effectively mimicking // event.stopPropagation from the layer with disabled outside pointer events. if (isDeepestLayer) { onEscapeKeyDown?.(event); if (!event.defaultPrevented) { onDismiss?.(); } } }); // Dismiss on pointer down outside const { onPointerDownCapture: handlePointerDownCapture } = usePointerDownOutside((event) => { // Only dismiss if there's no deeper layer which disabled pointer events outside itself if (!containsChildLayerWithDisabledOutsidePointerEvents) { onPointerDownOutside?.(event); onInteractOutside?.(event); if (!event.defaultPrevented) { onDismiss?.(); } } }); // Dismiss on focus outside const { onBlurCapture: handleBlurCapture, onFocusCapture: handleFocusCapture } = useFocusOutside( (event) => { onFocusOutside?.(event); onInteractOutside?.(event); if (!event.defaultPrevented) { onDismiss?.(); } } ); // If we have disabled pointer events on body, we need to reset `pointerEvents: 'auto'` // on some layers. This depends on which layers set `disableOutsidePointerEvents` to `true`. // // NOTE: it's important we set it on ALL layers that need it as we cannot simply // set it on the deepest layer which sets `disableOutsidePointerEvents` to `true` and rely // on inheritence. This is because layers may be rendered in different portals where // inheritence wouldn't apply, so we need to set it explicity on its children too. const isBodyPointerEventsDisabled = totalLayerCountWithDisabledOutsidePointerEvents > 0; const shouldReEnablePointerEvents = isBodyPointerEventsDisabled && !containsChildLayerWithDisabledOutsidePointerEvents; return ( <RunningLayerCountProvider runningCount={runningLayerCount}> <RunningLayerCountWithDisabledOutsidePointerEventsProvider runningCount={runningLayerCountWithDisabledOutsidePointerEvents} > <Primitive.div {...layerProps} ref={forwardedRef} style={{ pointerEvents: shouldReEnablePointerEvents ? 'auto' : undefined, ...layerProps.style, }} onPointerDownCapture={composeEventHandlers( props.onPointerDownCapture, handlePointerDownCapture )} onBlurCapture={composeEventHandlers(props.onBlurCapture, handleBlurCapture)} onFocusCapture={composeEventHandlers(props.onFocusCapture, handleFocusCapture)} /> </RunningLayerCountWithDisabledOutsidePointerEventsProvider> </RunningLayerCountProvider> ); }); /* ------------------------------------------------------------------------------------------------- * Utility hooks * -----------------------------------------------------------------------------------------------*/ const POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside'; const FOCUS_OUTSIDE = 'dismissableLayer.focusOutside'; type PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }>; type FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }>; /** * Sets up `pointerdown` listener which listens for events outside a react subtree. * * We use `pointerdown` rather than `pointerup` to mimic layer dismissing behaviour * present in OS which usually happens on `pointerdown`. * * Returns props to pass to the node we want to check for outside events. */ function usePointerDownOutside(onPointerDownOutside?: (event: PointerDownOutsideEvent) => void) { const handlePointerDownOutside = useCallbackRef(onPointerDownOutside) as EventListener; const isPointerInsideReactTreeRef = React.useRef(false); React.useEffect(() => { const handlePointerDown = (event: PointerEvent) => { const target = event.target; if (target && !isPointerInsideReactTreeRef.current) { const pointerDownOutsideEvent: PointerDownOutsideEvent = new CustomEvent( POINTER_DOWN_OUTSIDE, { bubbles: false, cancelable: true, detail: { originalEvent: event } } ); target.addEventListener(POINTER_DOWN_OUTSIDE, handlePointerDownOutside, { once: true }); target.dispatchEvent(pointerDownOutsideEvent); } isPointerInsideReactTreeRef.current = false; }; /** * if this hook executes in a component that mounts via a `pointerdown` event, the event * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid * this by delaying the event listener registration on the document. * This is not React specific, but rather how the DOM works, ie: * ``` * button.addEventListener('pointerdown', () => { * console.log('I will log'); * document.addEventListener('pointerdown', () => { * console.log('I will also log'); * }) * }); */ const timerId = window.setTimeout(() => { document.addEventListener('pointerdown', handlePointerDown); }, 0); return () => { window.clearTimeout(timerId); document.removeEventListener('pointerdown', handlePointerDown); }; }, [handlePointerDownOutside]); return { // ensures we check React component tree (not just DOM tree) onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true), }; } /** * Listens for when focus happens outside a react subtree. * Returns props to pass to the root (node) of the subtree we want to check. */ function useFocusOutside(onFocusOutside?: (event: FocusOutsideEvent) => void) { const handleFocusOutside = useCallbackRef(onFocusOutside) as EventListener; const isFocusInsideReactTreeRef = React.useRef(false); React.useEffect(() => { const handleFocus = (event: FocusEvent) => { const target = event.target; if (target && !isFocusInsideReactTreeRef.current) { const focusOutsideEvent: FocusOutsideEvent = new CustomEvent(FOCUS_OUTSIDE, { bubbles: false, cancelable: true, detail: { originalEvent: event }, }); target.addEventListener(FOCUS_OUTSIDE, handleFocusOutside, { once: true }); target.dispatchEvent(focusOutsideEvent); } }; document.addEventListener('focusin', handleFocus); return () => document.removeEventListener('focusin', handleFocus); }, [handleFocusOutside]); return { onFocusCapture: () => (isFocusInsideReactTreeRef.current = true), onBlurCapture: () => (isFocusInsideReactTreeRef.current = false), }; } /* ------------------------------------------------------------------------------------------------- * Layer counting utilities * -----------------------------------------------------------------------------------------------*/ function createTotalLayerCount(displayName?: string) { const [TotalLayerCountProviderImpl, useTotalLayerCountContext] = createContext( 'TotalLayerCount', { total: 0, onTotalIncrease: () => {}, onTotalDecrease: () => {} } ); const TotalLayerCountProvider: React.FC = ({ children }) => { const [total, setTotal] = React.useState(0); return ( <TotalLayerCountProviderImpl total={total} onTotalIncrease={React.useCallback(() => setTotal((n) => n + 1), [])} onTotalDecrease={React.useCallback(() => setTotal((n) => n - 1), [])} > {children} </TotalLayerCountProviderImpl> ); }; if (displayName) { TotalLayerCountProvider.displayName = displayName; } function useTotalLayerCount(counted = true) { const { total, onTotalIncrease, onTotalDecrease } = useTotalLayerCountContext('TotalLayerCountConsumer'); React.useLayoutEffect(() => { if (counted) { onTotalIncrease(); return () => onTotalDecrease(); } }, [counted, onTotalIncrease, onTotalDecrease]); return total; } return [TotalLayerCountProvider, useTotalLayerCount] as const; } function createRunningLayerCount(displayName?: string) { const [RunningLayerCountProviderImp, useRunningLayerCount] = createContext('RunningLayerCount', { count: 0, }); const RunningLayerCountProvider: React.FC<{ runningCount: number }> = (props) => { const { children, runningCount } = props; return ( <RunningLayerCountProviderImp count={runningCount}>{children}</RunningLayerCountProviderImp> ); }; if (displayName) { RunningLayerCountProvider.displayName = displayName; } function usePreviousRunningLayerCount() { const context = useRunningLayerCount('RunningLayerCountConsumer'); return context.count || 0; } return [RunningLayerCountProvider, usePreviousRunningLayerCount] as const; } const Root = DismissableLayer; export { DismissableLayer, // Root, }; export type { DismissableLayerProps };
the_stack
import uuid from 'uuid/v4'; import ActiveModel from 'models/ActiveModel.js'; import serializer from 'utils/serializer.js'; import GameState from 'tactics/GameState.js'; import ServerError from 'server/Error.js'; const gameKeys = new Set([ 'createdBy', 'isPublic', ]); const stateKeys = new Set([ 'type', 'randomFirstTurn', 'randomHitChance', 'turnTimeLimit', 'teams', ]); export default class Game extends ActiveModel { protected data: { id: string playerRequest: any state: GameState forkOf: any isPublic: boolean createdAt: Date } constructor(data) { super(); data.state.on('*', event => { // Clear a player's rejected requests when their turn starts. if (data.playerRequest) { if (event.type === 'startTurn') { const playerId = data.state.teams[event.data.teamId].playerId; const oldRejected = data.playerRequest.rejected; const newRejected = [ ...oldRejected ].filter(([k,v]) => !k.startsWith(`${playerId}:`)); if (newRejected.length !== oldRejected.size) { if (newRejected.length) data.playerRequest.rejected = new Map(newRejected); else data.playerRequest = null; } } else if (event.type === 'endGame') data.playerRequest = null; } this.emit('change:state'); }); this.data = data; } static create(gameOptions) { const gameData:any = { id: uuid(), createdAt: new Date(), playerRequest: null, }; const stateData:any = {}; Object.keys(gameOptions).forEach(option => { if (stateKeys.has(option)) stateData[option] = gameOptions[option]; else if (gameKeys.has(option)) gameData[option] = gameOptions[option]; }); /* * Use the default turn time limit if this is a multiplayer game */ if (stateData.turnTimeLimit === undefined) { for (const team of stateData.teams) { if (team && team.playerId === stateData.teams[0].playerId) continue; stateData.turnTimeLimit = 604800; break; } } gameData.state = GameState.create(stateData); return new Game(gameData); } get id() { return this.data.id; } get state() { return this.data.state; } get forkOf() { return this.data.forkOf; } get isFork() { return !!this.data.forkOf; } get isPublic() { return this.data.isPublic; } get createdAt() { return this.data.createdAt; } checkout(playerId, checkoutAt) { let changed = false; for (const team of this.data.state.teams) { if (team?.playerId === playerId && team.checkoutAt < checkoutAt) { team.checkoutAt = checkoutAt; changed = true; } } if (changed) this.emit('change:checkout'); return changed; } submitAction(playerId, action) { if (this.data.state.endedAt) throw new ServerError(409, 'The game has ended'); const playerRequest = this.data.playerRequest; if (playerRequest?.status === 'pending') throw new ServerError(409, `A '${playerRequest.type}' request is still pending`); const myTeams = this.data.state.teams.filter(t => t.playerId === playerId); if (myTeams.length === 0) throw new ServerError(403, 'You are not a player in this game.'); if (!Array.isArray(action)) action = [ action ]; if (action[0].type === 'surrender') action[0].declaredBy = playerId; else if (myTeams.includes(this.data.state.currentTeam)) action.forEach(a => a.teamId = this.data.state.currentTeamId); else throw new ServerError(409, 'Not your turn!'); this.data.state.submitAction(action); } submitPlayerRequest(playerId, requestType) { const oldRequest = this.data.playerRequest; if (oldRequest?.status === 'pending') throw new ServerError(409, `A '${requestType}' request is still pending`); if (this.data.state.teams.findIndex(t => t.playerId === playerId) === -1) throw new ServerError(401, 'You are not a player in this game.'); const newRequest = { createdAt: new Date(), createdBy: playerId, status: 'pending', type: requestType, accepted: new Set([ playerId ]), rejected: oldRequest?.rejected || new Map(), }; let saveRequest = false; if (requestType === 'undo') saveRequest = this.submitUndoRequest(newRequest); else if (requestType === 'truce') saveRequest = this.submitTruceRequest(newRequest); if (saveRequest) { this.data.playerRequest = newRequest; // The request is sent to all players. The initiator may cancel. this.emit({ type: `playerRequest`, data: newRequest, }); this.emit('change:submitPlayerRequest'); } } submitUndoRequest(request) { const state = this.data.state; const teams = state.teams; if (state.endedAt) { const myTeams = teams.filter(t => t.playerId === request.createdBy); const isPracticeGame = myTeams.length === teams.length; const isForkGame = !!this.data.forkOf; if (!isPracticeGame && !isForkGame) throw new ServerError(409, 'Game already ended'); } // Determine the team that is making the request. let team = state.currentTeam; let prevTeamId = (team.id === 0 ? teams.length : team.id) - 1; if (team.playerId === request.createdBy) { const prevTeam = teams[prevTeamId]; if (prevTeam.playerId === request.createdBy && state._actions.length === 0) team = prevTeam; } else { while (team.playerId !== request.createdBy) { prevTeamId = (team.id === 0 ? teams.length : team.id) - 1; team = teams[prevTeamId]; } } request.teamId = team.id; const canUndo = state.canUndo(team); if (canUndo === false) // The undo is rejected. throw new ServerError(403, 'You may not undo right now'); else if (canUndo === true) // The undo is auto-approved. state.undo(team); else if (request.rejected.has(`${request.createdBy}:${request.type}`)) throw new ServerError(403, `Your '${request.type}' request was already rejected`); else return true; } submitTruceRequest(request) { if (request.rejected.has(`${request.createdBy}:${request.type}`)) throw new ServerError(403, `Your '${request.type}' request was already rejected`); const state = this.data.state; if (state.endedAt) throw new ServerError(409, 'Game already ended'); else { const teams = state.teams; const myTeams = teams.filter(t => t.playerId === request.createdBy); const isPracticeGame = myTeams.length === teams.length; const isForkGame = !!this.data.forkOf; if (isPracticeGame || isForkGame) throw new ServerError(403, 'Truce not required for this game'); } return true; } acceptPlayerRequest(playerId, createdAt) { const request = this.data.playerRequest; if (request?.status !== 'pending') throw new ServerError(409, 'No request'); if (+createdAt !== +request.createdAt) throw new ServerError(409, 'No matching request'); if (request.accepted.has(playerId)) throw new ServerError(409, 'Already accepted request'); request.accepted.add(playerId); const teams = this.data.state.teams; const acceptedTeams = teams.filter(t => request.accepted.has(t.playerId)); this.emit({ type: `playerRequest:accept`, data: { playerId }, }); if (acceptedTeams.length === teams.length) { request.status = 'completed'; this.emit(`playerRequest:complete`); if (request.type === 'undo') { teams[request.teamId].setUsedUndo(); this.data.state.undo(teams[request.teamId], true); } else if (request.type === 'truce') this.data.state.end('truce'); } this.emit('change:acceptPlayerRequest'); } rejectPlayerRequest(playerId, createdAt) { const request = this.data.playerRequest; if (request?.status !== 'pending') throw new ServerError(409, 'No request'); if (+createdAt !== +request.createdAt) throw new ServerError(409, 'No matching request'); request.status = 'rejected'; request.rejected.set(`${request.createdBy}:${request.type}`, playerId); this.emit({ type: `playerRequest:reject`, data: { playerId }, }); this.emit('change:rejectPlayerRequest'); } cancelPlayerRequest(playerId, createdAt) { const request = this.data.playerRequest; if (request?.status !== 'pending') throw new ServerError(409, 'No request'); if (+createdAt !== +request.createdAt) throw new ServerError(409, 'No matching request'); if (playerId !== request.createdBy) throw new ServerError(403, 'Not your request'); request.status = 'cancelled'; this.emit(`playerRequest:cancel`); this.emit('change:cancelPlayerRequest'); } fork(clientPara, { turnId, vs, as }) { const forkGame = serializer.clone(this); if (turnId === undefined) turnId = forkGame.state.currentTurnId; if (turnId > forkGame.state.currentTurnId) turnId = forkGame.state.currentTurnId; if (vs === undefined) vs = 'you'; /* * If necessary, roll back to the previous playable turn. */ forkGame.state.revert(turnId); forkGame.state.autoPass(); while (turnId > 0) { if (forkGame.state.winningTeams.length < 2) { forkGame.state.revert(--turnId); continue; } const draw = forkGame.state.autoPass(); if (draw) { forkGame.state.revert(--turnId); continue; } break; } forkGame.createdAt = new Date(); forkGame.id = uuid(); forkGame.forkOf = { gameId:this.data.id, turnId:forkGame.state.currentTurnId }; forkGame.isPublic = false; const teams = forkGame.state.teams = forkGame.state.teams.map(t => t.fork()); if (vs === 'you') { if ( !this.data.state.endedAt && !this.data.forkOf && new Set(this.data.state.teams.map(t => t.playerId)).size > 1 ) { const myTeam = this.data.state.teams.find(t => t.playerId === clientPara.playerId); if (myTeam) { myTeam.setUsedSim(); this.emit('change:fork'); } } teams.forEach(t => t.join({}, clientPara)); forkGame.state.turnTimeLimit = null; forkGame.state.start(); } else if (vs === 'private') { if (teams[as] === undefined) throw new ServerError(400, "Invalid 'as' option value"); teams[as].join({}, clientPara); forkGame.state.startedAt = null; forkGame.state.turnStartedAt = null; forkGame.state.turnTimeLimit = 86400; } return forkGame; } }; serializer.addType({ name: 'Game', constructor: Game, schema: { type: 'object', required: [ 'id', 'isPublic', 'playerRequest', 'state', 'createdBy', 'createdAt' ], properties: { id: { type:'string', format:'uuid' }, isPublic: { type:'boolean' }, playerRequest: { type: [ 'object', 'null' ], required: [ 'type', 'status', 'accepted', 'rejected', 'createdBy', 'createdAt' ], properties: { type: { type: 'string', enum: [ 'undo', 'truce' ], }, status: { type: 'string', enum: [ 'pending', 'completed', 'rejected', 'cancelled' ], }, accepted: { type: 'array', subType: 'Set', items: { type: 'string', format: 'uuid', }, }, rejected: { type: 'array', subType: 'Map', items: { type: 'array', items: [ { type:'string' }, { type:'string' }, ], additionalItems: false, }, }, createdBy: { type:'string', format:'uuid' }, createdAt: { type:'string', subType:'Date' }, }, additionalProperties: false, }, forkOf: { type: 'object', required: [ 'gameId', 'turnId' ], properties: { gameId: { type:'string', format:'uuid' }, turnId: { type:'number', minimum:0 }, }, additionalProperties: false, }, state: { $ref:'GameState' }, createdBy: { type:'string', format:'uuid' }, createdAt: { type:'string', subType:'Date' }, }, additionalProperties: false, }, });
the_stack
import React, { useState, useEffect, useContext } from "react" import { NextPage } from "next" import Head from "next/head" import { useQuery, useMutation } from "@apollo/react-hooks" import Cookies from "js-cookie" import { useCheckoutEffect, createCheckout, checkoutQuery, checkoutLineItemsAdd, checkoutLineItemsUpdate, checkoutLineItemsRemove, checkoutCustomerAssociate, getCheckout } from "../../services/checkout" import Layout from "../../components/Layout/Layout" import CartContext from "../../components/Cart/CartContext" import { get } from "../../services/product" import { getProductsInfo } from "../../services/products" interface Props { shopLoading: any shopError: any product: any } const ProductPage: NextPage<Props> = ({ shopLoading, shopError, product }) => { const { isCartOpen, setIsCartOpen, checkout, setCheckout } = useContext( CartContext ) const [variantQuantity, setVariantQuantity] = useState(1) const checkoutId = Cookies.get("checkoutId") const handleQuantityChange = event => { setVariantQuantity(event.target.value) } const [ lineItemAddMutation, { data: lineItemAddData, loading: lineItemAddLoading, error: lineItemAddError } ] = useMutation(checkoutLineItemsAdd) useCheckoutEffect(lineItemAddData, "checkoutLineItemsAdd", setCheckout) const addVariantToCart = async (variantId, quantity) => { const variables = { checkoutId: checkoutId, lineItems: [{ variantId, quantity: parseInt(quantity, 10) }] } // TODO replace for each mutation in the checkout thingy. can we export them from there??? // create your own custom hook??? lineItemAddMutation({ variables }).then(res => { setIsCartOpen(true) }) } if (shopLoading) { return <p>Loading ...</p> } if (shopError) { return <p>{shopError.message}</p> } const variants = product.variants.edges.map(({ node }) => ({ ...node })) const variant = product.variants.edges[0].node const images = product.images.edges const imageSrc = images.length ? images[0].node.transformedSrc : "http://www.netum.vn/public/default/img/icon/default-product-image.png" const price = product.priceRange.minVariantPrice.amount const altText = images.length ? images[0].node.altText : "" return ( <> <Head> <title>{product.title} - Next Shopify Storefront</title> </Head> <Layout> <section className="text-gray-700 body-font overflow-hidden"> <div className="container px-5 py-24 mx-auto"> <div className="lg:w-4/5 mx-auto flex flex-wrap"> <img alt="ecommerce" className="lg:w-1/2 w-full lg:h-auto h-64 object-cover object-center rounded" src={imageSrc} /> <div className="lg:w-1/2 w-full lg:pl-10 lg:py-6 mt-6 lg:mt-0"> <h2 className="text-sm title-font border-0 mb-0 text-gray-500 tracking-widest"> BRAND NAME </h2> <h1 className="text-gray-900 mt-0 text-3xl title-font font-medium mb-1"> {product.title} </h1> <div className="flex mb-4"> <span className="flex items-center"> <svg fill="currentColor" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4 text-blue-500" viewBox="0 0 24 24" > <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <svg fill="currentColor" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4 text-blue-500" viewBox="0 0 24 24" > <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <svg fill="currentColor" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4 text-blue-500" viewBox="0 0 24 24" > <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <svg fill="currentColor" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4 text-blue-500" viewBox="0 0 24 24" > <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <svg fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4 text-blue-500" viewBox="0 0 24 24" > <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <span className="text-gray-600 ml-3">4 Reviews</span> </span> <span className="flex ml-3 pl-3 py-2 border-l-2 border-gray-200"> <a className="text-gray-500"> <svg fill="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-5 h-5" viewBox="0 0 24 24" > <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z" /> </svg> </a> <a className="ml-2 text-gray-500"> <svg fill="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-5 h-5" viewBox="0 0 24 24" > <path d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z" /> </svg> </a> <a className="ml-2 text-gray-500"> <svg fill="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-5 h-5" viewBox="0 0 24 24" > <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z" /> </svg> </a> </span> </div> <p className="leading-relaxed">{product.description}</p> <div className="flex mt-6 items-center pb-5 border-b-2 border-gray-200 mb-5"> <div className="flex"> <span className="mr-3">Color</span> <button className="border-2 border-gray-300 rounded-full w-6 h-6 focus:outline-none" /> <button className="border-2 border-gray-300 ml-1 bg-gray-700 rounded-full w-6 h-6 focus:outline-none" /> <button className="border-2 border-gray-300 ml-1 bg-blue-500 rounded-full w-6 h-6 focus:outline-none" /> </div> <div className="flex ml-6 items-center"> <span className="mr-3">Size</span> <div className="relative"> <select className="rounded border appearance-none border-gray-400 py-2 focus:outline-none focus:border-blue-500 text-base pl-3 pr-10"> <option>S</option> <option>M</option> <option>L</option> <option>XL</option> </select> <span className="absolute right-0 top-0 h-full w-10 text-center text-gray-600 pointer-events-none flex items-center justify-center"> <svg fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-4 h-4" viewBox="0 0 24 24" > <path d="M6 9l6 6 6-6" /> </svg> </span> </div> </div> </div> <label className="Product__option"> Qty:{" "} <input className="mb-4 border-2 rounded w-10 text-center" min="1" type="number" defaultValue={variantQuantity} onChange={handleQuantityChange} ></input> </label> <div className="flex"> <span className="title-font font-medium text-2xl text-gray-900"> ${parseFloat(price).toFixed(2)} </span> <button className="flex ml-auto text-white bg-blue-500 border-0 py-2 px-6 focus:outline-none hover:bg-blue-600 rounded" onClick={() => addVariantToCart(variant.id, variantQuantity) } > Add to cart </button> <button className="rounded-full w-10 h-10 bg-gray-200 p-0 border-0 inline-flex items-center justify-center text-gray-500 ml-4"> <svg fill="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} className="w-5 h-5" viewBox="0 0 24 24" > <path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" /> </svg> </button> </div> </div> </div> </div> </section> </Layout> </> ) } export async function getStaticProps({ ...ctx }) { const { producthandle } = ctx.params const product = await get({ handle: producthandle }) return { props: { // shopLoading: product.loading, // shopError: product.error, product: product.productByHandle } } } export async function getStaticPaths() { const products = await getProductsInfo() return { paths: products.map(({ node }) => "/products/" + node.handle), fallback: false } } export default ProductPage
the_stack
* @module adaptive-expressions */ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /* eslint-disable @typescript-eslint/no-unused-vars */ import { Constant } from './constant'; import { convertCSharpDateTimeToDayjs } from './datetimeFormatConverter'; import { Expression } from './expression'; import { EvaluateExpressionDelegate, ValueWithError } from './expressionEvaluator'; import { ExpressionType } from './expressionType'; import { MemoryInterface } from './memory'; import { Options } from './options'; import { ReturnType } from './returnType'; // eslint-disable-next-line lodash/import-scope import isEqual from 'lodash.isequal'; /** * Verify the result of an expression is of the appropriate type and return a string if not. * @param value Value to verify. * @param expression Expression that produced value. * @param child Index of child expression. */ export type VerifyExpression = (value: any, expression: Expression, child: number) => string | undefined; /** * Utility functions in AdaptiveExpression. */ export class FunctionUtils { /** * The default date time format string. */ public static readonly DefaultDateTimeFormat: string = 'YYYY-MM-DDTHH:mm:ss.SSS[Z]'; /** * Validate that expression has a certain number of children that are of any of the supported types. * @param expression Expression to validate. * @param minArity Minimum number of children. * @param maxArity Maximum number of children. * @param returnType Allowed return types for children. * If a child has a return type of Object then validation will happen at runtime. */ public static validateArityAndAnyType( expression: Expression, minArity: number, maxArity: number, returnType: ReturnType = ReturnType.Object ): void { if (expression.children.length < minArity) { throw new Error(`${expression} should have at least ${minArity} children.`); } if (expression.children.length > maxArity) { throw new Error(`${expression} can't have more than ${maxArity} children.`); } if ((returnType & ReturnType.Object) === 0) { for (const child of expression.children) { if ((child.returnType & ReturnType.Object) === 0 && (returnType & child.returnType) === 0) { throw new Error(FunctionUtils.buildTypeValidatorError(returnType, child, expression)); } } } } /** * Validate the number and type of arguments to a function. * @param expression Expression to validate. * @param optional Optional types in order. * @param types Expected types in order. */ public static validateOrder(expression: Expression, optional: ReturnType[], ...types: ReturnType[]): void { if (optional === undefined) { optional = []; } if (expression.children.length < types.length || expression.children.length > types.length + optional.length) { throw new Error( optional.length === 0 ? `${expression} should have ${types.length} children.` : `${expression} should have between ${types.length} and ${ types.length + optional.length } children.` ); } for (let i = 0; i < types.length; i++) { const child: Expression = expression.children[i]; const type: ReturnType = types[i]; if ( (type & ReturnType.Object) === 0 && (child.returnType & ReturnType.Object) === 0 && (type & child.returnType) === 0 ) { throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression)); } } for (let i = 0; i < optional.length; i++) { const ic: number = i + types.length; if (ic >= expression.children.length) { break; } const child: Expression = expression.children[ic]; const type: ReturnType = optional[i]; if ( (type & ReturnType.Object) === 0 && (child.returnType & ReturnType.Object) === 0 && (type & child.returnType) === 0 ) { throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression)); } } } /** * Validate at least 1 argument of any type. * @param expression Expression to validate. */ public static validateAtLeastOne(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER); } /** * Validate 1 or more numeric arguments. * @param expression Expression to validate. */ public static validateNumber(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, ReturnType.Number); } /** * Validate 1 or more string arguments. * @param expression Expression to validate. */ public static validateString(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, ReturnType.String); } /** * Validate there are two children. * @param expression Expression to validate. */ public static validateBinary(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 2, 2); } /** * Validate 2 numeric arguments. * @param expression Expression to validate. */ public static validateBinaryNumber(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 2, 2, ReturnType.Number); } /** * Validate 1 or 2 numeric arguments. * @param expression Expression to validate. */ public static validateUnaryOrBinaryNumber(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, 2, ReturnType.Number); } /** * Validate 2 or more than 2 numeric arguments. * @param expression Expression to validate. */ public static validateTwoOrMoreThanTwoNumbers(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 2, Number.MAX_VALUE, ReturnType.Number); } /** * Validate there are 2 numeric or string arguments. * @param expression Expression to validate. */ public static validateBinaryNumberOrString(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 2, 2, ReturnType.Number | ReturnType.String); } /** * Validate there is a single argument. * @param expression Expression to validate. */ public static validateUnary(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, 1); } /** * Validate there is a single argument. * @param expression Expression to validate. */ public static validateUnaryNumber(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, 1, ReturnType.Number); } /** * Validate there is a single string argument. * @param expression Expression to validate. */ public static validateUnaryString(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, 1, ReturnType.String); } /** * Validate there is one or two string arguments. * @param expression Expression to validate. */ public static validateUnaryOrBinaryString(expression: Expression): void { FunctionUtils.validateArityAndAnyType(expression, 1, 2, ReturnType.String); } /** * Validate there is a single boolean argument. * @param expression Expression to validate. */ public static validateUnaryBoolean(expression: Expression): void { FunctionUtils.validateOrder(expression, undefined, ReturnType.Boolean); } /** * Verify value is numeric. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyNumber(value: any, expression: Expression, _: number): string | undefined { let error: string; if (!FunctionUtils.isNumber(value)) { error = `${expression} is not a number.`; } return error; } /** * Verify value is numeric. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyNumberOrNumericList(value: any, expression: Expression, _: number): string | undefined { let error: string; if (FunctionUtils.isNumber(value)) { return error; } if (!Array.isArray(value)) { error = `${expression} is neither a list nor a number.`; } else { for (const elt of value) { if (!FunctionUtils.isNumber(elt)) { error = `${elt} is not a number in ${expression}.`; break; } } } return error; } /** * Verify value is numeric list. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyNumericList(value: any, expression: Expression, _: number): string | undefined { let error: string; if (!Array.isArray(value)) { error = `${expression} is not a list.`; } else { for (const elt of value) { if (!FunctionUtils.isNumber(elt)) { error = `${elt} is not a number in ${expression}.`; break; } } } return error; } /** * Verify value contains elements. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyContainer(value: any, expression: Expression, _: number): string | undefined { let error: string; if ( !(typeof value === 'string') && !Array.isArray(value) && !(value instanceof Map) && !(typeof value === 'object') ) { error = `${expression} must be a string, list, map or object.`; } return error; } /** * Verify value contains elements or null. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyContainerOrNull(value: unknown, expression: Expression, _: number): string | undefined { let error: string; if ( value != null && !(typeof value === 'string') && !Array.isArray(value) && !(value instanceof Map) && !(typeof value === 'object') ) { error = `${expression} must be a string, list, map or object.`; } return error; } /** * Verify value is not null or undefined. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if valid. */ public static verifyNotNull(value: any, expression: Expression, _: number): string | undefined { let error: string; if (value == null) { error = `${expression} is null.`; } return error; } /** * Verify value is an integer. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyInteger(value: any, expression: Expression, _: number): string | undefined { let error: string; if (!Number.isInteger(value)) { error = `${expression} is not a integer.`; } return error; } /** * Verify value is an list. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyList(value: any, expression: Expression): string | undefined { let error: string; if (!Array.isArray(value)) { error = `${expression} is not a list or array.`; } return error; } /** * Verify value is a string. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyString(value: any, expression: Expression, _: number): string | undefined { let error: string; if (typeof value !== 'string') { error = `${expression} is not a string.`; } return error; } /** * Verify an object is neither a string nor null. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyStringOrNull(value: any, expression: Expression, _: number): string | undefined { let error: string; if (typeof value !== 'string' && value !== undefined) { error = `${expression} is neither a string nor a null object.`; } return error; } /** * Verify value is a number or string or null. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyNumberOrStringOrNull(value: any, expression: Expression, _: number): string | undefined { let error: string; if (typeof value !== 'string' && value !== undefined && !FunctionUtils.isNumber(value)) { error = `${expression} is neither a number nor string`; } return error; } /** * Verify value is a number or string. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyNumberOrString(value: any, expression: Expression, _: number): string | undefined { let error: string; if (value === undefined || (!FunctionUtils.isNumber(value) && typeof value !== 'string')) { error = `${expression} is not string or number.`; } return error; } /** * Verify value is boolean. * @param value Value to check. * @param expression Expression that led to value. * @returns Error or undefined if invalid. */ public static verifyBoolean(value: any, expression: Expression, _: number): string | undefined { let error: string; if (typeof value !== 'boolean') { error = `${expression} is not a boolean.`; } return error; } /** * Evaluate expression children and return them. * @param expression Expression with children. * @param state Global state. * @param verify Optional function to verify each child's result. * @returns List of child values or error message. */ public static evaluateChildren( expression: Expression, state: MemoryInterface, options: Options, verify?: VerifyExpression ): { args: any[]; error: string } { const args: any[] = []; let value: any; let error: string; let pos = 0; for (const child of expression.children) { ({ value, error } = child.tryEvaluate(state, options)); if (error) { break; } if (verify !== undefined) { error = verify(value, child, pos); } if (error) { break; } args.push(value); ++pos; } return { args, error }; } /** * Generate an expression delegate that applies function after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static apply(func: (arg0: unknown[]) => unknown, verify?: VerifyExpression): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: any; const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); let error = childrenError; if (!error) { try { value = func(args); } catch (e) { error = e.message; } } return { value, error }; }; } /** * Generate an expression delegate that applies function after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static applyWithError( func: (arg0: any[]) => ValueWithError, verify?: VerifyExpression ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: any; const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); let error = childrenError; if (!error) { try { ({ value, error } = func(args)); } catch (e) { error = e.message; } } return { value, error }; }; } /** * Generate an expression delegate that applies function after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static applyWithOptionsAndError( func: (arg0: unknown[], options: Options) => { value: unknown; error: string }, verify?: VerifyExpression ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: unknown; const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); let error = childrenError; if (!error) { try { ({ value, error } = func(args, options)); } catch (e) { error = e.message; } } return { value, error }; }; } /** * Generate an expression delegate that applies function after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static applyWithOptions( func: (arg0: unknown[], options: Options) => unknown, verify?: VerifyExpression ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: unknown; const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); let error = childrenError; if (!error) { try { value = func(args, options); } catch (e) { error = e.message; } } return { value, error }; }; } /** * Generate an expression delegate that applies function on the accumulated value after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static applySequence(func: (arg0: any[]) => any, verify?: VerifyExpression): EvaluateExpressionDelegate { return FunctionUtils.apply((args: any[]): any => { const binaryArgs: any[] = [undefined, undefined]; let soFar: any = args[0]; for (let i = 1; i < args.length; i++) { binaryArgs[0] = soFar; binaryArgs[1] = args[i]; soFar = func(binaryArgs); } return soFar; }, verify); } /** * Generate an expression delegate that applies function on the accumulated value after verifying all children. * @param func Function to apply. * @param verify Function to check each arg for validity. * @returns Delegate for evaluating an expression. */ public static applySequenceWithError( func: (arg0: any[]) => any, verify?: VerifyExpression ): EvaluateExpressionDelegate { return FunctionUtils.applyWithError((args: any[]): any => { const binaryArgs: any[] = [undefined, undefined]; let soFar: any = args[0]; let value: any; let error: string; for (let i = 1; i < args.length; i++) { binaryArgs[0] = soFar; binaryArgs[1] = args[i]; ({ value, error } = func(binaryArgs)); if (error) { return { value, error }; } else { soFar = value; } } return { value: soFar, error: undefined }; }, verify); } /** * * @param args An array of arguments. * @param locale A locale string * @param maxArgsLength The max length of a given function. */ public static determineLocale(args: unknown[], maxArgsLength: number, locale = 'en-us'): string { if (args.length === maxArgsLength) { const lastArg = args[maxArgsLength - 1]; if (typeof lastArg === 'string') { locale = lastArg; } } return locale; } /** * * @param args An array of arguments. * @param format A format string. * @param locale A locale string. * @param maxArgsLength The max length of a given function. */ public static determineFormatAndLocale( args: unknown[], maxArgsLength: number, format: string, locale = 'en-us' ): { format: string; locale: string } { if (maxArgsLength >= 2) { if (args.length === maxArgsLength) { const lastArg = args[maxArgsLength - 1]; const secondLastArg = args[maxArgsLength - 2]; if (typeof lastArg === 'string' && typeof secondLastArg === 'string') { format = secondLastArg !== '' ? FunctionUtils.timestampFormatter(secondLastArg) : FunctionUtils.DefaultDateTimeFormat; locale = lastArg.substr(0, 2); //dayjs only support two-letter locale representattion } } else if (args.length === maxArgsLength - 1) { const lastArg = args[maxArgsLength - 2]; if (typeof lastArg === 'string') { format = FunctionUtils.timestampFormatter(lastArg); } } } return { format: format, locale: locale }; } /** * Timestamp formatter, convert C# datetime to day.js format. * @param formatter C# datetime format */ public static timestampFormatter(formatter: string): string { if (!formatter) { return FunctionUtils.DefaultDateTimeFormat; } let result = formatter; try { result = convertCSharpDateTimeToDayjs(formatter); } catch (e) { // do nothing } return result; } /** * State object for resolving memory paths. * @param expression Expression. * @param state Scope. * @param options Options used in evaluation. * @returns Return the accumulated path and the expression left unable to accumulate. */ public static tryAccumulatePath( expression: Expression, state: MemoryInterface, options: Options ): { path: string; left: any; error: string } { let path = ''; let left = expression; while (left !== undefined) { if (left.type === ExpressionType.Accessor) { path = (left.children[0] as Constant).value + '.' + path; left = left.children.length === 2 ? left.children[1] : undefined; } else if (left.type === ExpressionType.Element) { const { value, error } = left.children[1].tryEvaluate(state, options); if (error !== undefined) { return { path: undefined, left: undefined, error }; } if (FunctionUtils.isNumber(parseInt(value))) { path = `[${value}].${path}`; } else if (typeof value === 'string') { path = `['${value}'].${path}`; } else { return { path: undefined, left: undefined, error: `${left.children[1].toString()} doesn't return an int or string`, }; } left = left.children[0]; } else { break; } } // make sure we generated a valid path path = path.replace(/(\.*$)/g, '').replace(/(\.\[)/g, '['); if (path === '') { path = undefined; } return { path, left, error: undefined }; } /** * Is number helper function. * @param instance Input. * @returns True if the input is a number. */ public static isNumber(instance: any): instance is number { return instance != null && typeof instance === 'number' && !Number.isNaN(instance); } /** * Equal helper function. * @param args Input args. Compare the first param and second param. */ public static commonEquals(obj1: unknown, obj2: unknown): boolean { if (obj1 == null || obj2 == null) { return obj1 == null && obj2 == null; } // Array Comparison if (Array.isArray(obj1) && Array.isArray(obj2)) { if (obj1.length !== obj2.length) { return false; } return obj1.every((item, i) => FunctionUtils.commonEquals(item, obj2[i])); } // Object Comparison const propertyCountOfObj1 = FunctionUtils.getPropertyCount(obj1); const propertyCountOfObj2 = FunctionUtils.getPropertyCount(obj2); if (propertyCountOfObj1 >= 0 && propertyCountOfObj2 >= 0) { if (propertyCountOfObj1 !== propertyCountOfObj2) { return false; } const jsonObj1 = FunctionUtils.convertToObj(obj1); const jsonObj2 = FunctionUtils.convertToObj(obj2); return isEqual(jsonObj1, jsonObj2); } // Number Comparison if (FunctionUtils.isNumber(obj1) && FunctionUtils.isNumber(obj2)) { if (Math.abs(obj1 - obj2) < Number.EPSILON) { return true; } } try { return obj1 === obj2; } catch { return false; } } /** * @private */ private static buildTypeValidatorError(returnType: ReturnType, childExpr: Expression, expr: Expression): string { const names = Object.keys(ReturnType).filter((x): boolean => !(parseInt(x) >= 0)); const types = []; for (const name of names) { const value = ReturnType[name] as number; if ((returnType & value) !== 0) { types.push(name); } } if (types.length === 1) { return `${childExpr} is not a ${types[0]} expression in ${expr}.`; } else { const typesStr = types.join(', '); return `${childExpr} in ${expr} is not any of [${typesStr}].`; } } /** * Helper function of get the number of properties of an object. * @param obj An object. */ private static getPropertyCount(obj: unknown): number { let count = -1; if (obj != null && !Array.isArray(obj)) { if (obj instanceof Map) { count = obj.size; } else if (typeof obj === 'object' && !(obj instanceof Date)) { count = Object.keys(obj).length; } } return count; } /** * @private */ private static convertToObj(instance: unknown) { if (FunctionUtils.getPropertyCount(instance) >= 0) { const entries = instance instanceof Map ? Array.from(instance.entries()) : Object.entries(instance); return entries.reduce((acc, [key, value]) => ({ ...acc, [key]: FunctionUtils.convertToObj(value) }), {}); } else if (Array.isArray(instance)) { // Convert Array return instance.map((item) => FunctionUtils.convertToObj(item)); } return instance; } }
the_stack
import { Octokit } from '@octokit/rest'; import { GetResponseDataTypeFromEndpointMethod, GetResponseTypeFromEndpointMethod } from '@octokit/types'; import { actions } from '../../commons/utils/ActionsHelper'; import { showSimpleConfirmDialog } from '../../commons/utils/DialogHelper'; import { showSuccessMessage, showWarningMessage } from '../../commons/utils/NotificationsHelper'; import { store } from '../../pages/createStore'; /** * Exchanges the Access Code with the back-end to receive an Auth-Token * * @param {string} backendLink The address where the back-end microservice is deployed * @param {string} messageBody The message body. Must be URL-encoded * @return {Promise<Response>} A promise for a HTML response with an 'auth_token' field */ export async function exchangeAccessCode( backendLink: string, messageBody: string ): Promise<Response> { return await fetch(backendLink, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: messageBody }); } /** * Returns the Octokit instance saved in session state. * * This function allows for mocking Octokit behaviour in tests. */ export function getGitHubOctokitInstance(): any { const octokitObject = store.getState().session.githubOctokitObject; if (octokitObject === undefined) { return undefined; } else { return octokitObject.octokit; } } export async function checkIfFileCanBeOpened( octokit: Octokit, repoOwner: string, repoName: string, filePath: string ) { if (octokit === undefined) { showWarningMessage('Please log in and try again', 2000); return false; } if (filePath === '') { showWarningMessage('Please select a file!', 2000); return false; } type GetContentData = GetResponseDataTypeFromEndpointMethod<typeof octokit.repos.getContent>; let files: GetContentData; try { type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const results: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filePath }); files = results.data; } catch (err) { showWarningMessage('Connection denied or file does not exist.', 2000); console.error(err); return false; } if (Array.isArray(files)) { showWarningMessage("Can't open folder as a file!", 2000); return false; } return true; } /** * Returns an object containing 2 properties: 'canBeSaved' and 'saveType'. * 'canBeSaved' is a boolean that represents whether we should proceed with the save. * If the file can be saved, then 'saveType' is either 'Create' or 'Overwrite'. * * @param octokit The Octokit instance for the authenticated user * @param repoOwner The owner of the repository where the file is to be saved * @param repoName The name of the repository * @param filePath The filepath where the file will be saved to */ export async function checkIfFileCanBeSavedAndGetSaveType( octokit: Octokit, repoOwner: string, repoName: string, filePath: string ) { let saveType = ''; if (filePath === '') { showWarningMessage('No file name given.', 2000); return { canBeSaved: false, saveType: saveType }; } if (octokit === undefined) { showWarningMessage('Please log in and try again', 2000); return { canBeSaved: false, saveType: saveType }; } let files; try { type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const results: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filePath }); files = results.data; saveType = 'Overwrite'; } catch (err) { // 404 status means that the file could not be found. // In this case, the dialog should still continue as the user should be given // the option of creating a new file on their remote repository. if (err.status !== 404) { showWarningMessage('Connection denied or file does not exist.', 2000); console.error(err); return { canBeSaved: false, saveType: saveType }; } saveType = 'Create'; } if (Array.isArray(files)) { showWarningMessage("Can't save over a folder!", 2000); return { canBeSaved: false, saveType: saveType }; } return { canBeSaved: true, saveType: saveType }; } export async function checkIfUserAgreesToOverwriteEditorData() { return await showSimpleConfirmDialog({ contents: ( <div> <p>Warning: opening this file will overwrite the text data in the editor.</p> <p>Please click 'Confirm' to continue, or 'Cancel' to go back.</p> </div> ), negativeLabel: 'Cancel', positiveIntent: 'primary', positiveLabel: 'Confirm' }); } export async function checkIfUserAgreesToPerformOverwritingSave() { return await showSimpleConfirmDialog({ contents: ( <div> <p>Warning: You are saving over an existing file in the repository.</p> <p>Please click 'Confirm' to continue, or 'Cancel' to go back.</p> </div> ), negativeLabel: 'Cancel', positiveIntent: 'primary', positiveLabel: 'Confirm' }); } export async function openFileInEditor( octokit: Octokit, repoOwner: string, repoName: string, filePath: string ) { if (octokit === undefined) return; type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const results: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filePath }); const content = (results.data as any).content; if (content) { const newEditorValue = Buffer.from(content, 'base64').toString(); store.dispatch(actions.updateEditorValue(newEditorValue, 'playground')); store.dispatch(actions.playgroundUpdateGitHubSaveInfo(repoName, filePath, new Date())); showSuccessMessage('Successfully loaded file!', 1000); } } export async function performOverwritingSave( octokit: Octokit, repoOwner: string, repoName: string, filePath: string, githubName: string | null, githubEmail: string | null, commitMessage: string, content: string | null ) { if (octokit === undefined) return; githubEmail = githubEmail || 'No public email provided'; githubName = githubName || 'Source Academy User'; commitMessage = commitMessage || 'Changes made from Source Academy'; content = content || ''; const contentEncoded = Buffer.from(content, 'utf8').toString('base64'); try { type GetContentResponse = GetResponseTypeFromEndpointMethod<typeof octokit.repos.getContent>; const results: GetContentResponse = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filePath }); type GetContentData = GetResponseDataTypeFromEndpointMethod<typeof octokit.repos.getContent>; const files: GetContentData = results.data; // Cannot save over folder if (Array.isArray(files)) { return; } const sha = files.sha; await octokit.repos.createOrUpdateFileContents({ owner: repoOwner, repo: repoName, path: filePath, message: commitMessage, content: contentEncoded, sha: sha, committer: { name: githubName, email: githubEmail }, author: { name: githubName, email: githubEmail } }); store.dispatch(actions.playgroundUpdateGitHubSaveInfo(repoName, filePath, new Date())); showSuccessMessage('Successfully saved file!', 1000); } catch (err) { console.error(err); showWarningMessage('Something went wrong when trying to save the file.', 1000); } } export async function performCreatingSave( octokit: Octokit, repoOwner: string, repoName: string, filePath: string, githubName: string | null, githubEmail: string | null, commitMessage: string, content: string | null ) { if (octokit === undefined) return; githubEmail = githubEmail || 'No public email provided'; githubName = githubName || 'Source Academy User'; commitMessage = commitMessage || 'Changes made from Source Academy'; content = content || ''; const contentEncoded = Buffer.from(content, 'utf8').toString('base64'); try { await octokit.repos.createOrUpdateFileContents({ owner: repoOwner, repo: repoName, path: filePath, message: commitMessage, content: contentEncoded, committer: { name: githubName, email: githubEmail }, author: { name: githubName, email: githubEmail } }); store.dispatch(actions.playgroundUpdateGitHubSaveInfo(repoName, filePath, new Date())); showSuccessMessage('Successfully created file!', 1000); } catch (err) { console.error(err); showWarningMessage('Something went wrong when trying to save the file.', 1000); } } export async function performFolderDeletion( octokit: Octokit, repoOwner: string, repoName: string, filePath: string, githubName: string | null, githubEmail: string | null, commitMessage: string ) { if (octokit === undefined) return; githubEmail = githubEmail || 'No public email provided'; githubName = githubName || 'Source Academy User'; commitMessage = commitMessage || 'Changes made from Source Academy'; try { const results = await octokit.repos.getContent({ owner: repoOwner, repo: repoName, path: filePath }); const files = results.data; // This function must apply deletion to an entire folder if (!Array.isArray(files)) { showWarningMessage('Something went wrong when trying to delete the folder.', 1000); return; } for (let i = 0; i < files.length; i++) { const file = files[i]; await octokit.repos.deleteFile({ owner: repoOwner, repo: repoName, path: file.path, message: commitMessage, sha: file.sha }); } showSuccessMessage('Successfully deleted folder!', 1000); } catch (err) { console.error(err); showWarningMessage('Something went wrong when trying to delete the folder.', 1000); } }
the_stack
export = spritejs; // make it a module export as namespace spritejs; // keep a global namespace called Office type AnyAttrs = { [x: string]: any } /** * Sprite Node's Attributes. */ type BaseAttrs = { anchor: [number, number], anchorX: number, anchorY: number, bgcolor: string, border: [number, string], borderBottomLeftRadius: [number, number], borderBottomRightRadius: [number, number], borderColor: string, borderDash: number, borderDashOffset: number, borderRadius: [number, number, number, number, number, number, number, number], borderTopLeftRadius: [number, number], borderTopRightRadius: [number, number], borderWidth: number, boxSizing: 'content-box' | 'border-box', class: string, height: number, padding: [number, number, number, number], paddingBottom: number, paddingLeft: number, paddingRight: number, paddingTop: number, pos: [number, number], size: [number, number], sourceRect: Array<any>, texture: string, textureRect: [number, number, number, number], textureRepeat: boolean, width: number, id: string, name: string, className: string, /* class */ x: number, y: number, /* pos */ transformOrigin: [number, number], transform: string, translate: [number, number], rotate: number, scale: [number, number], skew: [number, number], opacity: number, zIndex: number, offsetPath: string, offsetDistance: number, offsetRotate: 'auto' | 'reverse' | number, pointerEvents: 'none' | 'visible' | 'visibleFill' | 'visibleStroke' | 'all', // none | visible | visibleFill | visibleStroke | all filter: 'none' | string, display: '' | string, }; type NumberOrArrayArgKey = 'scale' | 'skew' | 'anchor' | 'transformOrigin' type NumberOrArrayAttrs<T, K extends string> = { [index in K]: number | [number, number] } type AttrBorderRadius = 'borderRadius' type AttrPadding = 'padding' declare namespace spritejs { /** * Sprite Node's Attributes. */ type Attrs = BaseAttrs & AnyAttrs /** * attr's argument */ type ArgAttrs = Partial<Omit<BaseAttrs, NumberOrArrayArgKey | AttrBorderRadius | AttrPadding> & NumberOrArrayAttrs<BaseAttrs, NumberOrArrayArgKey> & { [k in AttrBorderRadius]: number | [number, number] | [number, number, number, number] | [number, number, number, number, number, number] | [number, number, number, number, number, number, number, number] } & { [k in AttrPadding]: number | [number, number] | [number, number, number] | [number | number | number | number] } & AnyAttrs> /** * Animation playstate. */ type playState = 'idel' | 'running' | 'pending' | 'paused' | 'finished'; /** * Custom timeline. https://github.com/spritejs/sprite-timeline */ interface Timeline { /** * Speed up or slow down the time-lapse. If playbackRate set to negative the time go backwards. */ playbackRate: number; } /** * Timing properties of an animation. */ interface Timing { /** * The number of milliseconds to delay the start of the animation. * Defaults to 0. */ delay?: number; /** * The number of milliseconds to delay after the end of an animation. * This is primarily of use when sequencing animations based on the end time of another animation. * Defaults to 0. */ endDelay?: number; /** * Dictates whether the animation's effects should be reflected by the element(s) * prior to playing ("backwards"), retained after the animation has completed playing ("forwards"), * or both. * @default "none" */ fill?: string; /** * The number of times the animation should repeat. * Defaults to 1, and can also take a value of Infinity to make it repeat for as long as the element exists. */ iterations?: number; /** * Whether the animation runs forwards (normal), backwards (reverse), * switches direction after each iteration (alternate), or runs backwards and switches * direction after each iteration (alternate-reverse). Defaults to "normal". */ direction?: string; /** * The number of milliseconds each iteration of the animation takes to complete. */ duration: number; /** * The rate of the animation's change over time. Accepts the pre-defined values "linear", * "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value * like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear". */ easing?: string; } /** * Web animation for sprite nodes. */ interface Animation { readonly effects: Record<string, any>; /** * The finished promise resolved when the animation's playstate is finished. */ readonly finished: Promise<void>; /** * The current frame props of the animation. */ readonly frame: Partial<Attrs>; /** * The playState of the animation. * Valid values are 'idel' or 'running' or 'pending' or 'paused' or 'finished'. */ readonly playState: playState; /** * The progress of the animation. * The value is between [0, 1]. */ readonly progress: number; /** * The ready promise resolved when the animation's playstate is ready. */ readonly ready: Promise<void>; /** * Timing properties of an animation. */ readonly timing: Timing; /** * Custom timeline. https://github.com/spritejs/sprite-timeline */ baseTimeline: Timeline; /** * Sets the rate at which the animation is being played back. */ playbackRate: number; /** * Apply animation effects to the animation. * @param effects The effect function maps. * @returns All effect function maps. */ applyEffects(effects: Record<string, Function>): Record<string, Function>; /** * Cancel the animation. * @param preserveState Whether the frame state is preserved when the animation is canceled. */ cancel(preserveState?: boolean): void; /** * Finish the animation. */ finish(): void; /** * Pause the animation. Set the timeline's playbackRate to 0. */ pause(): void; /** * Play the animation. */ play(): void; } /** * Sprite filter description. */ interface Filter { /** * The type of filter. It should be 'opacity', 'grayscale', 'drop-shadow' etc. */ type: string; /** * The arguments of the correspond filter. */ args: Array<string | number>; } interface Renderer2d { /** * The canvas instance. */ readonly canvas: HTMLCanvasElement | OffscreenCanvas; /** * If the renderer is a canvas2d render, canvasRenderer is CanvasRenderingContext2D, * otherwise is undefined. */ readonly canvasRenderer: CanvasRenderingContext2D | undefined; /** * If the renderer is a webgl render, glRenderer is WebGL2RenderingContext * or WebGLRenderingContext, otherwise is undefined. */ readonly glRenderer: WebGL2RenderingContext | WebGLRenderingContext | undefined; /** * Whether the rendering context is webgl2. */ readonly isWebGL2: boolean; /** * The renderer options. */ readonly options: Record<string, any>; /** * The transform matrix of the renderer. It affects all meshes. */ readonly globalTransformMatrix: Array<number>; /** * Creates webgl texture through an image, a bitmap or a canvas object. * @param img */ createTexture(img: any): WebGLTexture; /** * Load and create texture from an image URL. * loadTexture(textureURL, {useImageBitmap = false} = {}) * @param textureURL * @param options */ loadTexture(textureURL: string, options?: Record<string, any>): Promise<WebGLTexture>; /** * createText(text, {font = '16px arial', fillColor = null, strokeColor = null, strokeWidth = 1} = {}) * @param text * @param options */ createText(text: string, options?: Record<string, any>): WebGLTexture | Record<string, any>; /** * Create a webgl program. * createProgram({vertex, fragment, options} = {}) * @param options */ createProgram(options?: Record<string, any>): WebGLProgram; /** * Create a webgl programe as a pass channel. * createPassProgram({vertex = defaultPassVertex, fragment = defaultPassFragment, options} = {}) * @param options */ createPassProgram(options?: Record<string, any>): WebGLProgram; /** * Apply program to renderer. * @param program * @param attributeOptions */ useProgram(program: WebGLProgram, attributeOptions?: Record<string, any>): WebGLProgram; /** * Delete texture. * @param texture */ deleteTexture(texture: WebGLTexture): void; /** * Clear renderer. * @param rect */ clear(...rect: Array<number>): void; /** * drawMeshCloud(cloud, {clear = false, program = null} = {}) * @param cloud * @param options */ drawMeshCloud(cloud: MeshCloud, options?: Record<string, any>): void; /** * drawMeshes(meshes, {clear = false, program: drawProgram = null} = {}) * @param meshes * @param options */ drawMeshes(meshes: Array<Mesh2d>, options?: Record<string, any>): void; } /** * Event options */ interface EventOptions { /** * A Boolean indicating that events of this type will be dispatched to the registered listener * before being dispatched to any EventTarget beneath it in the DOM tree. * Defaults to false. */ capture: boolean; /** * A Boolean indicating that the listener should be invoked at most once after being added. * If true, the listener would be automatically removed when invoked. * Defaults to false. */ once?: boolean; } class Event { /** * constructor(originalEvent: any, {bubbles = null} = {}) * @param originalEvent * @param options */ constructor(originalEvent: any, options: Record<string, any>); /** * The original event. */ get originalEvent(): any; /** * The event type. */ get type(): string; /** * Whether the event bubbles. */ get bubbles(): boolean; /** * Event detail. */ get detail(): any; /** * Cancel bubbling. */ cancelBubble: boolean; /** * Event target. */ target: Node; currentTarget: Node; layerX: number; layerY: number; originalX: number; originalY: number; x: number; y: number; /** * Reset original event object. * @param originalEvent */ setOriginalEvent(originalEvent: any): void; /** * Stop bubbling. */ stopPropagation(): void; } interface Mesh2d { /** * The corresponding WebGLProgram. * Defaults to null. */ readonly program: WebGLProgram | null; /** * The bounding box of the mesh. [[x, y], [width, height]] */ readonly boundingBox: Array<any>; /** * The center point of the mesh. */ readonly boundingCenter: Array<any>; readonly fillRule: string; /** * Stroke lineWidth. */ readonly lineWidth: number; /** * Stroke lineCap. */ readonly lineCap: string; /** * Stroke lineJoin. */ readonly lineJoin: string; /** * Stroke miterLimit. */ readonly miterLimit: number; /** * Stroke style. */ readonly strokeStyle: string; /** * Stroke lineDash. */ readonly lineDash: Array<any> | null; /** * Stroke lineDash offset. */ readonly lineDashOffset: number; /** * Fill style. */ readonly fillStyle: string; /** * Color gradients. */ readonly gradient: any; /** * The texture of the mesh. */ readonly texture: any; /** * Whether enable opacity. */ readonly enableBlend: boolean; /** * Whether to use canvas to apply filter. */ readonly filterCanvas: boolean; /** * The filters applied to the mesh. */ readonly filter: string; /** * The transform matrix of the mesh. */ readonly transformMatrix: Array<number>; readonly transformScale: number; /** * The uniforms apply to the webgl program when drawing the mesh. */ readonly uniforms: any; /** * The pass channel of the mesh. */ readonly pass: Array<Mesh2d>; /** * The mesh data for rendering. */ readonly meshData: any; /** * The 2d polylines. https://github.com/mattdesl/svg-path-contours */ contours: Array<any>; /** * Force renderer to render or not to render alpha opacity. */ blend: boolean; /** * Use a custom WebGLProgram when drawing the mesh. * @param program */ setProgram(program: WebGLProgram | null): void; /** * Set shader attributes to program. * @param key * @param setter */ setAttribute(key: string, setter: Function | null): void; /** * Get opacity of the mesh. */ getOpacity(): number; /** * Set opacity of the mesh. * @param value * @returns the opacity of the mesh. */ setOpacity(value: number): void; /** * The point at a given distance along the path. * @param length * @returns the point at a given distance along the path. */ getPointAtLength(length: number): Array<number>; /** * The total length of the path. * @returns the total length of the path. */ getTotalLength(): number; accurate(scale: number): void; /** * Whether the mesh can ignore when rendering. */ canIgnore(): boolean; setClipPath(path: string): void; /** * Set stroke options. * @param stroke */ setStroke(stroke: any): this; /** * Set fill options. * @param fill */ setFill(fill: any): this; /** * Set texture of the mesh. * @param texture * @param options */ setTexture(texture: any, options?: Record<string, any>): this; setCircularGradient(gradient: any): this; setLinearGradient(gradient: any): this; setRadialGradient(gradient: any): this; /** * Set the color gradient of the mesh. * @param gradient */ setGradient(gradient: any): this; /** * Set the uniforms to the program before rendering. * @param uniforms */ setUniforms(uniforms: Record<string, any>): this; /** * Update the transform matrix. * @param m */ setTransform(...m: Array<number>): this; transform(...m: Array<number>): this; translate(x: number, y: number): this; rotate(rad: number, origin?: Array<number>): this; scale(x: number, y: number, origin?: Array<number>): this; skew(x: number, y: number, origin?: Array<number>): this; /** * Remove all filters. */ clearFilter(): this; /** * Update the color filter matrix. * @param m */ setColorTransform(...m: Array<number>): this; transformColor(...m: Array<number>): this; /** * Applies a Gaussian blur to the drawing. It defines the value of the standard deviation to * the Gaussian function, i.e., how many pixels on the screen blend into each other; thus, * a larger value will create more blur. A value of 0 leaves the input unchanged. * @param length */ blur(length: number): this; /** * Applies a linear multiplier to the drawing, making it appear brighter or darker. * A value under 1 darkens the image, while a value over 1 brightens it. A value of 0 * will create an image that is completely black, while a value of 1 leaves the input * unchanged. * @param p */ brightness(p: number): this; /** * Adjusts the contrast of the drawing. A value of 0 will create a drawing that is * completely black. A value of 1 leaves the drawing unchanged. * @param p */ contrast(p: number): this; /** * Applies a drop shadow effect to the drawing. A drop shadow is effectively a blurred, * offset version of the drawing's alpha mask drawn in a particular color, composited * below the drawing. * @param offsetX Specifies the horizontal distance of the shadow. * @param offsetY Specifies the vertical distance of the shadow. * @param blurRadius The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. * @param color */ dropShadow(offsetX: number, offsetY: number, blurRadius: number, color: Array<number>): this; /** * Converts the drawing to grayscale. A value of 1 is completely grayscale. * A value of 0 leaves the drawing unchanged. * @param p */ grayscale(p: number): this; /** * A CSS <angle>. Applies a hue rotation on the drawing. A value of 0deg leaves * the input unchanged. * @param deg */ hueRotate(deg: number): this; /** * Inverts the drawing. A value of 1 means complete inversion. A value of 0 * leaves the drawing unchanged. * @param p */ invert(p: number): this; /** * Applies transparency to the drawing. A value of 0 means completely transparent. * A value of 1 leaves the drawing unchanged. * @param p */ opacity(p: number): this; /** * Saturates the drawing. A value of 0 means completely un-saturated. A value of 1 * leaves the drawing unchanged. * @param p */ saturate(p: number): this; /** * Converts the drawing to sepia. A value of 1 means completely sepia. A value of 0 * leaves the drawing unchanged. * @param p */ sepia(p: number): this; /** * A CSS <url>. Takes an IRI pointing to an SVG filter element, which may be embedded * in an external XML file. * @param svgFilter */ url(svgFilter: string): this; /** * Determines whether a given point is within the fill or stroke shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the fill or stroke. * @param x * @param y * @param type 'fill'|'stroke' */ isPointCollision(x: number, y: number, type?: string): boolean; /** * Determines whether a given point is within the fill shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the fill. * @param x * @param y */ isPointInFill(x: number, y: number): boolean; /** * Determines whether a given point is within the stroke shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the stroke. * @param x * @param y */ isPointInStroke(x: number, y: number): boolean; /** * Add a pass channel to the mesh. * @param program * @param uniforms */ addPass(program: WebGLProgram | null, uniforms?: Record<string, any>): void; } /** * MeshCloud can draw multiple meshes of other elements on the canvas at the same time. */ interface MeshCloud { /** * Whether the meshes has fill color or stroke color. */ readonly hasCloudColor: boolean; /** * Whether the meshes has color filter. */ readonly hasCloudFilter: boolean; /** * Whether enable opacity. */ readonly enableBlend: boolean; /** * The mesh data for rendering. */ readonly meshData: any; readonly program: WebGLProgram; readonly uniforms: Record<string, any>; /** * The number of meshes drawn. */ amount: number; /** * Get the geometry mesh. */ mesh: Mesh2d; /** * Whether the mesh can ignore when rendering. */ canIgnore(): boolean; delete(idx: number): void; /** * Get filter string. * @param idx */ getFilter(idx: number): string; /** * Update the color filter matrix. * @param idx * @param m */ setColorTransform(idx: number, m: Array<number>): this; initBuffer(offset: number): void; /** * Get the color filter matrix. * @param idx */ getColorTransform(idx: number): Array<number>; transformColor(idx: number, m: Array<number>): this; /** * Set fill color to specified mesh. * @param idx * @param color */ setFillColor(idx: number, color: any): void; /** * Set stroke color to specified mesh. * @param idx * @param color */ setStrokeColor(idx: number, color: any): void; /** * Use a custom WebGLProgram when drawing the mesh. * @param program */ setProgram(program: WebGLProgram | null): void; /** * Set the uniforms to the program before rendering. * @param uniforms */ setUniforms(uniforms: Record<string, any>): this; /** * Get the rgba color of specified mesh. * @param idx */ getCloudRGBA(idx: number): string; /** * Converts the drawing to grayscale. A value of 1 is completely grayscale. * A value of 0 leaves the drawing unchanged. * @param idx * @param p */ grayscale(idx: number, p: number): this; /** * Adjusts the contrast of the drawing. A value of 0 will create a drawing that is * completely black. A value of 1 leaves the drawing unchanged. * @param idx * @param p */ brightness(idx: number, p: number): this; /** * Saturates the drawing. A value of 0 means completely un-saturated. A value of 1 * leaves the drawing unchanged. * @param idx * @param p */ saturate(idx: number, p: number): this; /** * Adjusts the contrast of the drawing. A value of 0 will create a drawing that is * completely black. A value of 1 leaves the drawing unchanged. * @param idx * @param p */ contrast(idx: number, p: number): this; /** * Inverts the drawing. A value of 1 means complete inversion. A value of 0 * leaves the drawing unchanged. * @param idx * @param p */ invert(idx: number, p: number): this; /** * Converts the drawing to sepia. A value of 1 means completely sepia. A value of 0 * leaves the drawing unchanged. * @param idx * @param p */ sepia(idx: number, p: number): this; /** * Applies transparency to the drawing. A value of 0 means completely transparent. * A value of 1 leaves the drawing unchanged. * @param idx * @param p */ opacity(idx: number, p: number): this; /** * A CSS <angle>. Applies a hue rotation on the drawing. A value of 0deg leaves * the input unchanged. * @param idx * @param deg */ hueRotate(idx: number, deg: number): this; /** * Update the transform matrix. * @param idx * @param m */ setTransform(idx: number, m: Array<number>): this; /** * Get the transform matrix of the specified mesh. * @param idx */ getTransform(idx: number): Array<number>; getTextureFrame(idx: number): Array<any>; setTextureFrames(frames: Array<any>, options?: Record<string, any>): void; setFrameIndex(idx: number, frameIndex: number): void; transform(idx: number, m: Array<number>): this; translate(idx: number, xy: Array<number>): this; rotate(idx: number, rad: number, origin?: Array<number>): this; scale(idx: number, xy: Array<number>, origin?: Array<number>): this; skew(idx: number, xy: Array<number>, origin?: Array<number>): this; /** * Determines whether a given point is within the fill or stroke shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the fill or stroke. * @param idx * @param xy * @param type 'fill'|'stroke' */ isPointCollision(idx: number, xy: Array<number>, type?: string): boolean; /** * Determines whether a given point is within the fill shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the fill. * @param idx * @param xy * @param type 'fill'|'stroke' */ isPointInFill(idx: number, xy: Array<number>): boolean; /** * Determines whether a given point is within the stroke shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the stroke. * @param idx * @param xy * @param type 'fill'|'stroke' */ isPointInStroke(idx: number, xy: Array<number>): boolean; } interface Resolution { /** * The width of the coordinate. */ width: number; /** * The height of the coordinate. */ height: number; } /** * Transitions enable you to define the transition between two states of an element. */ interface Trasition { /** * Cancel the trasition. * @param preserveState */ cancel(preserveState: boolean): void; /** * Finish the transition. */ end(): void; /** * Reverse the states of the transition. */ reverse(): void; /** * Set element attribute. * @param prop * @param val */ attr<T extends keyof BaseAttrs | string & {}>(prop: T, val: ArgAttrs[T]): Promise<void>; /** * Set element attributes. * @param attrs */ attr(attrs: ArgAttrs): Promise<void>; } /** * Returns a RectReadOnly which in essence describes a rectangle describing the smallest * rectangle that contains the entire target element. */ interface BoundingClientRect { /** * The x coordinate of the Rect's origin. */ x: number; /** * The y coordinate of the Rect's origin. */ y: number; /** * The width of the Rect. */ width: number; /** * The height of the Rect. */ height: number; /** * Returns the left coordinate value of the Rect (usually the same as x). */ left: number; /** * Returns the top coordinate value of the Rect (usually the same as y.) */ top: number; /** * Returns the right coordinate value of the Rect (usually the same as x + width). */ right: number; /** * Returns the bottom coordinate value of the Rect (usually the same as y + height). */ bottom: number; } /** * Arc element can draw an arc, sector or circle. */ export class Arc extends Ellipse { static Attr: any; } /** * Block is the base class of all block elements. */ export class Block extends Node { /** * Element's border size, equal to [content + padding + half of border]. */ get borderSize(): Array<number>; /** * Element's content box size, equal to [content + padding]. */ get clientSize(): Array<number>; /** * Element's content size. */ get contentSize(): Array<number>; /** * If there is a border. */ get hasBorder(): boolean; /** * Whether the element is visible. */ get isVisible(): boolean; /** * Get the element's geometry mesh data. */ get mesh(): Mesh2d; /** * Element's content box and border size, equal to [content + padding + border]. */ get offsetSize(): Array<number>; /** * Client box area before transform. */ get originalClientRect(): Array<number>; /** * Content rect before transform. */ get originalContentRect(): Array<number>; /** * Returns a RectReadOnly which in essence describes a rectangle describing the smallest * rectangle that contains the entire target element. */ getBoundingClientRect(): BoundingClientRect; /** * The element's attribute value change. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; /** * Recalculate the mesh geometries. */ updateContours(): void; } /** * Cloud can draw multiple meshes of other elements on the canvas at the same time. */ export class Cloud extends Node { /** * Create cloud elements with node elements as a template. * @param node * @param amount */ constructor(node: Mesh2d, amount: number); /** * Get the mesh-cloud object. */ get meshCloud(): MeshCloud; /** * Whether the element is visible. */ get isVisible(): boolean; /** * Get the number of elements drawn. */ get amount(): number; /** * Set the number of elements drawn. */ set amount(value: number); /** * Adjusts the contrast of the drawing. A value of 0 will create a drawing that is * completely black. A value of 1 leaves the drawing unchanged. * @param idx * @param p */ brightness(idx: number, p: number): this; /** * Applies a drop shadow effect to the drawing. A drop shadow is effectively a blurred, * offset version of the drawing's alpha mask drawn in a particular color, composited * below the drawing. * @param idx * @param p */ contrast(idx: number, p: number): this; /** * Delete the specified mesh data. * @param idx */ delete(idx: number): void; /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * Get the transform matrix of the specified mesh. * @param idx */ getTransform(idx: number): Array<number>; /** * Converts the drawing to grayscale. A value of 1 is completely grayscale. * A value of 0 leaves the drawing unchanged. * @param idx * @param p */ grayscale(idx: number, p: number): this; /** * A CSS <angle>. Applies a hue rotation on the drawing. A value of 0deg leaves * the input unchanged. * @param idx * @param deg */ hueRotate(idx: number, deg: number): this; /** * Inverts the drawing. A value of 1 means complete inversion. A value of 0 * leaves the drawing unchanged. * @param idx * @param p */ invert(idx: number, p: number): this; /** * Determines whether a given point is within the fill or stroke shape of an element. Normal hit * testing rules apply; the value of the pointer-events property on the element determines * whether a point is considered to be within the fill or stroke. * @param x * @param y * @param type 'fill'|'stroke' */ isPointCollision(x: number, y: number): boolean; /** * Applies transparency to the drawing. A value of 0 means completely transparent. * A value of 1 leaves the drawing unchanged. * @param idx * @param p */ setOpacity(idx: number, p: number): this; rotate(idx: number, rad: number, origin?: Array<number>): this; /** * Saturates the drawing. A value of 0 means completely un-saturated. A value of 1 * leaves the drawing unchanged. * @param idx * @param p */ saturate(idx: number, p: number): this; scale(idx: number, xy: Array<number>, origin?: Array<number>): this; /** * Update the color filter matrix. * @param idx * @param m */ setColorTransform(idx: number, m: Array<number>): this; /** * Set fill color to specified mesh. * @param idx * @param color */ setFillColor(idx: number, color: any): void; /** * Converts the drawing to sepia. A value of 1 means completely sepia. A value of 0 * leaves the drawing unchanged. * @param idx * @param p */ sepia(idx: number, p: number): this; /** * Set the resolution of the mesh. * @param resolution {width, height} */ setResolution(resolution: Resolution): void; /** * Set stroke color to specified mesh. * @param idx * @param color */ setStrokeColor(idx: number, color: any): void; /** * Update the transform matrix. * @param idx * @param m */ setTransform(idx: number, m: Array<number>): this; skew(idx: number, xy: Array<number>, origin?: Array<number>): this; transform(idx: number, m: Array<number>): this; transformColor(idx: number, m: Array<number>): this; translate(idx: number, xy: Array<number>): this; /** * Update mesh data. */ updateMesh(): void; } /** * The ellipse element can draw an elliptical arc, sector or ellipse. */ export class Ellipse extends Path { static Attr: any; /** * Whether the element is visible. */ get isVisible(): boolean; } export class Color { /** * constructor(r = 0, g = 0, b = 0, a = 0) * @param r * @param g * @param b * @param a */ constructor(r: number, g: number, b: number, a: number); get r(): number; set r(v: number); get g(): number; set g(v: number); get b(): number; set b(v: number); get a(): number; set a(v: number); get hex(): string; get rgba(): string; fromColor(color: any): this; } /** * Create a gradient object. */ class Gradient { /** * constructor({vector, colors}) * @param options */ constructor(options: Record<string, any>); /** * Returns the corresponding gradient string. */ toString(): string; } /** * The Group element creates a group. */ export class Group extends Block { /** * The child elements. */ get childNodes(): Array<any>; /** * The child elements. */ get children(): Array<any>; /** * Child elements sorted by zindex and zorder. */ get orderedChildren(): Array<any>; /** * Add elements to the group. * @param els */ append(...els: Array<any>): Array<any>; /** * Add an element to the group. * @param el */ appendChild(el: any): any; /** * Copy a group. If deep parameter is true, the child elements in the group * are copied at the same time. * @param deep */ cloneNode(deep?: boolean): Node; /** * Dispatch a mouse or touch event. * @param event */ dispatchPointerEvent(event: Event): void; /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * Returns the child element of the specified ID. * @param id */ getElementById(id: string): Node | null; /** * Returns the list of child elements for the specified className. * @param className */ getElementsByClassName(className: string): Array<Node>; /** * Returns a list of child elements for the specified name. * @param name */ getElementsByName(name: string): Array<Node>; /** * Returns a list of child elements of the specified type. * @param tagName */ getElementsByTagName(tagName: string): Array<Node>; /** * Before inserting the specified element into the ref element, if ref is null, * then el will be added to the end of the group. If ref is not null and is not * a child element of the group, an exception will be thrown. * @param el * @param ref */ insertBefore(el: any, ref: any): any; /** * Returns the specified child element based on the selector. * @param selector */ querySelector(selector: string): Node | null; /** * Returns a list of all matching child elements based on the selector. * @param selector */ querySelectorAll(selector: string): Array<Node>; /** * Replace the ref element with a new el element. If the ref element is not in the current group, * an exception is thrown. * @param el * @param ref */ replaceChild(el: any, ref: any): any; /** * Remove all child elements of the group. */ removeAllChildren(): void; /** * Moves the specified element out of the group. * @param el */ removeChild(el: any): any; /** * Reorder children in the order of zindex and zorder, which updates orderedChildren. */ reorder(): void; /** * Seal child elements to improve performance. */ seal(): any; /** * Set the context resolution of the element. * @param resolution */ setResolution(resolution: Resolution): void; /** * Update the geometric figure of the drawing. */ updateContours(): void; } interface TextImage { image?: HTMLCanvasElement, rect?: [number, number, number, number] } /** * Label draws a piece of text. */ export class Label extends Block { constructor(text: string); constructor(attrs?: Record<string, any>); /** * Element's content size. */ get contentSize(): Array<number>; get textImage(): TextImage; get textImageReady(): Promise<any>; get text(): string; set text(value: string); get textContent(): string; set textContent(value: string); /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * The action when an element attribute value is changed. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; /** * Update the geometric figure of the drawing. */ updateContours(): void; updateText(): Promise<any> | null; } /** * The layer element represents a layer that binds to a canvas context. */ export class Layer extends Group { constructor(options?: Record<string, any>); canvas: HTMLCanvasElement | OffscreenCanvas; /** * Whether to render automatically depends on the parameters when creating a layer. */ get autoRender(): boolean; /** * The display pixel ratio is determined according to the scene parameters. */ get displayRatio(): number; /** * The resolution height. */ get height(): number; /** * Get the layer object in the current paint context. */ get layer(): this; get gl(): WebGLRenderingContext | WebGL2RenderingContext | null; /** * If the canvas of the layer is offscreen, this property is true. */ get offscreen(): boolean; /** * Get the pass channel of the layer. */ get pass(): Array<Mesh2d>; /** * A promise, corresponding to the current frame rendering state, is only valid when autoRender is true. */ get prepareRender(): Promise<void>; /** * Get the rendered object in the current paint context. */ get renderer(): any; /** * The coordinate offset of the layer from the scene's container. */ get renderOffset(): Array<number>; /** * The timeline used to control the animations. */ get timeline(): Timeline; /** * The resolution width. */ get width(): number; /** * Add pass channel of the layer. * @param options */ addPass(options: Record<string, any>): void; deleteTexture(image: any): boolean; /** * Dispatch a mouse or touch event. * @param event */ dispatchPointerEvent(event: any): void; forceContextLoss(): boolean; /** * Force the canvas to be redrawn. */ forceUpdate(): void; /** * Get the frame buffer object. */ getFBO(): any; /** * The action when an element attribute value is changed. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; /** * Draw content onto canvas. * @param options */ render(options?: Record<string, any>): void; /** * Set the context resolution of the element. * @param resolution */ setResolution(resolution: Resolution): void; /** * Set animation frame to update layer periodically. * @param handler * @param options */ tick(handler: (t: number, p: number) => void, options?: Record<string, any>): any; /** * Convert the layer coordinates to DOM event coordinates. * @param x * @param y */ toGlobalPos(x: number, y: number): Array<number>; /** * Convert DOM event coordinates to layer coordinates. * @param x * @param y */ toLocalPos(x: number, y: number): Array<number>; } /** * LayerWorker inherits from a worker object. It can render a layer in the web worker. */ export class LayerWorker extends Worker { /** * The ID of the LayerWorker. */ get id(): string; /** * Set the resolution of the LayerWorker. * @param resolution */ setResolution(resolution: Resolution): void; /** * Get the resolution of the LayerWorker. * @param resolution */ getResolution(): Resolution; /** * Remove from parent. */ remove(): void; /** * When the element is added to the context tree, the function is called * and parent and zorder are assigned to the element. * @param parent * @param zOrder */ connect(parent: Node, zOrder: number): void; /** * When the element is removed from the context tree, the function is called * and the parent and zorder properties are removed. * @param parent */ disconnect(parent?: Node): void; // TODO: fix disconnect /** * Dispatch a mouse or touch event. * @param event */ dispatchPointerEvent(event: Event): void; } /** * Node is the common base class for all SpriteJS elements. */ export class Node { static Attr: any; constructor(attrs?: Record<string, any> | any); /** * The attribute object of the current element. */ attributes: Partial<Attrs>; /** * The parent of the node. */ readonly parent?: Node; readonly parentNode?: Node; /** * Group sort children by zIndex and zOrder. */ readonly zOrder?: number; readonly nodeType?: number; readonly nodeName?: string; readonly tagName?: string; readonly ownerDocument?: Record<string, any>; readonly namespaceURI?: string; /** * Get a list of ancestor elements for the current element. */ get ancestors(): Array<Node>; /** * Get all animations in the execution of the current element. */ get animations(): Set<Animation>; /** * Get the filters on the current element. */ get filters(): Array<Filter>; /** * Whether the element is visible. */ get isVisible(): boolean; /** * Get the layer object in the current paint context. */ get layers(): Layer; /** * Get the transform matrix of the current element relative to the parent element. */ get localMatrix(): Array<number>; get nextSibling(): Node | undefined; get previousSibling(): Node | undefined; get opacity(): number; /** * Get custom WebGLProgram. */ get program(): WebGLProgram; /** * Get the rendered object in the current paint context. */ get renderer(): any; /** * Get the transform matrix of the current element relative to the canvas coordinate system. */ get renderMatrix(): Array<number>; /** * Get uniforms of the WebGLProgram. */ get uniforms(): Record<string, any>; get className(): string; set className(value: string); get id(): string; set id(value: string); get name(): string; set name(value: string); get zIndex(): number; set zIndex(value: number); get shaderAttrs(): Record<string, any>; get worldPosition(): Array<number>; get worldRotation(): number; get worldScaling(): Array<number>; /** * Activate all animations in progress on the element. */ activateAnimations(): void; /** * Register event listeners. * @param type * @param listener * @param options */ addEventListener(type: string, listener: (event: Event) => void, options?: EventOptions): this; /** * Perform the animations. * @param frames * @param timing */ animate(frames: Array<ArgAttrs>, timing: Timing): Animation; /** * Get all attributes. */ attr(): Attrs; /** * Get attribute by key. * @param key */ attr<T extends keyof BaseAttrs | string & {}>(key: T): ArgAttrs[T]; /** * Set attribute by key and value. * @param key * @param value */ attr<T extends keyof BaseAttrs | string & {}>(key: T, value: ArgAttrs[T]): this; /** * Set attributes. * @param key */ attr(key: ArgAttrs): this; /** * Copy the entire element. * @param deep */ cloneNode(deep?: boolean): Node; /** * When the element is added to the context tree, the function is called * and parent and zorder are assigned to the element. * @param parent * @param zOrder */ connect(parent: Node, zOrder: number): void; contains(node: Node): boolean; /** * Stops all animations in progress on the element. */ deactivateAnimations(): void; /** * When the element is added to the context tree, the function is called * and parent and zorder are assigned to the element. * @param parent */ disconnect(parent?: Node): void; // TODO: fix disconnect /** * Dispatch a custom event. * @param event */ dispatchEvent(event: any, data?: any): void; /** * Dispatch a mouse or touch event. * @param event */ dispatchPointerEvent(event: Event): void; /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * Force the canvas to be redrawn. */ forceUpdate(): void; /** * Get element attribute values. * @param key */ getAttribute(key: string): any; /** * Get the event listeners. * @param type * @param options */ getListeners(type: string, options: EventOptions): Array<(event: Event) => void>; getNodeNearBy(distance: number): Node | undefined; /** * Transform the specified [x, y] coordinates relative of the layer to the coordinates * of the current element, with the anchor as the origin [0, 0]. * @param x * @param y */ getOffsetPosition(x: number, y: number): Array<number>; getWorldPosition(offsetX: number, offsetY: number): Array<number>; /** * Get the context resolution of the element. */ getResolution(): Resolution; /** * Determine whether the event coordinates intersect the element. * @param x * @param y */ isPointCollision(x: number, y: number): boolean; /** * The action when an element attribute value is changed. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; /** * Set the element attribute value. * @param key * @param value */ setAttribute(key: string, value: any): void; /** * Capture mouse pointer. */ setMouseCapture(): void; /** * Set custom WebGLProgram to the element. * @param program */ setProgram(program: WebGLProgram): void; /** * Set custom shader attributes to custom WebGLProgram. * @param attrName * @param setter */ setShaderAttribute(attrName: string, setter: Function | null): void; /** * Set custom uniforms to custom WebGLProgram. * @param uniforms */ setUniforms(uniforms: Record<string, any>): void; /** * Set the context resolution of the element. * @param resolution */ setResolution(resolution: Resolution): void; show(): void; hide(): void; /** * Release mouse pointer. */ releaseMouseCapture(): void; /** * Remove the element from its parent. */ remove(): boolean; /** * Remove all listeners of the specified type. * @param type * @param options */ removeAllListeners(type: string, options?: EventOptions): this; /** * Remove the element attribute value and restore it to the default value. * @param key */ removeAttribute(key: string): void; /** * Remove the event listener. * @param type * @param listener * @param options */ removeEventListener(type: string, listener: (event: Event) => void, options?: EventOptions): this; /** * Create a transition animation. * @param sec * @param easing */ transition(sec: number, easing?: string): Trasition; /** * Update the geometric figure of the drawing. */ updateContours(): void; } /** * The Parallel element draws a parallelogram. */ export class Parallel extends Polyline { /** * Whether the element is visible. */ get isVisible(): boolean; } /** * The path element draws an SVG path. */ export class Path extends Node { /** * Whether the element is visible. */ get isVisible(): boolean; /** * Get the element's geometry mesh data. */ get mesh(): Mesh2d; /** * Content box area before transform. */ get originalContentRect(): Array<number>; /** * Content box area before transform. */ get originalClientRect(): Array<number>; /** * Client center point before transform. */ get originalClientCenter(): Array<number>; /** * Get the svg-path string. */ get d(): string; /** * Set the svg-path string. */ set d(value: string); /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * Get the actual drawing area information of the element. */ getBoundingClientRect(): BoundingClientRect; /** * Get the total length of path. */ getPathLength(): number; /** * Get the original coordinates of the point where the specified length is located. * @param len */ getPointAtLength(len: number): Array<number>; /** * The action when an element attribute value is changed. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; /** * Update the geometric figure of the drawing. */ updateContours(): void; } /** * The Polyline element draws a polyline or polygon. */ export class Polyline extends Path { /** * Whether the element is visible. */ get isVisible(): boolean; } /** * The Rect element draws a rectangle. */ export class Rect extends Path { /** * Whether the element is visible. */ get isVisible(): boolean; } /** * The Regular element draws a regular polygon. */ export class Regular extends Polyline { } /** * The Ring element draws a torus or arc. */ export class Ring extends Path { /** * Whether the element is visible. */ get isVisible(): boolean; } interface WorkerOptions { worker: true, } /** * Scene manages one or more layers. */ export class Scene extends Group { constructor(options: Record<string, any>); /** * Get the container of Scene */ get container(): Element; /** * If there is offscreen canvas, different rendering modes will be choosen * according to the situation. */ get hasOffscreenCanvas(): boolean; /** * Get the pixel ratio. */ get displayRatio(): number; /** * Set the pixel ratio. */ set displayRatio(value: number); /** * Get the resolution height. */ get height(): number; /** * Set the resolution height. */ set height(value: number); /** * Get the adaptation mode. */ get mode(): string; /** * Set the adaptation mode. */ set mode(value: string); /** * Get the resolution width. */ get width(): number; /** * Set the resolution width. */ set width(value: number); /** * Add a layer to the scene. * @param layer */ appendChild(layer: any): any; /** * Force the canvas to be redrawn. */ forceUpdate(): void; /** * Before inserting the specified element into the ref element, if ref is null, * then el will be added to the end of the group. If ref is not null and is not * a child element of the group, an exception will be thrown. * @param layer * @param ref */ insertBefore(layer: any, ref: any): any; /** * Create and get the corresponding layer. * @param id * @param options */ layer(id: string, options: WorkerOptions): LayerWorker; /** * Create and get the corresponding layer. * @param id * @param options */ layer(id?: string, options?: Record<string, any>): Layer; /** * Create a 3d layer from sprite-extend-3d. * @param id * @param options */ layer3d(id: string, options: Record<string, any>): Layer; /** * Load resources asynchronously. * @param resources */ preload(...resources: Array<any>): Promise<Array<any>>; /** * Moves the specified element out of the group. * @param layer */ removeChild(layer: any): any; /** * When there is an offscreen canvas in the layer, this method will be called to render. */ render(): void; /** * Replace the ref element with a new el element. If the ref element is not in the * current group, an exception is thrown. * @param layer * @param ref */ replaceChild(layer: any, ref: any): any; /** * Resize according to the outer container. */ resize(): void; /** * Set the context resolution of the element. * @param resolution */ setResolution(resolution: Resolution): void; /** * Take a snapshot of the current scene. * @param options */ snapshot(options?: Record<string, any>): HTMLCanvasElement | OffscreenCanvas; } /** * Sprite elements can be used to draw pictures. */ export class Sprite extends Block { constructor(texture: string); constructor(attrs?: Record<string, any>); /** * Element's content size. */ get contentSize(): Array<number>; get textureImageReady(): Promise<any>; /** * Get a list of element related geometric meshes for rendering. * @param meshes */ draw(meshes?: Array<Mesh2d>): Array<Mesh2d>; /** * The action when an element attribute value is changed. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; } export class SpriteSvg extends Sprite { constructor(svgText: string); constructor(attrs?: Record<string, any>); get children(): Array<any>; get childNodes(): Array<any>; get svg(): HTMLOrSVGElement; /** * Set the resolution of the mesh. * @param resolution {width, height} */ setResolution(resolution: Resolution): void; /** * Dispatch a mouse or touch event. * @param event */ dispatchPointerEvent(event: Event): void; /** * Returns the child element of the specified ID. * @param id */ getElementById(id: string): Node | null; /** * Returns the list of child elements for the specified className. * @param className */ getElementsByClassName(className: string): Array<Node>; /** * Returns a list of child elements for the specified name. * @param name */ getElementsByName(name: string): Array<Node>; /** * Returns a list of child elements of the specified type. * @param tagName */ getElementsByTagName(tagName: string): Array<Node>; /** * Returns the specified child element based on the selector. * @param selector */ querySelector(selector: string): Node | null; /** * Returns a list of all matching child elements based on the selector. * @param selector */ querySelectorAll(selector: string): Array<Node>; /** * The element's attribute value change. * @param key * @param newValue * @param oldValue */ onPropertyChange(key: string, newValue: any, oldValue: any): void; } /** * The Star element draws a polygonal star. */ export class Star extends Polyline { } /** * The Triangle element draws a triangle. */ export class Triangle extends Polyline { /** * Whether the element is visible. */ get isVisible(): boolean; } namespace helpers { /** * Parse color to a RGBA string. * @param color */ export function parseColor(color: any): string | Gradient; /** * Convert the CSS <length> to number. * @param value * @param defaultWidth */ export function sizeToPixel(value: string, defaultWidth?: number): number; /** * Convert values to array, if the values is divided by spaces. * @param value * @param parseNumber */ export function toArray(value: any, parseNumber?: boolean): any; /** * Convert a value to string, if the value is not null. * @param value */ export function toString(value: any): string | null; /** * Convert a string value to number. * @param value */ export function toNumber(value: any): number | null; } /** * Create an element by nodeNome. * @param nodeName * @param attrs * @param children */ export function createElement(nodeName: string, attrs?: Record<string, any>, children?: Array<any>): Node; /** * Check if the object is a sprite node. * @param node */ export function isSpriteNode(node: any): boolean; /** * Register a class of Node to a specified nodeName. * @param Node * @param nodeName * @param nodeType */ export function registerNode(Node: any, nodeName?: string, nodeType?: number): void; /** * requestAnimation polyfill. * @param callback */ export function requestAnimationFrame(callback: (t: number) => void): any; /** * cancelAnimationFrame polyfill. * @param id */ export function cancelAnimationFrame(id: any): void; namespace ENV { /** * Container polyfill. */ export const Container: any; /** * createCanvas polyfill. */ export const createCanvas: Function | null; /** * loadImage polyfill. */ export const loadImage: Function | null; /** * createText polyfill. */ export const createText: Function | null; } }
the_stack
import { prettyByte } from "./utils/prettyByte"; import { ExtensionCodec, ExtensionCodecType } from "./ExtensionCodec"; import { getInt64, getUint64, UINT32_MAX } from "./utils/int"; import { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from "./utils/utf8"; import { createDataView, ensureUint8Array } from "./utils/typedArrays"; import { CachedKeyDecoder, KeyDecoder } from "./CachedKeyDecoder"; import { DecodeError } from "./DecodeError"; const enum State { ARRAY, MAP_KEY, MAP_VALUE, } type MapKeyType = string | number; const isValidMapKeyType = (key: unknown): key is MapKeyType => { const keyType = typeof key; return keyType === "string" || keyType === "number"; }; type StackMapState = { type: State.MAP_KEY | State.MAP_VALUE; size: number; key: MapKeyType | null; readCount: number; map: Record<string, unknown>; }; type StackArrayState = { type: State.ARRAY; size: number; array: Array<unknown>; position: number; }; type StackState = StackArrayState | StackMapState; const HEAD_BYTE_REQUIRED = -1; const EMPTY_VIEW = new DataView(new ArrayBuffer(0)); const EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer); // IE11: Hack to support IE11. // IE11: Drop this hack and just use RangeError when IE11 is obsolete. export const DataViewIndexOutOfBoundsError: typeof Error = (() => { try { // IE11: The spec says it should throw RangeError, // IE11: but in IE11 it throws TypeError. EMPTY_VIEW.getInt8(0); } catch (e: any) { return e.constructor; } throw new Error("never reached"); })(); const MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data"); const sharedCachedKeyDecoder = new CachedKeyDecoder(); export class Decoder<ContextType = undefined> { private totalPos = 0; private pos = 0; private view = EMPTY_VIEW; private bytes = EMPTY_BYTES; private headByte = HEAD_BYTE_REQUIRED; private readonly stack: Array<StackState> = []; public constructor( private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any, private readonly context: ContextType = undefined as any, private readonly maxStrLength = UINT32_MAX, private readonly maxBinLength = UINT32_MAX, private readonly maxArrayLength = UINT32_MAX, private readonly maxMapLength = UINT32_MAX, private readonly maxExtLength = UINT32_MAX, private readonly keyDecoder: KeyDecoder | null = sharedCachedKeyDecoder, ) {} private reinitializeState() { this.totalPos = 0; this.headByte = HEAD_BYTE_REQUIRED; this.stack.length = 0; // view, bytes, and pos will be re-initialized in setBuffer() } private setBuffer(buffer: ArrayLike<number> | BufferSource): void { this.bytes = ensureUint8Array(buffer); this.view = createDataView(this.bytes); this.pos = 0; } private appendBuffer(buffer: ArrayLike<number> | BufferSource) { if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) { this.setBuffer(buffer); } else { const remainingData = this.bytes.subarray(this.pos); const newData = ensureUint8Array(buffer); // concat remainingData + newData const newBuffer = new Uint8Array(remainingData.length + newData.length); newBuffer.set(remainingData); newBuffer.set(newData, remainingData.length); this.setBuffer(newBuffer); } } private hasRemaining(size: number) { return this.view.byteLength - this.pos >= size; } private createExtraByteError(posToShow: number): Error { const { view, pos } = this; return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`); } /** * @throws {DecodeError} * @throws {RangeError} */ public decode(buffer: ArrayLike<number> | BufferSource): unknown { this.reinitializeState(); this.setBuffer(buffer); const object = this.doDecodeSync(); if (this.hasRemaining(1)) { throw this.createExtraByteError(this.pos); } return object; } public *decodeMulti(buffer: ArrayLike<number> | BufferSource): Generator<unknown, void, unknown> { this.reinitializeState(); this.setBuffer(buffer); while (this.hasRemaining(1)) { yield this.doDecodeSync(); } } public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>): Promise<unknown> { let decoded = false; let object: unknown; for await (const buffer of stream) { if (decoded) { throw this.createExtraByteError(this.totalPos); } this.appendBuffer(buffer); try { object = this.doDecodeSync(); decoded = true; } catch (e) { if (!(e instanceof DataViewIndexOutOfBoundsError)) { throw e; // rethrow } // fallthrough } this.totalPos += this.pos; } if (decoded) { if (this.hasRemaining(1)) { throw this.createExtraByteError(this.totalPos); } return object; } const { headByte, pos, totalPos } = this; throw new RangeError( `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`, ); } public decodeArrayStream( stream: AsyncIterable<ArrayLike<number> | BufferSource>, ): AsyncGenerator<unknown, void, unknown> { return this.decodeMultiAsync(stream, true); } public decodeStream(stream: AsyncIterable<ArrayLike<number> | BufferSource>): AsyncGenerator<unknown, void, unknown> { return this.decodeMultiAsync(stream, false); } private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>, isArray: boolean) { let isArrayHeaderRequired = isArray; let arrayItemsLeft = -1; for await (const buffer of stream) { if (isArray && arrayItemsLeft === 0) { throw this.createExtraByteError(this.totalPos); } this.appendBuffer(buffer); if (isArrayHeaderRequired) { arrayItemsLeft = this.readArraySize(); isArrayHeaderRequired = false; this.complete(); } try { while (true) { yield this.doDecodeSync(); if (--arrayItemsLeft === 0) { break; } } } catch (e) { if (!(e instanceof DataViewIndexOutOfBoundsError)) { throw e; // rethrow } // fallthrough } this.totalPos += this.pos; } } private doDecodeSync(): unknown { DECODE: while (true) { const headByte = this.readHeadByte(); let object: unknown; if (headByte >= 0xe0) { // negative fixint (111x xxxx) 0xe0 - 0xff object = headByte - 0x100; } else if (headByte < 0xc0) { if (headByte < 0x80) { // positive fixint (0xxx xxxx) 0x00 - 0x7f object = headByte; } else if (headByte < 0x90) { // fixmap (1000 xxxx) 0x80 - 0x8f const size = headByte - 0x80; if (size !== 0) { this.pushMapState(size); this.complete(); continue DECODE; } else { object = {}; } } else if (headByte < 0xa0) { // fixarray (1001 xxxx) 0x90 - 0x9f const size = headByte - 0x90; if (size !== 0) { this.pushArrayState(size); this.complete(); continue DECODE; } else { object = []; } } else { // fixstr (101x xxxx) 0xa0 - 0xbf const byteLength = headByte - 0xa0; object = this.decodeUtf8String(byteLength, 0); } } else if (headByte === 0xc0) { // nil object = null; } else if (headByte === 0xc2) { // false object = false; } else if (headByte === 0xc3) { // true object = true; } else if (headByte === 0xca) { // float 32 object = this.readF32(); } else if (headByte === 0xcb) { // float 64 object = this.readF64(); } else if (headByte === 0xcc) { // uint 8 object = this.readU8(); } else if (headByte === 0xcd) { // uint 16 object = this.readU16(); } else if (headByte === 0xce) { // uint 32 object = this.readU32(); } else if (headByte === 0xcf) { // uint 64 object = this.readU64(); } else if (headByte === 0xd0) { // int 8 object = this.readI8(); } else if (headByte === 0xd1) { // int 16 object = this.readI16(); } else if (headByte === 0xd2) { // int 32 object = this.readI32(); } else if (headByte === 0xd3) { // int 64 object = this.readI64(); } else if (headByte === 0xd9) { // str 8 const byteLength = this.lookU8(); object = this.decodeUtf8String(byteLength, 1); } else if (headByte === 0xda) { // str 16 const byteLength = this.lookU16(); object = this.decodeUtf8String(byteLength, 2); } else if (headByte === 0xdb) { // str 32 const byteLength = this.lookU32(); object = this.decodeUtf8String(byteLength, 4); } else if (headByte === 0xdc) { // array 16 const size = this.readU16(); if (size !== 0) { this.pushArrayState(size); this.complete(); continue DECODE; } else { object = []; } } else if (headByte === 0xdd) { // array 32 const size = this.readU32(); if (size !== 0) { this.pushArrayState(size); this.complete(); continue DECODE; } else { object = []; } } else if (headByte === 0xde) { // map 16 const size = this.readU16(); if (size !== 0) { this.pushMapState(size); this.complete(); continue DECODE; } else { object = {}; } } else if (headByte === 0xdf) { // map 32 const size = this.readU32(); if (size !== 0) { this.pushMapState(size); this.complete(); continue DECODE; } else { object = {}; } } else if (headByte === 0xc4) { // bin 8 const size = this.lookU8(); object = this.decodeBinary(size, 1); } else if (headByte === 0xc5) { // bin 16 const size = this.lookU16(); object = this.decodeBinary(size, 2); } else if (headByte === 0xc6) { // bin 32 const size = this.lookU32(); object = this.decodeBinary(size, 4); } else if (headByte === 0xd4) { // fixext 1 object = this.decodeExtension(1, 0); } else if (headByte === 0xd5) { // fixext 2 object = this.decodeExtension(2, 0); } else if (headByte === 0xd6) { // fixext 4 object = this.decodeExtension(4, 0); } else if (headByte === 0xd7) { // fixext 8 object = this.decodeExtension(8, 0); } else if (headByte === 0xd8) { // fixext 16 object = this.decodeExtension(16, 0); } else if (headByte === 0xc7) { // ext 8 const size = this.lookU8(); object = this.decodeExtension(size, 1); } else if (headByte === 0xc8) { // ext 16 const size = this.lookU16(); object = this.decodeExtension(size, 2); } else if (headByte === 0xc9) { // ext 32 const size = this.lookU32(); object = this.decodeExtension(size, 4); } else { throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`); } this.complete(); const stack = this.stack; while (stack.length > 0) { // arrays and maps const state = stack[stack.length - 1]!; if (state.type === State.ARRAY) { state.array[state.position] = object; state.position++; if (state.position === state.size) { stack.pop(); object = state.array; } else { continue DECODE; } } else if (state.type === State.MAP_KEY) { if (!isValidMapKeyType(object)) { throw new DecodeError("The type of key must be string or number but " + typeof object); } if (object === "__proto__") { throw new DecodeError("The key __proto__ is not allowed"); } state.key = object; state.type = State.MAP_VALUE; continue DECODE; } else { // it must be `state.type === State.MAP_VALUE` here state.map[state.key!] = object; state.readCount++; if (state.readCount === state.size) { stack.pop(); object = state.map; } else { state.key = null; state.type = State.MAP_KEY; continue DECODE; } } } return object; } } private readHeadByte(): number { if (this.headByte === HEAD_BYTE_REQUIRED) { this.headByte = this.readU8(); // console.log("headByte", prettyByte(this.headByte)); } return this.headByte; } private complete(): void { this.headByte = HEAD_BYTE_REQUIRED; } private readArraySize(): number { const headByte = this.readHeadByte(); switch (headByte) { case 0xdc: return this.readU16(); case 0xdd: return this.readU32(); default: { if (headByte < 0xa0) { return headByte - 0x90; } else { throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`); } } } } private pushMapState(size: number) { if (size > this.maxMapLength) { throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`); } this.stack.push({ type: State.MAP_KEY, size, key: null, readCount: 0, map: {}, }); } private pushArrayState(size: number) { if (size > this.maxArrayLength) { throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`); } this.stack.push({ type: State.ARRAY, size, array: new Array<unknown>(size), position: 0, }); } private decodeUtf8String(byteLength: number, headerOffset: number): string { if (byteLength > this.maxStrLength) { throw new DecodeError( `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`, ); } if (this.bytes.byteLength < this.pos + headerOffset + byteLength) { throw MORE_DATA; } const offset = this.pos + headerOffset; let object: string; if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) { object = this.keyDecoder.decode(this.bytes, offset, byteLength); } else if (byteLength > TEXT_DECODER_THRESHOLD) { object = utf8DecodeTD(this.bytes, offset, byteLength); } else { object = utf8DecodeJs(this.bytes, offset, byteLength); } this.pos += headerOffset + byteLength; return object; } private stateIsMapKey(): boolean { if (this.stack.length > 0) { const state = this.stack[this.stack.length - 1]!; return state.type === State.MAP_KEY; } return false; } private decodeBinary(byteLength: number, headOffset: number): Uint8Array { if (byteLength > this.maxBinLength) { throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`); } if (!this.hasRemaining(byteLength + headOffset)) { throw MORE_DATA; } const offset = this.pos + headOffset; const object = this.bytes.subarray(offset, offset + byteLength); this.pos += headOffset + byteLength; return object; } private decodeExtension(size: number, headOffset: number): unknown { if (size > this.maxExtLength) { throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`); } const extType = this.view.getInt8(this.pos + headOffset); const data = this.decodeBinary(size, headOffset + 1 /* extType */); return this.extensionCodec.decode(data, extType, this.context); } private lookU8() { return this.view.getUint8(this.pos); } private lookU16() { return this.view.getUint16(this.pos); } private lookU32() { return this.view.getUint32(this.pos); } private readU8(): number { const value = this.view.getUint8(this.pos); this.pos++; return value; } private readI8(): number { const value = this.view.getInt8(this.pos); this.pos++; return value; } private readU16(): number { const value = this.view.getUint16(this.pos); this.pos += 2; return value; } private readI16(): number { const value = this.view.getInt16(this.pos); this.pos += 2; return value; } private readU32(): number { const value = this.view.getUint32(this.pos); this.pos += 4; return value; } private readI32(): number { const value = this.view.getInt32(this.pos); this.pos += 4; return value; } private readU64(): number { const value = getUint64(this.view, this.pos); this.pos += 8; return value; } private readI64(): number { const value = getInt64(this.view, this.pos); this.pos += 8; return value; } private readF32() { const value = this.view.getFloat32(this.pos); this.pos += 4; return value; } private readF64() { const value = this.view.getFloat64(this.pos); this.pos += 8; return value; } }
the_stack