text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as _ from 'underscore';
import { BasicSelectionModel, TextRenderer } from '@lumino/datagrid';
import { CellRenderer } from '@lumino/datagrid';
import { JSONExt } from '@lumino/coreutils';
import { MessageLoop } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
import {
DOMWidgetModel,
DOMWidgetView,
JupyterPhosphorPanelWidget,
ISerializers,
resolvePromisesDict,
unpack_models,
WidgetModel,
ICallbacks,
} from '@jupyter-widgets/base';
import { ViewBasedJSONModel } from './core/viewbasedjsonmodel';
import { MODULE_NAME, MODULE_VERSION } from './version';
import { CellRendererModel, CellRendererView } from './cellrenderer';
import { FeatherGrid } from './feathergrid';
import { Theme } from './utils';
// Import CSS
import '../style/jupyter-widget.css';
// Shorthand for a string->T mapping
type Dict<T> = { [keys: string]: T };
export class DataGridModel extends DOMWidgetModel {
defaults() {
return {
...super.defaults(),
_model_module: DataGridModel.model_module,
_model_module_version: DataGridModel.model_module_version,
_view_name: DataGridModel.view_name,
_view_module: DataGridModel.view_module,
_view_module_version: DataGridModel.view_module_version,
_visible_rows: [],
_transforms: [],
baseRowSize: 20,
baseColumnSize: 64,
baseRowHeaderSize: 64,
baseColumnHeaderSize: 20,
headerVisibility: 'all',
_data: {},
renderers: {},
corner_renderer: null,
default_renderer: null,
header_renderer: null,
selection_mode: 'none',
selections: [],
grid_style: {},
editable: false,
column_widths: {},
};
}
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.updateDataSync = this.updateDataSync.bind(this);
this.syncTransformState = this.syncTransformState.bind(this);
this.on('change:_data', this.updateData.bind(this));
this.on('change:_transforms', this.updateTransforms.bind(this));
this.on('change:selection_mode', this.updateSelectionModel, this);
this.on('change:selections', this.updateSelections, this);
this.updateData();
this.updateTransforms();
this.updateSelectionModel();
this.on('msg:custom', (content) => {
if (content.event_type === 'cell-changed') {
this.data_model.setModelData(
'body',
content.row,
content.column_index,
content.value,
);
}
});
}
updateDataSync(sender: any, msg: any) {
switch (msg.type) {
case 'row-indices-updated':
this.set('_visible_rows', msg.indices);
this.save_changes();
break;
case 'cell-updated':
this.set('_data', this.data_model.dataset);
this.save_changes();
break;
case 'cell-edit-event':
// Update data in widget model
const newData = this.get('_data');
newData.data[msg.row][msg.columnIndex] = msg.value;
this.set('_data', newData);
this.send(
{
event_type: 'cell-changed',
region: msg.region,
row: msg.row,
column_index: msg.columnIndex,
value: msg.value,
},
{ ...this._view_callbacks },
);
break;
default:
throw 'unreachable';
}
}
syncTransformState(sender: any, value: any) {
this.set('_transforms', value.transforms);
this.save_changes();
}
updateData() {
const data = this.data;
const schema = Private.createSchema(data);
if (this.data_model) {
this.data_model.updateDataset({ data: data.data, schema: schema });
this.data_model.transformStateChanged.disconnect(this.syncTransformState);
this.data_model.dataSync.disconnect(this.updateDataSync);
}
this.data_model = new ViewBasedJSONModel({
data: data.data,
schema: schema,
});
this.data_model.transformStateChanged.connect(this.syncTransformState);
this.data_model.dataSync.connect(this.updateDataSync);
this.updateTransforms();
this.trigger('data-model-changed');
this.updateSelectionModel();
}
updateTransforms() {
if (this.selectionModel) {
this.selectionModel.clear();
}
this.data_model.replaceTransforms(this.get('_transforms'));
}
updateSelectionModel() {
if (this.selectionModel) {
this.selectionModel.clear();
}
const selectionMode = this.get('selection_mode');
if (selectionMode === 'none') {
this.selectionModel = null;
return;
}
this.selectionModel = new BasicSelectionModel({
dataModel: this.data_model,
});
this.selectionModel.selectionMode = selectionMode;
this.trigger('selection-model-changed');
this.selectionModel.changed.connect(
(sender: BasicSelectionModel, args: void) => {
if (this.synchingWithKernel) {
return;
}
this.synchingWithKernel = true;
const selectionIter = sender.selections().iter();
const selections: any[] = [];
let selection = null;
while ((selection = selectionIter.next())) {
selections.push({
r1: Math.min(selection.r1, selection.r2),
r2: Math.max(selection.r1, selection.r2),
c1: Math.min(selection.c1, selection.c2),
c2: Math.max(selection.c1, selection.c2),
});
}
this.set('selections', selections);
this.save_changes();
this.synchingWithKernel = false;
},
this,
);
}
updateSelections() {
if (!this.selectionModel || this.synchingWithKernel) {
return;
}
this.synchingWithKernel = true;
const selections = this.get('selections');
this.selectionModel.clear();
for (const selection of selections) {
this.selectionModel.select({
r1: selection.r1,
c1: selection.c1,
r2: selection.r2,
c2: selection.c2,
cursorRow: selection.r1,
cursorColumn: selection.c1,
clear: 'none',
});
}
this.synchingWithKernel = false;
}
get data(): DataGridModel.IData {
return this.get('_data');
}
static serializers: ISerializers = {
...DOMWidgetModel.serializers,
transforms: { deserialize: unpack_models as any },
renderers: { deserialize: unpack_models as any },
corner_renderer: { deserialize: unpack_models as any },
default_renderer: { deserialize: unpack_models as any },
header_renderer: { deserialize: unpack_models as any },
_data: { deserialize: unpack_data as any },
grid_style: { deserialize: unpack_style as any },
};
static model_name = 'DataGridModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
static view_name = 'DataGridView';
static view_module = MODULE_NAME;
static view_module_version = MODULE_VERSION;
data_model: ViewBasedJSONModel;
selectionModel: BasicSelectionModel | null;
synchingWithKernel = false;
_view_callbacks: ICallbacks;
}
/**
* Helper function to conver snake_case strings to camelCase.
* Assumes all strings are valid snake_case (all lowercase).
* @param string snake_case string
* @returns camelCase string
*/
function camelCase(string: string): string {
string = string.toLowerCase();
const charArray = [];
for (let i = 0; i < string.length; i++) {
const curChar = string.charAt(i);
if (curChar === '_') {
i++;
charArray.push(string.charAt(i).toUpperCase());
continue;
}
charArray.push(curChar);
}
return charArray.join('');
}
/**
* Custom deserialization function for grid styles.
*/
function unpack_style(
value: any | Dict<unknown> | string | (Dict<unknown> | string)[],
manager: any,
): Promise<WidgetModel | Dict<WidgetModel> | WidgetModel[] | any> {
if (value instanceof Object && typeof value !== 'string') {
const unpacked: { [key: string]: any } = {};
Object.keys(value).forEach((key) => {
unpacked[camelCase(key)] = unpack_style(value[key], manager);
});
return resolvePromisesDict(unpacked);
} else if (typeof value === 'string' && value.slice(0, 10) === 'IPY_MODEL_') {
return Promise.resolve(
manager.get_model(value.slice(10, value.length)),
).then((model) => {
// returning the color formatting function from VegaExprModel.
return model._function;
});
} else {
return Promise.resolve(value);
}
}
// modified from ipywidgets original
function unpack_data(
value: any | Dict<unknown> | string | (Dict<unknown> | string)[],
manager: any,
): Promise<WidgetModel | Dict<WidgetModel> | WidgetModel[] | any> {
if (Array.isArray(value)) {
const unpacked: any[] = [];
value.forEach((sub_value, key) => {
unpacked.push(unpack_data(sub_value, manager));
});
return Promise.all(unpacked);
} else if (value instanceof Object && typeof value !== 'string') {
const unpacked: { [key: string]: any } = {};
Object.keys(value).forEach((key) => {
unpacked[key] = unpack_data(value[key], manager);
});
return resolvePromisesDict(unpacked);
} else if (value === '$NaN$') {
return Promise.resolve(Number.NaN);
} else if (value === '$Infinity$') {
return Promise.resolve(Number.POSITIVE_INFINITY);
} else if (value === '$NegInfinity$') {
return Promise.resolve(Number.NEGATIVE_INFINITY);
} else if (value === '$NaT$') {
return Promise.resolve(new Date('INVALID'));
} else {
return Promise.resolve(value);
}
}
export class DataGridView extends DOMWidgetView {
_createElement(tagName: string) {
this.pWidget = new JupyterPhosphorPanelWidget({ view: this });
this._initializeTheme();
return this.pWidget.node;
}
_setElement(el: HTMLElement) {
if (this.el || el !== this.pWidget.node) {
throw new Error('Cannot reset the DOM element.');
}
this.el = this.pWidget.node;
}
manageResizeEvent = () => {
MessageLoop.postMessage(this.pWidget, Widget.ResizeMessage.UnknownSize);
};
render() {
this.el.classList.add('datagrid-container');
window.addEventListener('resize', this.manageResizeEvent);
this.once('remove', () => {
window.removeEventListener('resize', this.manageResizeEvent);
});
this.grid = new FeatherGrid({
defaultSizes: {
rowHeight: this.model.get('base_row_size'),
columnWidth: this.model.get('base_column_size'),
rowHeaderWidth: this.model.get('base_row_header_size'),
columnHeaderHeight: this.model.get('base_column_header_size'),
},
headerVisibility: this.model.get('header_visibility'),
style: this.model.get('grid_style'),
});
this.grid.columnWidths = this.model.get('column_widths');
this.grid.editable = this.model.get('editable');
// this.default_renderer must be created after setting grid.isLightTheme
// for proper color variable initialization
this.grid.isLightTheme = this._isLightTheme;
this.grid.dataModel = this.model.data_model;
this.grid.selectionModel = this.model.selectionModel;
this.grid.backboneModel = this.model;
this.grid.cellClicked.connect(
(sender: FeatherGrid, event: FeatherGrid.ICellClickedEvent) => {
if (this.model.comm) {
this.send({
event_type: 'cell-click',
region: event.region,
column: event.column,
column_index: event.columnIndex,
row: event.row,
primary_key_row: event.primaryKeyRow,
cell_value: event.cellValue,
});
}
},
);
this.grid.columnsResized.connect(
(sender: FeatherGrid, args: void): void => {
this.model.set(
'column_widths',
JSONExt.deepCopy(this.grid.columnWidths),
);
this.model.save_changes();
},
);
// Attaching the view's iopub callbacks functions to
// the data model so we can use those as an
// argument to model.send() function in the model class.
this.model._view_callbacks = this.callbacks();
this.model.on('data-model-changed', () => {
this.grid.dataModel = this.model.data_model;
});
this.model.on('change:base_row_size', () => {
this.grid.baseRowSize = this.model.get('base_row_size');
});
this.model.on('change:base_column_size', () => {
this.grid.baseColumnSize = this.model.get('base_column_size');
});
this.model.on('change:column_widths', () => {
this.grid.columnWidths = this.model.get('column_widths');
});
this.model.on('change:base_row_header_size', () => {
this.grid.baseRowHeaderSize = this.model.get('base_row_header_size');
});
this.model.on('change:base_column_header_size', () => {
this.grid.baseColumnHeaderSize = this.model.get(
'base_column_header_size',
);
});
this.model.on('change:header_visibility', () => {
this.grid.headerVisibility = this.model.get('header_visibility');
});
this.model.on_some_change(
[
'corner_renderer',
'header_renderer',
'default_renderer',
'renderers',
'grid_style',
],
() => {
this.updateRenderers()
.then(this.updateGridStyle.bind(this))
.then(this.updateGridRenderers.bind(this));
},
this,
);
this.model.on('selection-model-changed', () => {
this.grid.selectionModel = this.model.selectionModel;
});
this.model.on('change:editable', () => {
this.grid.editable = this.model.get('editable');
});
this.model.on_some_change(
['auto_fit_columns', 'auto_fit_params'],
() => {
this.handleColumnAutoFit();
},
this,
);
if (this.model.get('auto_fit_columns')) {
this.handleColumnAutoFit();
}
return this.updateRenderers().then(() => {
this.updateGridStyle();
this.updateGridRenderers();
this.pWidget.addWidget(this.grid);
});
}
private handleColumnAutoFit() {
// Check whether we need to auto-fit or revert to base size.
const shouldAutoFit = this.model.get('auto_fit_columns');
if (!shouldAutoFit) {
this.grid.baseColumnSize = this.model.get('base_column_size');
// Terminate call here if not auto-fitting.
return;
}
// Retrieve user-defined auto-fit params
let { area, padding, numCols } = this.model.get('auto_fit_params');
// Data validation on params
area = area ?? 'all';
padding = padding ?? 30;
numCols = numCols ?? undefined;
// Call resize function
this.grid.grid.fitColumnNames(area, padding, numCols);
}
private updateRenderers() {
// Unlisten to previous renderers
if (this.default_renderer) {
this.stopListening(this.default_renderer, 'renderer-changed');
}
if (this.header_renderer) {
this.stopListening(this.header_renderer, 'renderer-changed');
}
if (this.corner_renderer) {
this.stopListening(this.corner_renderer, 'renderer-changed');
}
for (const key in this.renderers) {
this.stopListening(this.renderers[key], 'renderer-changed');
}
// And create views for new renderers
const promises = [];
const default_renderer = this.model.get('default_renderer');
promises.push(
this.create_child_view(default_renderer).then(
(defaultRendererView: any) => {
this.default_renderer = defaultRendererView;
this.listenTo(
this.default_renderer,
'renderer-changed',
this.updateGridRenderers.bind(this),
);
},
),
);
const corner_renderer = this.model.get('corner_renderer');
if (corner_renderer) {
promises.push(
this.create_child_view(corner_renderer).then(
(cornerRendererView: any) => {
this.corner_renderer = cornerRendererView;
this.listenTo(
this.corner_renderer,
'renderer-changed',
this.updateGridRenderers.bind(this),
);
},
),
);
}
const header_renderer = this.model.get('header_renderer');
if (header_renderer) {
promises.push(
this.create_child_view(header_renderer).then(
(headerRendererView: any) => {
this.header_renderer = headerRendererView;
this.listenTo(
this.header_renderer,
'renderer-changed',
this.updateGridRenderers.bind(this),
);
},
),
);
}
const renderer_promises: Dict<Promise<any>> = {};
_.each(
this.model.get('renderers'),
(model: CellRendererModel, key: string) => {
renderer_promises[key] = this.create_child_view(model);
},
);
promises.push(
resolvePromisesDict(renderer_promises).then(
(rendererViews: Dict<CellRendererView>) => {
this.renderers = rendererViews;
for (const key in rendererViews) {
this.listenTo(
rendererViews[key],
'renderer-changed',
this.updateGridRenderers.bind(this),
);
}
},
),
);
return Promise.all(promises);
}
public updateGridStyle() {
this.grid.updateGridStyle();
}
set isLightTheme(value: boolean) {
this._isLightTheme = value;
if (!this.grid) {
return;
}
this.grid.isLightTheme = value;
}
get isLightTheme(): boolean {
return this._isLightTheme;
}
private updateGridRenderers() {
let defaultRenderer = this.default_renderer.renderer;
if (
this.grid.grid.style.backgroundColor !== Theme.getBackgroundColor() ||
this.grid.grid.style.rowBackgroundColor ||
this.grid.grid.style.columnBackgroundColor
) {
// Making sure the default renderer doesn't paint over the global
// grid background color, if the latter is set.
defaultRenderer = new TextRenderer({
...this.default_renderer.renderer,
backgroundColor: undefined,
});
}
const hasHeaderRenderer = this.model.get('header_renderer') !== null;
let columnHeaderRenderer = null;
if (this.header_renderer && hasHeaderRenderer) {
columnHeaderRenderer = this.header_renderer.renderer;
} else {
columnHeaderRenderer = new TextRenderer({
font: '12px sans-serif',
textColor: Theme.getFontColor(),
backgroundColor: Theme.getBackgroundColor(2),
});
}
let cornerHeaderRenderer = null;
if (this.corner_renderer) {
cornerHeaderRenderer = this.corner_renderer.renderer;
}
const renderers: Dict<CellRenderer> = {};
Object.entries(this.renderers).forEach(([name, rendererView]) => {
renderers[name] = rendererView.renderer;
});
this.grid.defaultRenderer = defaultRenderer;
this.grid.columnHeaderRenderer = columnHeaderRenderer;
if (cornerHeaderRenderer) {
this.grid.cornerHeaderRenderer = cornerHeaderRenderer;
}
this.grid.renderers = renderers;
}
private _initializeTheme() {
// initialize theme unless set earlier
if (this._isLightTheme !== undefined) {
return;
}
// initialize theme based on application settings
this._isLightTheme = !(
(
document.body.classList.contains(
'theme-dark',
) /* jupyter notebook or voila */ ||
document.body.dataset.jpThemeLight === 'false'
) /* jupyter lab */
);
}
renderers: Dict<CellRendererView>;
corner_renderer: CellRendererView;
default_renderer: CellRendererView;
header_renderer: CellRendererView;
grid: FeatherGrid;
pWidget: JupyterPhosphorPanelWidget;
model: DataGridModel;
backboneModel: DataGridModel;
// keep undefined since widget initializes before constructor
private _isLightTheme: boolean;
}
export {
TextRendererModel,
TextRendererView,
BarRendererModel,
BarRendererView,
HyperlinkRendererModel,
HyperlinkRendererView,
} from './cellrenderer';
export { VegaExprModel, VegaExprView } from './vegaexpr';
export namespace DataGridModel {
/**
* An options object for initializing the data model.
*/
export interface IData {
data: ViewBasedJSONModel.DataSource;
schema: ISchema;
fields: { [key: string]: null }[];
}
export interface IField {
readonly name: string | any[];
readonly type: string;
readonly rows: any[];
}
export interface ISchema {
readonly fields: IField[];
readonly primaryKey: string[];
readonly primaryKeyUuid: string;
}
}
/**
* The namespace for the module implementation details.
*/
namespace Private {
/**
* Creates a valid JSON Table Schema from the schema provided by pandas.
*
* @param data - The data that has been synced from the kernel.
*/
export function createSchema(
data: DataGridModel.IData,
): ViewBasedJSONModel.ISchema {
// Construct a new array of schema fields based on the keys in data.fields
// Note: this accounts for how tuples/lists may be serialized into strings
// in the case of multiIndex columns.
const fields: ViewBasedJSONModel.IField[] = [];
data.fields.forEach((val: { [key: string]: null }, i: number) => {
const rows = Array.isArray(data.schema.fields[i].name)
? <any[]>data.schema.fields[i].name
: <string[]>[data.schema.fields[i].name];
const field = {
name: Object.keys(val)[0],
type: data.schema.fields[i].type,
rows: rows,
};
fields.push(field);
});
// Updating the primary key to account for a multiIndex primary key.
const primaryKey = data.schema.primaryKey.map((key: string) => {
for (let i = 0; i < data.schema.fields.length; i++) {
const curFieldKey = Array.isArray(key)
? data.schema.fields[i].name[0]
: data.schema.fields[i].name;
const newKey = Array.isArray(key) ? key[0] : key;
if (curFieldKey == newKey) {
return Object.keys(data.fields[i])[0];
}
}
return 'unreachable';
});
return {
primaryKey: primaryKey,
primaryKeyUuid: data.schema.primaryKeyUuid,
fields: fields,
};
}
} | the_stack |
import { AfterViewInit, ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';
import { List } from '../../list/model/list';
import { PricingService } from '../pricing.service';
import { getItemSource, ListRow } from '../../list/model/list-row';
import { MediaObserver } from '@angular/flex-layout';
import { SettingsService } from '../../settings/settings.service';
import { interval, Observable, Subject } from 'rxjs';
import { ListsFacade } from '../../list/+state/lists.facade';
import { filter, first, map, mergeMap, shareReplay, switchMap, takeUntil, tap } from 'rxjs/operators';
import { XivapiService } from '@xivapi/angular-client';
import { AuthFacade } from '../../../+state/auth.facade';
import { ProgressPopupService } from '../../progress-popup/progress-popup.service';
import { I18nToolsService } from '../../../core/tools/i18n-tools.service';
import { TranslateService } from '@ngx-translate/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NumberQuestionPopupComponent } from '../../number-question-popup/number-question-popup/number-question-popup.component';
import { UniversalisService } from '../../../core/api/universalis.service';
import { DataType } from '../../list/data/data-type';
import { ListController } from '../../list/list-controller';
import { LazyDataFacade } from '../../../lazy-data/+state/lazy-data.facade';
import { safeCombineLatest } from '../../../core/rxjs/safe-combine-latest';
@Component({
selector: 'app-pricing',
templateUrl: './pricing.component.html',
styleUrls: ['./pricing.component.less']
})
export class PricingComponent implements AfterViewInit {
list$: Observable<List>;
items$: Observable<ListRow[]>;
crystals$: Observable<ListRow[]>;
preCrafts$: Observable<ListRow[]>;
@Output()
close: EventEmitter<void> = new EventEmitter<void>();
public spendingTotal = 0;
public discount = 0;
public flatDiscount = 0;
loggedIn$ = this.authFacade.loggedIn$;
private costs: { [index: number]: number } = {};
private server$: Observable<string> = this.authFacade.mainCharacter$.pipe(
map(char => char.Server)
);
constructor(private pricingService: PricingService, private media: MediaObserver, public settings: SettingsService,
private listsFacade: ListsFacade, private xivapi: XivapiService, private authFacade: AuthFacade,
private progressService: ProgressPopupService, private i18n: I18nToolsService,
private translate: TranslateService, private message: NzMessageService, private cd: ChangeDetectorRef,
private lazyData: LazyDataFacade, private dialog: NzModalService, private universalis: UniversalisService) {
this.list$ = this.listsFacade.selectedList$.pipe(
tap(list => {
this.updateCosts(list);
this.updateCosts(list);
const discounts = (localStorage.getItem(`discounts:${list.$key}`) || '0,0').split(',');
this.flatDiscount = +discounts[0];
this.discount = +discounts[1];
}),
shareReplay(1)
);
this.crystals$ = this.list$.pipe(
map(list => list.items.filter(i => i.id < 20).sort((a, b) => a.id - b.id)),
shareReplay(1)
);
this.items$ = this.list$.pipe(
map(list => list.items.filter(i => (getItemSource(i, DataType.CRAFTED_BY).length === 0) && i.id >= 20)),
shareReplay(1)
);
this.preCrafts$ = this.list$.pipe(
map(list => list.items.filter(i => getItemSource(i, DataType.CRAFTED_BY).length > 0)),
shareReplay(1)
);
}
public saveDiscounts(listKey: string): void {
localStorage.setItem(`discounts:${listKey}`, `${this.flatDiscount},${this.discount}`);
}
public setBenefits(items: ListRow[], list: List): void {
this.dialog.create({
nzTitle: `${this.translate.instant('PRICING.Enter_total_earnings')}`,
nzContent: NumberQuestionPopupComponent,
nzComponentParams: {
value: this.getTotalEarnings(items, list)
},
nzFooter: null
}).afterClose
.pipe(
filter(value => value || value === 0)
)
.subscribe(value => {
items.forEach(item => {
const totalPricePerItem = value / items.length;
const pricePerCraft = Math.round(totalPricePerItem / item.amount);
this.pricingService.savePrice(item, {
fromMB: false,
fromVendor: false,
hq: pricePerCraft,
nq: pricePerCraft
});
});
this.pricingService.priceChanged$.next(null);
});
}
public fillMbCosts(rows: ListRow[], finalItems = false): void {
const stopInterval$ = new Subject<void>();
const rowsToFill = rows;
if (rowsToFill.length === 0) {
return;
}
const operations = interval(250).pipe(
takeUntil(stopInterval$),
filter(index => rowsToFill[index] !== undefined),
mergeMap(index => {
const row = rowsToFill[index];
return this.server$.pipe(
switchMap(server => {
return this.lazyData.datacenters$.pipe(
first(),
map(datacenters => {
const dc = Object.keys(datacenters).find(key => {
return datacenters[key].indexOf(server) > -1;
});
return { server, dc };
})
);
}),
mergeMap(({ server, dc }) => {
return this.universalis.getDCPrices(dc, row.id).pipe(
map(res => {
const item = res[0];
let prices = item.Prices;
if (finalItems || this.settings.disableCrossWorld) {
prices = prices.filter(price => (<any>price).Server === server);
}
const cheapestHq = prices.filter(p => p.IsHQ)
.sort((a, b) => a.PricePerUnit - b.PricePerUnit)[0];
const cheapestNq = prices.filter(p => !p.IsHQ)
.sort((a, b) => a.PricePerUnit - b.PricePerUnit)[0];
const result: any = {
item: row,
hq: cheapestHq ? cheapestHq.PricePerUnit : this.pricingService.getPrice(row).hq,
hqServer: cheapestHq ? (<any>cheapestHq).Server : null,
updated: item.Updated
};
const servicePrice = this.pricingService.getPrice(row);
if (!servicePrice.fromVendor) {
result.nq = cheapestNq ? cheapestNq.PricePerUnit : this.pricingService.getPrice(row).nq;
result.nqServer = cheapestNq ? (<any>cheapestNq).Server : null;
}
return result;
})
);
})
);
}),
tap((res) => {
this.pricingService.savePrice(res.item, {
nq: res.nq,
nqServer: res.nqServer,
hq: res.hq,
hqServer: res.hqServer,
fromVendor: false,
fromMB: true,
updated: res.updated
});
})
);
this.progressService.showProgress(operations, rowsToFill.length)
.pipe(
switchMap(() => this.list$),
first()
)
.subscribe((res) => {
if (res instanceof Error) {
this.message.error(this.translate.instant('MARKETBOARD.Error'));
} else {
stopInterval$.next(null);
this.pricingService.priceChanged$.next(null);
this.updateCosts(res);
}
});
}
public updateCosts(list: List): void {
const items = this.topologicalSort(list.items);
items.forEach(item => {
this.costs[item.id] = this._getCraftCost(item, list);
});
list.finalItems.forEach(item => {
this.costs[item.id] = this._getCraftCost(item, list);
});
this.spendingTotal = this.getSpendingTotal(list);
this.cd.detectChanges();
}
public save(list: List): void {
this.listsFacade.updateList(list);
}
public getEarningText = (rows: ListRow[], list: List) => {
return safeCombineLatest(rows.filter(row => row.usePrice !== false).map(row => {
return this.i18n.getNameObservable('items', row.id).pipe(
map(itemName => ({ row, itemName }))
);
})).pipe(
map(rowsWithName => {
return rowsWithName.reduce((total, { row, itemName }) => {
const price = this.pricingService.getEarnings(row);
const amount = this.pricingService.getAmount(list.$key, row, true);
let priceString: string;
if (price.hq > 0 && amount.hq > 0) {
priceString = `${price.hq.toLocaleString()}gil x${amount.hq}(HQ)`;
if (price.nq > 0 && amount.nq > 0) {
priceString += `, ${price.nq.toLocaleString()}gil x${amount.nq}(NQ)`;
}
} else {
priceString = `${price.nq}gil x${amount.nq}(NQ)`;
}
return `${total}\n ${itemName}: ${priceString}`;
}, `${this.translate.instant('COMMON.Total')}: ${this.getTotalEarnings(rows, list).toLocaleString()}gil\n`);
})
);
};
public getSpendingText = (rows: ListRow[], list: List) => {
return safeCombineLatest(rows.filter(row => row.usePrice).map(row => {
return this.i18n.getNameObservable('items', row.id).pipe(
map(itemName => ({ row, itemName }))
);
})).pipe(
map(rowsWithName => {
return rowsWithName
.reduce((total, { row, itemName }) => {
const price = this.pricingService.getPrice(row);
const amount = this.pricingService.getAmount(list.$key, row, false);
let priceString: string;
if (price.hq > 0 && amount.hq > 0) {
priceString = `${price.hq.toLocaleString()}gil x${amount.hq}(HQ) (${this.getWorldName(price.hqServer)})`;
if (price.nq > 0 || amount.nq > 0) {
priceString += `, ${price.nq.toLocaleString()}gil x${amount.nq}(NQ) (${this.getWorldName(price.nqServer)})`;
}
} else {
priceString = `${price.nq}gil x${amount.nq}(NQ) (${this.getWorldName(price.nqServer)})`;
}
return `${total}\n ${itemName}: ${priceString}`;
}, `${this.translate.instant('COMMON.Total')}: ${this.getTotalEarnings(rows, list).toLocaleString()}gil\n`);
})
);
};
public getSpendingTotal(list: List): number {
return list.finalItems.reduce((total, item) => {
let cost = this.getCraftCost(item);
if (this.pricingService.isCustomPrice(item)) {
const price = this.pricingService.getPrice(item);
const amount = this.pricingService.getAmount(list.$key, item);
cost = Math.min(1, price.nq * amount.nq) * Math.min(1, price.hq * amount.hq);
} else {
if (this.settings.expectToSellEverything) {
// If we expect to sell everything, price based on amount of items crafted
cost *= item.amount_needed * item.yield;
} else {
// Else, price based on amount of items used
cost *= item.amount;
}
}
return total + cost;
}, 0);
}
getTotalEarnings(rows: ListRow[], list: List): number {
const totalPrice = rows.filter(row => row.usePrice).reduce((total, row) => {
const price = this.pricingService.getEarnings(row);
const amount = this.pricingService.getAmount(list.$key, row, true);
return total + amount.nq * price.nq + amount.hq * price.hq;
}, 0);
return (totalPrice - this.flatDiscount) * (1 - (this.discount / 100));
}
/**
* Gets the crafting cost of a given item.
* @param {ListRow} row
* @returns {number}
*/
getCraftCost(row: ListRow): number {
if (!row.usePrice) {
return 0;
}
return this.costs[row.id] || 0;
}
/**
* Gets the final benefits made from the whole list.
* @returns {number}
*/
getBenefits(list: List): number {
return this.getTotalEarnings(list.finalItems, list) - this.spendingTotal;
}
public trackByItemFn(index: number, item: ListRow): number {
return item.id;
}
ngAfterViewInit(): void {
this.list$.pipe(
first()
).subscribe(list => {
this.updateCosts(list);
});
setTimeout(() => {
this.cd.detectChanges();
}, 500);
}
private _getCraftCost(row: ListRow, list: List): number {
const price = (row.requires || []).reduce((total, requirement) => {
const requirementRow = ListController.getItemById(list, requirement.id, true);
if (this.settings.expectToSellEverything) {
// If you expect to sell everything, just divide by yield.
return total + (this.getCraftCost(requirementRow) / row.yield) * requirement.amount;
} else {
// else, divide by amount / amount_needed, aka adjusted yield for when you craft more than you sell because of yield.
return total + (this.getCraftCost(requirementRow) / (row.amount / row.amount_needed)) * requirement.amount;
}
}, 0);
// If that's a final item or the price is custom, no recursion.
if (this.pricingService.isCustomPrice(row)
|| price === 0
|| (this.pricingService.getPrice(row).fromVendor && list.finalItems.indexOf(row) === -1)) {
if (this.settings.ignoreCompletedItemInPricing && row.done >= row.amount) {
return 0;
}
const prices = this.pricingService.getPrice(row);
const amounts = this.pricingService.getAmount(list.$key, row);
if (prices.hq > 0 && prices.hq < prices.nq) {
return prices.hq * (amounts.nq || 1) * (amounts.hq || 1) / (amounts.hq + amounts.nq);
}
return ((prices.nq * amounts.nq) + (prices.hq * amounts.hq)) / (amounts.hq + amounts.nq);
}
return price;
}
private topologicalSort(data: ListRow[]): ListRow[] {
const res: ListRow[] = [];
const doneList: boolean[] = [];
while (data.length > res.length) {
let resolved = false;
for (const item of data) {
if (res.indexOf(item) > -1) {
// item already in resultset
continue;
}
resolved = true;
if (item.requires !== undefined) {
for (const dep of item.requires) {
// We have to check if it's not a precraft, as some dependencies aren't resolvable inside the current array.
const depIsInArray = data.find(row => row.id === dep.id) !== undefined;
if (!doneList[dep.id] && depIsInArray) {
// there is a dependency that is not met:
resolved = false;
break;
}
}
}
if (resolved) {
// All dependencies are met:
doneList[item.id] = true;
res.push(item);
}
}
}
return res;
}
private getWorldName(world: string): string {
return this.i18n.getName(this.lazyData.getWorldName(world));
}
} | the_stack |
import { AbortOptions, IPFSPath } from '../utils'
import CID, { CIDVersion } from 'cids'
import { CodecName } from 'multicodec'
import { HashName } from 'multihashes'
import { Mtime, MtimeLike } from 'ipfs-unixfs'
import type { AddProgressFn } from '../root'
export interface API<OptionExtension = {}> {
/**
* Change mode for files and directories
*
* @example
* ```js
* // To give a file -rwxrwxrwx permissions
* await ipfs.files.chmod('/path/to/file.txt', parseInt('0777', 8))
*
* // Alternatively
* await ipfs.files.chmod('/path/to/file.txt', '+rwx')
*
* // You can omit the leading `0` too
* await ipfs.files.chmod('/path/to/file.txt', '777')
* ```
*/
chmod: (path: string, mode: number | string, options?: ChmodOptions & OptionExtension) => Promise<void>
/**
* Copy files from one location to another
*
* - If from has multiple values then to must be a directory.
* - If from has a single value and to exists and is a directory, from will be copied into to.
* - If from has a single value and to exists and is a file, from must be a file and the contents of to will be replaced with the contents of from otherwise an error will be returned.
* - If from is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen.
* - If from is an IPFS path and the content does not exist in your node's repo, only the root node of the source file with be retrieved from the network and linked to from the destination. The remainder of the file will be retrieved on demand.
*
* @example
* ```js
* // To copy a file
* await ipfs.files.cp('/src-file', '/dst-file')
*
* // To copy a directory
* await ipfs.files.cp('/src-dir', '/dst-dir')
*
* // To copy multiple files to a directory
* await ipfs.files.cp('/src-file1', '/src-file2', '/dst-dir')
* ```
*/
cp: (from: IPFSPath | IPFSPath[], to: string, options?: CpOptions & OptionExtension) => Promise<void>
/**
* Make a directory in your MFS
*/
mkdir: (path: string, options?: MkdirOptions & OptionExtension) => Promise<void>
/**
* Get file or directory statistics
*/
stat: (ipfsPath: IPFSPath, options?: StatOptions & OptionExtension) => Promise<StatResult>
/**
* Update the mtime of a file or directory
*
* @example
* ```js
* // set the mtime to the current time
* await ipfs.files.touch('/path/to/file.txt')
*
* // set the mtime to a specific time
* await ipfs.files.touch('/path/to/file.txt', {
* mtime: new Date('May 23, 2014 14:45:14 -0700')
* })
* ```
*/
touch: (ipfsPath: string, options?: TouchOptions & OptionExtension) => Promise<void>
/**
* Remove a file or directory
*
* @example
* ```js
* // To remove a file
* await ipfs.files.rm('/my/beautiful/file.txt')
*
* // To remove multiple files
* await ipfs.files.rm('/my/beautiful/file.txt', '/my/other/file.txt')
*
* // To remove a directory
* await ipfs.files.rm('/my/beautiful/directory', { recursive: true })
* ```
*/
rm: (ipfsPaths: string | string[], options?: RmOptions & OptionExtension) => Promise<void>
/**
* Read a file
*
* @example
* ```js
* const chunks = []
*
* for await (const chunk of ipfs.files.read('/hello-world')) {
* chunks.push(chunk)
* }
*
* console.log(uint8ArrayConcat(chunks).toString())
* // Hello, World!
* ```
*/
read: (ipfsPath: IPFSPath, options?: ReadOptions & OptionExtension) => AsyncIterable<Uint8Array>
/**
* Write to an MFS path
*
* @example
* ```js
* await ipfs.files.write('/hello-world', new TextEncoder().encode('Hello, world!'))
* ```
*/
write: (ipfsPath: string, content: string | Uint8Array | Blob | AsyncIterable<Uint8Array> | Iterable<Uint8Array>, options?: WriteOptions & OptionExtension) => Promise<void>
/**
* Move files from one location to another
*
* - If from has multiple values then to must be a directory.
* - If from has a single value and to exists and is a directory, from will be moved into to.
* - If from has a single value and to exists and is a file, from must be a file and the contents of to will be replaced with the contents of from otherwise an error will be returned.
* - If from is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen.
* - If from is an IPFS path and the content does not exist in your node's repo, only the root node of the source file with be retrieved from the network and linked to from the destination. The remainder of the file will be retrieved on demand.
* - All values of from will be removed after the operation is complete unless they are an IPFS path.
*
* @example
* ```js
* await ipfs.files.mv('/src-file', '/dst-file')
*
* await ipfs.files.mv('/src-dir', '/dst-dir')
*
* await ipfs.files.mv('/src-file1', '/src-file2', '/dst-dir')
* ```
*/
mv: (from: string | string[], to: string, options?: MvOptions & OptionExtension) => Promise<void>
/**
* Flush a given path's data to the disk
*
* @example
* ```js
* const cid = await ipfs.files.flush('/')
* ```
*/
flush: (ipfsPath: string, options?: AbortOptions & OptionExtension) => Promise<CID>
/**
* List directories in the local mutable namespace
*
* @example
* ```js
* for await (const file of ipfs.files.ls('/screenshots')) {
* console.log(file.name)
* }
* // 2018-01-22T18:08:46.775Z.png
* // 2018-01-22T18:08:49.184Z.png
* ```
*/
ls: (ipfsPath: IPFSPath, options?: AbortOptions & OptionExtension) => AsyncIterable<MFSEntry>
}
export interface MFSEntry {
/**
* The object's name
*/
name: string
/**
* The object's type (directory or file)
*/
type: 'directory' | 'file'
/**
* The size of the file in bytes
*/
size: number
/**
* The CID of the object
*/
cid: CID
/**
* The UnixFS mode as a Number
*/
mode?: number
/**
* An object with numeric secs and nsecs properties
*/
mtime?: Mtime
}
export interface MFSOptions {
/**
* If true the changes will be immediately flushed to disk
*/
flush?: boolean
}
export interface ChmodOptions extends MFSOptions, AbortOptions {
/**
* If true mode will be applied to the entire tree under path
*/
recursive?: boolean
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
}
export interface CpOptions extends MFSOptions, AbortOptions {
/**
* The value or node that was fetched during the get operation
*/
parents?: boolean
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
}
export interface MkdirOptions extends MFSOptions, AbortOptions {
/**
* If true, create intermediate directories
*/
parents?: boolean
/**
* An integer that represents the file mode
*/
mode?: number
/**
* A Date object, an object with { secs, nsecs } properties where secs is the number of seconds since (positive) or before (negative) the Unix Epoch began and nsecs is the number of nanoseconds since the last full second, or the output of process.hrtime()
*/
mtime?: MtimeLike
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
}
export interface StatOptions extends AbortOptions {
/**
* If true, return only the CID
*/
hash?: boolean
/**
* If true, return only the size
*/
size?: boolean
/**
* If true, compute the amount of the DAG that is local and if possible the total size
*/
withLocal?: boolean
}
export interface StatResult {
/**
* A CID instance
*/
cid: CID
/**
* The file size in Bytes
*/
size: number
/**
* The size of the DAGNodes making up the file in Bytes
*/
cumulativeSize: number
/**
* Either directory or file
*/
type: 'directory' | 'file'
/**
* If type is directory, this is the number of files in the directory. If it is file it is the number of blocks that make up the file
*/
blocks: number
/**
* Indicates if locality information is present
*/
withLocality: boolean
/**
* Indicates if the queried dag is fully present locally
*/
local?: boolean
/**
* Indicates the cumulative size of the data present locally
*/
sizeLocal?: number
/**
* UnixFS mode if applicable
*/
mode?: number
/**
* UnixFS mtime if applicable
*/
mtime?: Mtime
}
export interface TouchOptions extends MFSOptions, AbortOptions {
/**
* A Date object, an object with { secs, nsecs } properties where secs is the number of seconds since (positive) or before (negative) the Unix Epoch began and nsecs is the number of nanoseconds since the last full second, or the output of process.hrtime()
*/
mtime?: MtimeLike
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
}
export interface RmOptions extends MFSOptions, AbortOptions {
/**
* If true all paths under the specifed path(s) will be removed
*/
recursive?: boolean
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
}
export interface ReadOptions extends AbortOptions {
/**
* An offset to start reading the file from
*/
offset?: number
/**
* An optional max length to read from the file
*/
length?: number
}
export interface WriteOptions extends MFSOptions, AbortOptions {
/**
* An offset within the file to start writing at
*/
offset?: number
/**
* Optionally limit how many bytes are written
*/
length?: number
/**
* Create the MFS path if it does not exist
*/
create?: boolean
/**
* Create intermediate MFS paths if they do not exist
*/
parents?: boolean
/**
* Truncate the file at the MFS path if it would have been larger than the passed content
*/
truncate?: boolean
/**
* If true, DAG leaves will contain raw file data and not be wrapped in a protobuf
*/
rawLeaves?: boolean
/**
* An integer that represents the file mode
*/
mode?: number
/**
* A Date object, an object with { secs, nsecs } properties where secs is the number of seconds since (positive) or before (negative) the Unix Epoch began and nsecs is the number of nanoseconds since the last full second, or the output of process.hrtime()
*/
mtime?: MtimeLike
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
/**
* If writing a file and only a single leaf would be present, store the file data in the root node
*/
reduceSingleLeafToSelf?: boolean
/**
* What sort of DAG structure to create
*/
strategy?: 'balanced' | 'trickle'
/**
* Callback to be notified of write progress
*/
progress?: AddProgressFn
}
export interface MvOptions extends MFSOptions, AbortOptions {
/**
* Create intermediate MFS paths if they do not exist
*/
parents?: boolean
/**
* The hash algorithm to use for any updated entries
*/
hashAlg?: HashName
/**
* The CID version to use for any updated entries
*/
cidVersion?: CIDVersion
/**
* The threshold for splitting any modified folders into HAMT shards
*/
shardSplitThreshold?: number
} | the_stack |
import { EventEmitter } from 'events';
import contractsMap from '@metamask/contract-metadata';
import { abiERC721 } from '@metamask/metamask-eth-abis';
import { v1 as random } from 'uuid';
import { Mutex } from 'async-mutex';
import { ethers } from 'ethers';
import { BaseController, BaseConfig, BaseState } from '../BaseController';
import type { PreferencesState } from '../user/PreferencesController';
import type { NetworkState, NetworkType } from '../network/NetworkController';
import { validateTokenToWatch, toChecksumHexAddress } from '../util';
import { MAINNET } from '../constants';
import type { Token } from './TokenRatesController';
const ERC721_INTERFACE_ID = '0x80ac58cd';
/**
* @type TokensConfig
*
* Tokens controller configuration
* @property networkType - Network ID as per net_version
* @property selectedAddress - Vault selected address
*/
export interface TokensConfig extends BaseConfig {
networkType: NetworkType;
selectedAddress: string;
chainId: string;
provider: any;
}
/**
* @type AssetSuggestionResult
* @property result - Promise resolving to a new suggested asset address
* @property suggestedAssetMeta - Meta information about this new suggested asset
*/
interface AssetSuggestionResult {
result: Promise<string>;
suggestedAssetMeta: SuggestedAssetMeta;
}
enum SuggestedAssetStatus {
accepted = 'accepted',
failed = 'failed',
pending = 'pending',
rejected = 'rejected',
}
export type SuggestedAssetMetaBase = {
id: string;
time: number;
type: string;
asset: Token;
};
/**
* @type SuggestedAssetMeta
*
* Suggested asset by EIP747 meta data
* @property error - Synthesized error information for failed asset suggestions
* @property id - Generated UUID associated with this suggested asset
* @property status - String status of this this suggested asset
* @property time - Timestamp associated with this this suggested asset
* @property type - Type type this suggested asset
* @property asset - Asset suggested object
*/
export type SuggestedAssetMeta =
| (SuggestedAssetMetaBase & {
status: SuggestedAssetStatus.failed;
error: Error;
})
| (SuggestedAssetMetaBase & {
status:
| SuggestedAssetStatus.accepted
| SuggestedAssetStatus.rejected
| SuggestedAssetStatus.pending;
});
/**
* @type TokensState
*
* Assets controller state
* @property allTokens - Object containing tokens by network and account
* @property suggestedAssets - List of pending suggested assets to be added or canceled
* @property tokens - List of tokens associated with the active network and address pair
* @property ignoredTokens - List of ignoredTokens associated with the active network and address pair
* @property allIgnoredTokens - Object containing hidden/ignored tokens by network and account
*/
export interface TokensState extends BaseState {
allTokens: { [key: string]: { [key: string]: Token[] } };
allIgnoredTokens: { [key: string]: { [key: string]: string[] } };
ignoredTokens: string[];
suggestedAssets: SuggestedAssetMeta[];
tokens: Token[];
}
/**
* Controller that stores assets and exposes convenience methods
*/
export class TokensController extends BaseController<
TokensConfig,
TokensState
> {
private mutex = new Mutex();
private ethersProvider: any;
private failSuggestedAsset(
suggestedAssetMeta: SuggestedAssetMeta,
error: Error,
) {
const failedSuggestedAssetMeta = {
...suggestedAssetMeta,
status: SuggestedAssetStatus.failed,
error,
};
this.hub.emit(
`${suggestedAssetMeta.id}:finished`,
failedSuggestedAssetMeta,
);
}
/**
* EventEmitter instance used to listen to specific EIP747 events
*/
hub = new EventEmitter();
/**
* Name of this controller used during composition
*/
name = 'TokensController';
/**
* Creates a TokensController instance.
*
* @param options - The controller options.
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
* @param options.config - Initial options used to configure this controller.
* @param options.state - Initial state to set on this controller.
*/
constructor({
onPreferencesStateChange,
onNetworkStateChange,
config,
state,
}: {
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
onNetworkStateChange: (
listener: (networkState: NetworkState) => void,
) => void;
config?: Partial<TokensConfig>;
state?: Partial<TokensState>;
}) {
super(config, state);
this.defaultConfig = {
networkType: MAINNET,
selectedAddress: '',
chainId: '',
provider: undefined,
...config,
};
this.defaultState = {
allTokens: {},
allIgnoredTokens: {},
ignoredTokens: [],
suggestedAssets: [],
tokens: [],
...state,
};
this.initialize();
onPreferencesStateChange(({ selectedAddress }) => {
const { allTokens, allIgnoredTokens } = this.state;
const { chainId } = this.config;
this.configure({ selectedAddress });
this.update({
tokens: allTokens[chainId]?.[selectedAddress] || [],
ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] || [],
});
});
onNetworkStateChange(({ provider }) => {
const { allTokens, allIgnoredTokens } = this.state;
const { selectedAddress } = this.config;
const { chainId } = provider;
this.configure({ chainId });
this.ethersProvider = this._instantiateNewEthersProvider();
this.update({
tokens: allTokens[chainId]?.[selectedAddress] || [],
ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] || [],
});
});
}
_instantiateNewEthersProvider(): any {
return new ethers.providers.Web3Provider(this.config?.provider);
}
/**
* Adds a token to the stored token list.
*
* @param address - Hex address of the token contract.
* @param symbol - Symbol of the token.
* @param decimals - Number of decimals the token uses.
* @param image - Image of the token.
* @returns Current token list.
*/
async addToken(
address: string,
symbol: string,
decimals: number,
image?: string,
): Promise<Token[]> {
const releaseLock = await this.mutex.acquire();
try {
address = toChecksumHexAddress(address);
const { tokens, ignoredTokens } = this.state;
const isERC721 = await this._detectIsERC721(address);
const newEntry: Token = { address, symbol, decimals, image, isERC721 };
const previousEntry = tokens.find(
(token) => token.address.toLowerCase() === address.toLowerCase(),
);
if (previousEntry) {
const previousIndex = tokens.indexOf(previousEntry);
tokens[previousIndex] = newEntry;
} else {
tokens.push(newEntry);
}
const newIgnoredTokens = ignoredTokens.filter(
(tokenAddress) => tokenAddress.toLowerCase() !== address.toLowerCase(),
);
const { newAllTokens, newAllIgnoredTokens } = this._getNewAllTokensState(
tokens,
newIgnoredTokens,
);
this.update({
allTokens: newAllTokens,
tokens,
allIgnoredTokens: newAllIgnoredTokens,
ignoredTokens: newIgnoredTokens,
});
return tokens;
} finally {
releaseLock();
}
}
/**
* Adds a batch of tokens to the stored token list.
*
* @param tokensToAdd - Array of Tokens to be added or updated.
* @returns Current token list.
*/
async addTokens(tokensToAdd: Token[]): Promise<Token[]> {
const releaseLock = await this.mutex.acquire();
const { tokens, ignoredTokens } = this.state;
try {
tokensToAdd = await Promise.all(
tokensToAdd.map(async (token) => {
token.isERC721 = await this._detectIsERC721(token.address);
return token;
}),
);
let newIgnoredTokens = ignoredTokens;
tokensToAdd.forEach((tokenToAdd) => {
const { address, symbol, decimals, image, isERC721 } = tokenToAdd;
const checksumAddress = toChecksumHexAddress(address);
const newEntry: Token = {
address: checksumAddress,
symbol,
decimals,
image,
isERC721,
};
const previousEntry = tokens.find(
(token) =>
token.address.toLowerCase() === checksumAddress.toLowerCase(),
);
if (previousEntry) {
const previousIndex = tokens.indexOf(previousEntry);
tokens[previousIndex] = newEntry;
} else {
tokens.push(newEntry);
}
newIgnoredTokens = newIgnoredTokens.filter(
(tokenAddress) =>
tokenAddress.toLowerCase() !== address.toLowerCase(),
);
});
const { newAllTokens, newAllIgnoredTokens } = this._getNewAllTokensState(
tokens,
newIgnoredTokens,
);
this.update({
tokens,
allTokens: newAllTokens,
allIgnoredTokens: newAllIgnoredTokens,
ignoredTokens: newIgnoredTokens,
});
return tokens;
} finally {
releaseLock();
}
}
/**
* Adds isERC721 field to token object. This is called when a user attempts to add tokens that
* were previously added which do not yet had isERC721 field.
*
* @param tokenAddress - The contract address of the token requiring the isERC721 field added.
* @returns The new token object with the added isERC721 field.
*/
async updateTokenType(tokenAddress: string) {
const isERC721 = await this._detectIsERC721(tokenAddress);
const { tokens } = this.state;
const tokenIndex = tokens.findIndex((token) => {
return token.address.toLowerCase() === tokenAddress.toLowerCase();
});
tokens[tokenIndex].isERC721 = isERC721;
this.update({ tokens });
return tokens[tokenIndex];
}
/**
* Detects whether or not a token is ERC-721 compatible.
*
* @param tokenAddress - The token contract address.
* @returns A boolean indicating whether the token address passed in supports the EIP-721
* interface.
*/
async _detectIsERC721(tokenAddress: string) {
const checksumAddress = toChecksumHexAddress(tokenAddress);
// if this token is already in our contract metadata map we don't need
// to check against the contract
if (contractsMap[checksumAddress]?.erc721 === true) {
return Promise.resolve(true);
} else if (contractsMap[checksumAddress]?.erc20 === true) {
return Promise.resolve(false);
}
const tokenContract = await this._createEthersContract(
tokenAddress,
abiERC721,
this.ethersProvider,
);
try {
return await tokenContract.supportsInterface(ERC721_INTERFACE_ID);
} catch (error: any) {
// currently we see a variety of errors across different networks when
// token contracts are not ERC721 compatible. We need to figure out a better
// way of differentiating token interface types but for now if we get an error
// we have to assume the token is not ERC721 compatible.
return false;
}
}
async _createEthersContract(
tokenAddress: string,
abi: string,
ethersProvider: any,
): Promise<any> {
const tokenContract = await new ethers.Contract(
tokenAddress,
abi,
ethersProvider,
);
return tokenContract;
}
_generateRandomId(): string {
return random();
}
/**
* Adds a new suggestedAsset to state. Parameters will be validated according to
* asset type being watched. A `<suggestedAssetMeta.id>:pending` hub event will be emitted once added.
*
* @param asset - The asset to be watched. For now only ERC20 tokens are accepted.
* @param type - The asset type.
* @returns Object containing a Promise resolving to the suggestedAsset address if accepted.
*/
async watchAsset(asset: Token, type: string): Promise<AssetSuggestionResult> {
const suggestedAssetMeta = {
asset,
id: this._generateRandomId(),
status: SuggestedAssetStatus.pending as SuggestedAssetStatus.pending,
time: Date.now(),
type,
};
try {
switch (type) {
case 'ERC20':
validateTokenToWatch(asset);
break;
default:
throw new Error(`Asset of type ${type} not supported`);
}
} catch (error) {
this.failSuggestedAsset(suggestedAssetMeta, error);
return Promise.reject(error);
}
const result: Promise<string> = new Promise((resolve, reject) => {
this.hub.once(
`${suggestedAssetMeta.id}:finished`,
(meta: SuggestedAssetMeta) => {
switch (meta.status) {
case SuggestedAssetStatus.accepted:
return resolve(meta.asset.address);
case SuggestedAssetStatus.rejected:
return reject(new Error('User rejected to watch the asset.'));
case SuggestedAssetStatus.failed:
return reject(new Error(meta.error.message));
/* istanbul ignore next */
default:
return reject(new Error(`Unknown status: ${meta.status}`));
}
},
);
});
const { suggestedAssets } = this.state;
suggestedAssets.push(suggestedAssetMeta);
this.update({ suggestedAssets: [...suggestedAssets] });
this.hub.emit('pendingSuggestedAsset', suggestedAssetMeta);
return { result, suggestedAssetMeta };
}
/**
* Accepts to watch an asset and updates it's status and deletes the suggestedAsset from state,
* adding the asset to corresponding asset state. In this case ERC20 tokens.
* A `<suggestedAssetMeta.id>:finished` hub event is fired after accepted or failure.
*
* @param suggestedAssetID - The ID of the suggestedAsset to accept.
*/
async acceptWatchAsset(suggestedAssetID: string): Promise<void> {
const { suggestedAssets } = this.state;
const index = suggestedAssets.findIndex(
({ id }) => suggestedAssetID === id,
);
const suggestedAssetMeta = suggestedAssets[index];
try {
switch (suggestedAssetMeta.type) {
case 'ERC20':
const { address, symbol, decimals, image } = suggestedAssetMeta.asset;
await this.addToken(address, symbol, decimals, image);
suggestedAssetMeta.status = SuggestedAssetStatus.accepted;
this.hub.emit(
`${suggestedAssetMeta.id}:finished`,
suggestedAssetMeta,
);
break;
default:
throw new Error(
`Asset of type ${suggestedAssetMeta.type} not supported`,
);
}
} catch (error) {
this.failSuggestedAsset(suggestedAssetMeta, error);
}
const newSuggestedAssets = suggestedAssets.filter(
({ id }) => id !== suggestedAssetID,
);
this.update({ suggestedAssets: [...newSuggestedAssets] });
}
/**
* Rejects a watchAsset request based on its ID by setting its status to "rejected"
* and emitting a `<suggestedAssetMeta.id>:finished` hub event.
*
* @param suggestedAssetID - The ID of the suggestedAsset to accept.
*/
rejectWatchAsset(suggestedAssetID: string) {
const { suggestedAssets } = this.state;
const index = suggestedAssets.findIndex(
({ id }) => suggestedAssetID === id,
);
const suggestedAssetMeta = suggestedAssets[index];
if (!suggestedAssetMeta) {
return;
}
suggestedAssetMeta.status = SuggestedAssetStatus.rejected;
this.hub.emit(`${suggestedAssetMeta.id}:finished`, suggestedAssetMeta);
const newSuggestedAssets = suggestedAssets.filter(
({ id }) => id !== suggestedAssetID,
);
this.update({ suggestedAssets: [...newSuggestedAssets] });
}
/**
* Removes a token from the stored token list and saves it in ignored tokens list.
*
* @param address - The hex address of the token contract.
*/
removeAndIgnoreToken(address: string) {
address = toChecksumHexAddress(address);
const { tokens, ignoredTokens } = this.state;
const alreadyIgnored = ignoredTokens.find(
(tokenAddress) => tokenAddress.toLowerCase() === address.toLowerCase(),
);
const newTokens = tokens.filter((token) => {
if (token.address.toLowerCase() === address.toLowerCase()) {
!alreadyIgnored && ignoredTokens.push(address);
return false;
}
return true;
});
const { newAllTokens, newAllIgnoredTokens } = this._getNewAllTokensState(
newTokens,
ignoredTokens,
);
this.update({
allTokens: newAllTokens,
tokens: newTokens,
allIgnoredTokens: newAllIgnoredTokens,
ignoredTokens,
});
}
/**
* Takes a new tokens and ignoredTokens array for the current network/account combination
* and returns new allTokens and allIgnoredTokens state to update to.
*
* @param newTokens - The new tokens to set for the current network and selected account.
* @param newIgnoredTokens - The new ignored tokens to set for the current network and selected account.
* @returns The updated `allTokens` and `allIgnoredTokens` state.
*/
_getNewAllTokensState(newTokens: Token[], newIgnoredTokens: string[]) {
const { allTokens, allIgnoredTokens } = this.state;
const { chainId, selectedAddress } = this.config;
const networkTokens = allTokens[chainId];
const networkIgnoredTokens = allIgnoredTokens[chainId];
const newNetworkTokens = {
...networkTokens,
...{ [selectedAddress]: newTokens },
};
const newIgnoredNetworkTokens = {
...networkIgnoredTokens,
...{ [selectedAddress]: newIgnoredTokens },
};
const newAllTokens = {
...allTokens,
...{ [chainId]: newNetworkTokens },
};
const newAllIgnoredTokens = {
...allIgnoredTokens,
...{ [chainId]: newIgnoredNetworkTokens },
};
return { newAllTokens, newAllIgnoredTokens };
}
/**
* Removes all tokens from the ignored list.
*/
clearIgnoredTokens() {
this.update({ ignoredTokens: [], allIgnoredTokens: {} });
}
}
export default TokensController; | the_stack |
import { RTreeIndex } from '../rtree/rtreeIndex';
import { BaseExtension } from '../baseExtension';
import { GeoPackage } from '../../geoPackage';
import { Extension } from '../extension';
import { TableIndex } from './tableIndex';
import { FeatureDao } from '../../features/user/featureDao';
import { GeometryIndexDao } from './geometryIndexDao';
import { RTreeIndexDao } from '../rtree/rtreeIndexDao';
import { EnvelopeBuilder } from '../../geom/envelopeBuilder';
import { TableIndexDao } from './tableIndexDao';
import { Envelope } from '../../geom/envelope';
import { FeatureRow } from '../../features/user/featureRow';
import { GeometryData } from '../../geom/geometryData';
import { BoundingBox } from '../../boundingBox';
/**
* This class will either use the RTree index if it exists, or the
* Feature Table Index NGA Extension implementation. This extension is used to
* index Geometries within a feature table by their minimum bounding box for
* bounding box queries.
* @class
* @extends BaseExtension
*/
export class FeatureTableIndex extends BaseExtension {
public static readonly EXTENSION_GEOMETRY_INDEX_AUTHOR: string = 'nga';
public static readonly EXTENSION_GEOMETRY_INDEX_NAME_NO_AUTHOR: string = 'geometry_index';
public static readonly EXTENSION_NAME: string = Extension.buildExtensionName(
FeatureTableIndex.EXTENSION_GEOMETRY_INDEX_AUTHOR,
FeatureTableIndex.EXTENSION_GEOMETRY_INDEX_NAME_NO_AUTHOR,
);
public static readonly EXTENSION_GEOMETRY_INDEX_DEFINITION: string =
'http://ngageoint.github.io/GeoPackage/docs/extensions/geometry-index.html';
progress: Function;
tableName: string;
columnName: string;
tableIndexDao: TableIndexDao;
geometryIndexDao: GeometryIndexDao;
rtreeIndexDao: RTreeIndexDao;
rtreeIndex: RTreeIndex;
rtreeIndexed: boolean;
/**
*
* @param geoPackage GeoPackage object
* @param featureDao FeatureDao to index
*/
constructor(geoPackage: GeoPackage, public featureDao: FeatureDao<FeatureRow>) {
super(geoPackage);
this.progress;
this.extensionName = FeatureTableIndex.EXTENSION_NAME;
this.extensionDefinition = FeatureTableIndex.EXTENSION_GEOMETRY_INDEX_DEFINITION;
this.tableName = featureDao.table_name;
this.columnName = featureDao.getGeometryColumnName();
this.tableIndexDao = geoPackage.tableIndexDao;
this.geometryIndexDao = geoPackage.getGeometryIndexDao(featureDao);
this.rtreeIndexDao = new RTreeIndexDao(geoPackage, featureDao);
this.rtreeIndexDao.gpkgTableName = 'rtree_' + this.tableName + '_' + this.columnName;
this.rtreeIndex = new RTreeIndex(geoPackage, featureDao);
/**
* true if the table is indexed with an RTree
* @type {Boolean}
*/
this.rtreeIndexed = this.hasExtension('gpkg_rtree_index', this.tableName, this.columnName);
}
/**
* Index the table if not already indexed
* @param {Function} progress function which is called with progress while indexing
* @return {Promise<Boolean>} promise resolved when the indexing is complete
*/
async index(progress?: Function): Promise<boolean> {
return this.indexWithForce(false, progress);
}
/**
* Index the table if not already indexed or force is true
* @param {Boolean} force force index even if the table is already indexed
* @param {Function} progress function which is called with progress while indexing
* @return {Promise<Boolean>} promise resolved when the indexing is complete
*/
async indexWithForce(force?: false, progress?: Function): Promise<boolean> {
// eslint-disable-next-line @typescript-eslint/no-empty-function
progress = progress || function(): void {};
this.progress = function(message: any): void {
setTimeout(progress, 0, message);
};
let indexed = this.isIndexed();
if (!indexed || force) {
const rtreeIndex = new RTreeIndex(this.geoPackage, this.featureDao);
rtreeIndex.create();
this.rtreeIndexed = rtreeIndex.hasExtension(
rtreeIndex.extensionName,
rtreeIndex.tableName,
rtreeIndex.columnName,
);
indexed = this.isIndexed();
}
if (!indexed) {
this.getOrCreateExtension();
const tableIndex = this.getOrCreateTableIndex();
this.createOrClearGeometryIndicies();
return this.indexTable(tableIndex);
} else {
return indexed;
}
}
/**
* Index the table using the NGA index and Rtree if not already indexed or force is true
* @param {Boolean} force force index even if the table is already indexed
* @param {Function} progress function which is called with progress while indexing
* @return {Promise<Boolean>} promise resolved when the indexing is complete
*/
async ngaIndexWithForce(force?: false, progress?: Function): Promise<boolean> {
// eslint-disable-next-line @typescript-eslint/no-empty-function
progress = progress || function(): void {};
this.progress = function(message: any): void {
setTimeout(progress, 0, message);
};
const indexed = this.isIndexed(true);
if (!indexed || force) {
const rtreeIndex = new RTreeIndex(this.geoPackage, this.featureDao);
await rtreeIndex.create();
}
if (!indexed || force) {
this.getOrCreateExtension();
const tableIndex = await this.getOrCreateTableIndex();
await this.createOrClearGeometryIndicies();
return this.indexTable(tableIndex);
} else {
return indexed;
}
}
/**
* Check if the table is indexed either with an RTree or the NGA Feature Table Index
* @return {Boolean}
*/
isIndexed(checkOnlyNGA = false): boolean {
if (!checkOnlyNGA) {
const rtreeIndex = new RTreeIndex(this.geoPackage, this.featureDao);
this.rtreeIndexed = rtreeIndex.hasExtension(
rtreeIndex.extensionName,
rtreeIndex.tableName,
rtreeIndex.columnName,
);
if (this.rtreeIndexed) {
return true;
}
}
try {
const result = this.getFeatureTableIndexExtension();
if (result) {
const contentsDao = this.geoPackage.contentsDao;
const contents = contentsDao.queryForId(this.tableName);
if (!contents) return false;
const lastChange = new Date(contents.last_change);
const tableIndex: TableIndex = this.tableIndexDao.queryForId(this.tableName);
if (!tableIndex || !tableIndex.last_indexed) {
return false;
}
const lastIndexed = new Date(tableIndex.last_indexed);
return lastIndexed >= lastChange;
} else {
return false;
}
} catch (e) {
return false;
}
}
/**
* Returns the feature table index extension for this table and column name if exists
* @return {module:extension~Extension}
*/
getFeatureTableIndexExtension(): Extension {
return this.getExtension(this.extensionName, this.tableName, this.columnName)[0];
}
/**
* Get or create the extension for this table name and column name
* @return {module:extension~Extension}
*/
getOrCreateExtension(): Extension {
return this.getOrCreate(
this.extensionName,
this.tableName,
this.columnName,
this.extensionDefinition,
Extension.READ_WRITE,
);
}
/**
* Get or create if needed the table index
* @return {TableIndex}
*/
getOrCreateTableIndex(): TableIndex {
const tableIndex = this.tableIndex;
if (tableIndex) return tableIndex;
this.tableIndexDao.createTable();
this.createTableIndex();
return this.tableIndex;
}
/**
* Create the table index
* @return {module:extension/index~TableIndex}
*/
createTableIndex(): number {
const ti = new TableIndex();
ti.table_name = this.tableName;
ti.last_indexed = new Date();
return this.tableIndexDao.create(ti);
}
/**
* Get the table index
* @return {module:extension/index~TableIndex}
*/
get tableIndex(): TableIndex {
if (this.tableIndexDao.isTableExists()) {
return this.tableIndexDao.queryForId(this.tableName);
} else {
return;
}
}
/**
* Clear the geometry indices or create the table if needed
* @return {Promise} resolved when complete
*/
createOrClearGeometryIndicies(): number {
this.geometryIndexDao.createTable();
return this.clearGeometryIndicies();
}
/**
* Clears the geometry indices
* @return {Number} number of rows deleted
*/
clearGeometryIndicies(): number {
const where = this.geometryIndexDao.buildWhereWithFieldAndValue(GeometryIndexDao.COLUMN_TABLE_NAME, this.tableName);
const whereArgs = this.geometryIndexDao.buildWhereArgs(this.tableName);
return this.geometryIndexDao.deleteWhere(where, whereArgs);
}
/**
* Indexes the table
* @param {module:extension/index~TableIndex} tableIndex TableIndex
* @return {Promise} resolved when complete
*/
async indexTable(tableIndex: TableIndex): Promise<boolean> {
return new Promise((resolve: Function, reject: Function) => {
setTimeout(() => {
this.indexChunk(0, tableIndex, resolve, reject);
});
}).then(() => {
return this.updateLastIndexed(tableIndex) === 1;
});
}
/**
* Indexes a chunk of 100 rows
* @param {Number} page page to start on
* @param {module:extension/index~TableIndex} tableIndex TableIndex
* @param {Function} resolve function to call when all chunks are indexed
* @param {Function} reject called if there is an error
*/
indexChunk(page: number, tableIndex: TableIndex, resolve: Function, reject: Function): void {
const rows = this.featureDao.queryForChunk(100, page);
if (rows.length) {
this.progress('Indexing ' + page * 100 + ' to ' + (page + 1) * 100);
console.log('Indexing ' + page * 100 + ' to ' + (page + 1) * 100);
rows.forEach(row => {
const fr = this.featureDao.getRow(row) as FeatureRow;
this.indexRow(tableIndex, fr.id, fr.geometry);
});
setTimeout(() => {
this.indexChunk(++page, tableIndex, resolve, reject);
});
} else {
resolve();
}
}
/**
* Indexes a row
* @param {ableIndex} tableIndex TableIndex`
* @param {Number} geomId id of the row
* @param {GeometryData} geomData GeometryData to index
* @return {Boolean} success
*/
indexRow(tableIndex: TableIndex, geomId: number, geomData: GeometryData): boolean {
if (!geomData) return false;
let envelope = geomData.envelope;
if (!envelope) {
const geometry = geomData.geometry;
if (geometry) {
envelope = EnvelopeBuilder.buildEnvelopeWithGeometry(geometry);
}
}
if (envelope) {
const geometryIndex = this.geometryIndexDao.populate(tableIndex, geomId, envelope);
return this.geometryIndexDao.createOrUpdate(geometryIndex) === 1;
} else {
return false;
}
}
/**
* Update the last time this feature table was indexed
* @param {module:extension/index~TableIndex} tableIndex TableIndex
* @return {Object} update status
*/
updateLastIndexed(tableIndex: TableIndex): number {
if (!tableIndex) {
tableIndex = new TableIndex();
tableIndex.table_name = this.tableName;
}
tableIndex.last_indexed = new Date().toISOString();
const updateIndex = this.tableIndexDao.createOrUpdate(tableIndex);
return updateIndex;
}
/**
* Query the index with the specified bounding box and projection
* @param {module:boundingBox~BoundingBox} boundingBox bounding box to query for
* @param {string} projection projection the boundingBox is in
* @return {IterableIterator}
*/
queryWithBoundingBox(boundingBox: BoundingBox, projection: string | proj4.Converter): IterableIterator<any> {
const projectedBoundingBox = boundingBox.projectBoundingBox(projection, this.featureDao.projection);
const envelope = projectedBoundingBox.buildEnvelope();
return this.queryWithGeometryEnvelope(envelope);
}
/**
* Query witha geometry envelope
* @param {any} envelope envelope
* @return {IterableIterator<any>}
*/
queryWithGeometryEnvelope(envelope: Envelope): IterableIterator<any> {
if (this.rtreeIndexed) {
return this.rtreeIndexDao.queryWithGeometryEnvelope(envelope);
} else {
return this.geometryIndexDao.queryWithGeometryEnvelope(envelope);
}
}
/**
* Count the index with the specified bounding box and projection
* @param {module:boundingBox~BoundingBox} boundingBox bounding box to query for
* @param {string} projection projection the boundingBox is in
* @return {Number}
*/
countWithBoundingBox(boundingBox: BoundingBox, projection: string): number {
const projectedBoundingBox = boundingBox.projectBoundingBox(projection, this.featureDao.projection);
const envelope = projectedBoundingBox.buildEnvelope();
return this.countWithGeometryEnvelope(envelope);
}
/**
* Count with a geometry envelope
* @param {any} envelope envelope
* @return {Number}
*/
countWithGeometryEnvelope(envelope: Envelope): number {
if (this.rtreeIndexed) {
return this.rtreeIndexDao.countWithGeometryEnvelope(envelope);
} else {
return this.geometryIndexDao.countWithGeometryEnvelope(envelope);
}
}
} | the_stack |
* @module Editing
*/
import { BeDuration, BeEvent, BentleyError } from "@itwin/core-bentley";
import { Cartographic, ColorDef, EcefLocation, EcefLocationProps } from "@itwin/core-common";
import {
BeButton, BeButtonEvent, BriefcaseConnection, CoreTools, DecorateContext, EditManipulator, EventHandled, GraphicType, HitDetail, IModelApp,
IModelConnection, MessageBoxIconType, MessageBoxType, MessageBoxValue, NotifyMessageDetails, OutputMessagePriority, QuantityType, ScreenViewport,
Tool, ViewClipControlArrow, ViewClipDecorationProvider, ViewClipShapeModifyTool, ViewClipTool, Viewport,
} from "@itwin/core-frontend";
import {
Angle, Arc3d, AxisIndex, AxisOrder, ClipShape, ClipVector, Constant, Matrix3d, Point3d, PolygonOps, Range1d, Range3d, Range3dProps, Ray3d,
Transform, Vector3d,
} from "@itwin/core-geometry";
import { BasicManipulationCommandIpc, editorBuiltInCmdIds } from "@itwin/editor-common";
import { EditTools } from "../EditTool";
import { ProjectGeolocationNorthTool, ProjectGeolocationPointTool } from "./ProjectGeolocation";
function translateMessage(key: string) { return EditTools.translate(`ProjectLocation:Message.${key}`); }
function translateMessageBold(key: string) { return `<b>${translateMessage(key)}:</b> `; }
function translateCoreMeasureBold(key: string) { return `<b>${CoreTools.translate(`Measure.Labels.${key}`)}:</b> `; }
function clearViewClip(vp: ScreenViewport): boolean {
if (!ViewClipTool.doClipClear(vp))
return false;
ViewClipDecorationProvider.create().onClearClip(vp); // Send clear event...
ViewClipDecorationProvider.clear();
return true;
}
function clipToProjectExtents(vp: ScreenViewport): boolean {
clearViewClip(vp); // Clear any existing view clip and send clear event...
ViewClipTool.enableClipVolume(vp);
return ViewClipTool.doClipToRange(vp, vp.iModel.projectExtents, Transform.createIdentity());
}
function enableBackgroundMap(viewport: Viewport, onOff: boolean): boolean {
if (onOff === viewport.viewFlags.backgroundMap)
return false;
viewport.viewFlags = viewport.viewFlags.with("backgroundMap", onOff);
return true;
}
function updateMapDisplay(vp: ScreenViewport, turnOnMap: boolean): void {
if (!turnOnMap || !enableBackgroundMap(vp, true))
vp.invalidateRenderPlan();
}
class ProjectExtentsControlArrow extends ViewClipControlArrow {
public extentValid = true;
}
/** Values for [[ProjectExtentsClipDecoration.onChanged] event.
* @beta
*/
export enum ProjectLocationChanged {
/** Extents has been modified (unsaved changes) */
Extents,
/** Geolocation has been modified (unsaved changes) */
Geolocation,
/** Abandon unsaved changes to extents */
ResetExtents,
/** Abandon unsaved changes to geolocation */
ResetGeolocation,
/** Decoration hidden (unsaved changes preserved) */
Hide,
/** Decoration shown (unsaved changes restored) */
Show,
/** Save changes to extents and geolocation */
Save,
}
/** Controls to modify project extents shown using view clip
* @beta
*/
export class ProjectExtentsClipDecoration extends EditManipulator.HandleProvider {
private static _decorator?: ProjectExtentsClipDecoration;
protected _clip?: ClipVector;
protected _clipId?: string;
protected _clipShape?: ClipShape;
protected _clipShapeExtents?: Range1d;
protected _clipRange?: Range3d;
protected _extentsLengthValid = true;
protected _extentsWidthValid = true;
protected _extentsHeightValid = true;
protected _ecefLocation?: EcefLocation;
protected _allowEcefLocationChange = false;
protected _controlIds: string[] = [];
protected _controls: ProjectExtentsControlArrow[] = [];
protected _monumentPoint?: Point3d;
protected _northDirection?: Ray3d;
protected _monumentId?: string;
protected _northId?: string;
protected _suspendDecorator = false;
protected _removeViewCloseListener?: () => void;
public suspendGeolocationDecorations = false;
/** Called when project extents or geolocation is modified */
public readonly onChanged = new BeEvent<(iModel: IModelConnection, ev: ProjectLocationChanged) => void>();
public constructor(public viewport: ScreenViewport) {
super(viewport.iModel);
if (!this.init())
return;
this._monumentId = this.iModel.transientIds.next;
this._northId = this.iModel.transientIds.next;
this._clipId = this.iModel.transientIds.next;
this.start();
}
protected start(): void {
this.updateDecorationListener(true);
this._removeViewCloseListener = IModelApp.viewManager.onViewClose.addListener((vp) => this.onViewClose(vp));
this.iModel.selectionSet.replace(this._clipId!); // Always select decoration on create...
}
protected override stop(): void {
const selectedId = (undefined !== this._clipId && this.iModel.selectionSet.has(this._clipId)) ? this._clipId : undefined;
this._clipId = undefined; // Invalidate id so that decorator will be dropped...
super.stop();
if (undefined !== selectedId)
this.iModel.selectionSet.remove(selectedId); // Don't leave decorator id in selection set...
if (undefined !== this._removeViewCloseListener) {
this._removeViewCloseListener();
this._removeViewCloseListener = undefined;
}
}
protected init(): boolean {
if (!this.getClipData())
return false;
this._ecefLocation = this.iModel.ecefLocation;
this._monumentPoint = this.getMonumentPoint();
this._northDirection = this.getNorthDirection();
return true;
}
public onViewClose(vp: ScreenViewport): void {
if (this.viewport === vp)
ProjectExtentsClipDecoration.clear();
}
private getClipData(): boolean {
this._clip = this._clipShape = this._clipShapeExtents = this._clipRange = undefined;
const clip = this.viewport.view.getViewClip();
if (undefined === clip)
return false;
const clipShape = ViewClipTool.isSingleClipShape(clip);
if (undefined === clipShape)
return false;
if (5 !== clipShape.polygon.length || undefined === clipShape.zLow || undefined === clipShape.zHigh)
return false; // Not a box, can't be project extents clip...
if (undefined !== clipShape.transformFromClip && !clipShape.transformFromClip.isIdentity)
return false; // Not axis aligned, can't be project extents clip...
this._clipShapeExtents = Range1d.createXX(clipShape.zLow, clipShape.zHigh);
this._clipShape = clipShape;
this._clip = clip;
this._clipRange = Range3d.create();
const shapePtsLo = ViewClipTool.getClipShapePoints(this._clipShape, this._clipShapeExtents.low);
const shapePtsHi = ViewClipTool.getClipShapePoints(this._clipShape, this._clipShapeExtents.high);
this._clipRange.extendArray(shapePtsLo);
this._clipRange.extendArray(shapePtsHi);
return true;
}
private ensureNumControls(numReqControls: number): void {
const numCurrent = this._controlIds.length;
if (numCurrent < numReqControls) {
const transientIds = this.iModel.transientIds;
for (let i: number = numCurrent; i < numReqControls; i++)
this._controlIds[i] = transientIds.next;
} else if (numCurrent > numReqControls) {
this._controlIds.length = numReqControls;
}
}
private createClipShapeControls(): boolean {
if (undefined === this._clipShape)
return false;
const shapePtsLo = ViewClipTool.getClipShapePoints(this._clipShape, this._clipShapeExtents!.low);
const shapePtsHi = ViewClipTool.getClipShapePoints(this._clipShape, this._clipShapeExtents!.high);
const shapeArea = PolygonOps.centroidAreaNormal(shapePtsLo);
if (undefined === shapeArea)
return false;
const numControls = shapePtsLo.length + 1; // Number of edge midpoints plus zLow and zHigh...
this.ensureNumControls(numControls);
for (let i: number = 0; i < numControls - 2; i++) {
const midPtLo = shapePtsLo[i].interpolate(0.5, shapePtsLo[i + 1]);
const midPtHi = shapePtsHi[i].interpolate(0.5, shapePtsHi[i + 1]);
const faceCenter = midPtLo.interpolate(0.5, midPtHi);
const edgeTangent = Vector3d.createStartEnd(shapePtsLo[i], shapePtsLo[i + 1]);
const faceNormal = edgeTangent.crossProduct(shapeArea.direction); faceNormal.normalizeInPlace();
this._controls[i] = new ProjectExtentsControlArrow(faceCenter, faceNormal, 0.75);
this._controls[i].extentValid = (faceNormal.isParallelTo(Vector3d.unitX(), true) ? this._extentsLengthValid : this._extentsWidthValid);
}
const zFillColor = ColorDef.from(150, 150, 250);
this._controls[numControls - 2] = new ProjectExtentsControlArrow(shapeArea.origin, Vector3d.unitZ(-1.0), 0.75, zFillColor, undefined, "zLow");
this._controls[numControls - 1] = new ProjectExtentsControlArrow(shapeArea.origin.plusScaled(Vector3d.unitZ(), shapePtsLo[0].distance(shapePtsHi[0])), Vector3d.unitZ(), 0.75, zFillColor, undefined, "zHigh");
this._controls[numControls - 2].extentValid = this._extentsHeightValid;
this._controls[numControls - 1].extentValid = this._extentsHeightValid;
return true;
}
/** Allow project extents for map projections to be larger since curvature of the earth is accounted for. */
protected get maxExtentLength(): number { return ((this._allowEcefLocationChange ? 20 : 350) * Constant.oneKilometer); }
/** Impose some reasonable height limit for project extents. */
protected get maxExtentHeight(): number { return (2 * Constant.oneKilometer); }
protected hasValidGCS(): boolean {
if (!this.iModel.isGeoLocated || this.iModel.noGcsDefined)
return false;
const gcs = this.iModel.geographicCoordinateSystem;
if (undefined === gcs || undefined === gcs.horizontalCRS)
return false; // A valid GCS ought to have horizontalCR defined...
// Check for approximate GCS (such as from MicroStation's "From Placemark" tool) and allow it to be replaced...
const hasValidId = (undefined !== gcs.horizontalCRS.id && 0 !== gcs.horizontalCRS.id.length);
const hasValidDescr = (undefined !== gcs.horizontalCRS.description && 0 !== gcs.horizontalCRS.description.length);
const hasValidProjection = (undefined !== gcs.horizontalCRS.projection && "AzimuthalEqualArea" !== gcs.horizontalCRS.projection.method);
return hasValidId || hasValidDescr || hasValidProjection;
}
protected async createControls(): Promise<boolean> {
// Always update to current view clip to handle post-modify, etc.
if (undefined === this._clipId || !this.getClipData())
return false;
this._allowEcefLocationChange = !this.hasValidGCS();
if (undefined !== this._clipRange) {
this._extentsLengthValid = (this._clipRange.xLength() < this.maxExtentLength);
this._extentsWidthValid = (this._clipRange.yLength() < this.maxExtentLength);
this._extentsHeightValid = (this._clipRange.zLength() < this.maxExtentHeight);
}
// Show controls if only range box and it's controls are selected, selection set doesn't include any other elements...
let showControls = false;
if (this.iModel.selectionSet.size <= this._controlIds.length + 1 && this.iModel.selectionSet.has(this._clipId)) {
showControls = true;
if (this.iModel.selectionSet.size > 1) {
this.iModel.selectionSet.elements.forEach((val) => {
if (this._clipId !== val && !this._controlIds.includes(val))
showControls = false;
});
}
}
if (!showControls)
return false; // Don't clear decoration on de-select...
return this.createClipShapeControls();
}
protected override clearControls(): void {
this.iModel.selectionSet.remove(this._controlIds); // Remove any selected controls as they won't continue to be displayed...
super.clearControls();
}
protected async modifyControls(hit: HitDetail, _ev: BeButtonEvent): Promise<boolean> {
if (undefined === this._clip || hit.sourceId === this._clipId)
return false;
const saveQualifiers = IModelApp.toolAdmin.currentInputState.qualifiers;
if (undefined !== this._clipShape) {
const clipShapeModifyTool = new ViewClipShapeModifyTool(this, this._clip, this.viewport, hit.sourceId, this._controlIds, this._controls);
this._suspendDecorator = await clipShapeModifyTool.run();
}
if (this._suspendDecorator)
IModelApp.toolAdmin.currentInputState.qualifiers = saveQualifiers; // onInstallTool cleared qualifiers, preserve for "modify all" behavior when shift was held and drag started...
return this._suspendDecorator;
}
protected override async onRightClick(_hit: HitDetail, _ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; }
protected override async onTouchTap(hit: HitDetail, ev: BeButtonEvent): Promise<EventHandled> { return (hit.sourceId === this._clipId ? EventHandled.No : super.onTouchTap(hit, ev)); }
public override async onDecorationButtonEvent(hit: HitDetail, ev: BeButtonEvent): Promise<EventHandled> {
if (hit.sourceId === this._monumentId) {
if (BeButton.Data === ev.button && !ev.isDown && !ev.isDragging)
await ProjectGeolocationPointTool.startTool();
return EventHandled.Yes; // Only pickable for tooltip, don't allow selection...
}
if (hit.sourceId === this._northId) {
if (BeButton.Data === ev.button && !ev.isDown && !ev.isDragging)
await ProjectGeolocationNorthTool.startTool();
return EventHandled.Yes; // Only pickable for tooltip, don't allow selection...
}
return super.onDecorationButtonEvent(hit, ev);
}
public override onManipulatorEvent(eventType: EditManipulator.EventType): void {
if (EditManipulator.EventType.Accept === eventType)
this.onChanged.raiseEvent(this.iModel, ProjectLocationChanged.Extents);
this._suspendDecorator = false;
super.onManipulatorEvent(eventType);
}
public async getDecorationToolTip(hit: HitDetail): Promise<HTMLElement | string> {
const quantityFormatter = IModelApp.quantityFormatter;
const toolTip = document.createElement("div");
let toolTipHtml = "";
if (hit.sourceId === this._monumentId) {
toolTipHtml += `${translateMessage("ModifyGeolocation")}<br>`;
const coordFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Coordinate);
if (undefined !== coordFormatterSpec) {
const pointAdjusted = this._monumentPoint!.minus(this.iModel.globalOrigin);
const formattedPointX = quantityFormatter.formatQuantity(pointAdjusted.x, coordFormatterSpec);
const formattedPointY = quantityFormatter.formatQuantity(pointAdjusted.y, coordFormatterSpec);
const formattedPointZ = quantityFormatter.formatQuantity(pointAdjusted.z, coordFormatterSpec);
toolTipHtml += `${translateCoreMeasureBold("Coordinate") + formattedPointX}, ${formattedPointY}, ${formattedPointZ}<br>`;
}
const latLongFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.LatLong);
if (undefined !== latLongFormatterSpec && undefined !== coordFormatterSpec && this.iModel.isGeoLocated) {
const cartographic = this.iModel.spatialToCartographicFromEcef(this._monumentPoint!);
const formattedLat = quantityFormatter.formatQuantity(Math.abs(cartographic.latitude), latLongFormatterSpec);
const formattedLong = quantityFormatter.formatQuantity(Math.abs(cartographic.longitude), latLongFormatterSpec);
const formattedHeight = quantityFormatter.formatQuantity(cartographic.height, coordFormatterSpec);
const latDir = CoreTools.translate(cartographic.latitude < 0 ? "Measure.Labels.S" : "Measure.Labels.N");
const longDir = CoreTools.translate(cartographic.longitude < 0 ? "Measure.Labels.W" : "Measure.Labels.E");
toolTipHtml += `${translateCoreMeasureBold("LatLong") + formattedLat + latDir}, ${formattedLong}${longDir}<br>`;
toolTipHtml += `${translateCoreMeasureBold("Altitude") + formattedHeight}<br>`;
}
} else if (hit.sourceId === this._northId) {
toolTipHtml += `${translateMessage("ModifyNorthDirection")}<br>`;
const angleFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Angle);
if (undefined !== angleFormatterSpec) {
const formattedAngle = quantityFormatter.formatQuantity(this.getClockwiseAngleToNorth().radians, angleFormatterSpec);
toolTipHtml += `${translateMessageBold("Angle") + formattedAngle}<br>`;
}
} else if (hit.sourceId === this._clipId) {
const extentsValid = (this._extentsLengthValid && this._extentsWidthValid && this._extentsHeightValid);
toolTipHtml += `${translateMessage(extentsValid ? "ProjectExtents" : "LargeProjectExtents")}<br>`;
const distanceFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length);
if (undefined !== distanceFormatterSpec && undefined !== this._clipRange) {
const formattedLength = quantityFormatter.formatQuantity(this._clipRange.xLength(), distanceFormatterSpec);
const formattedWidth = quantityFormatter.formatQuantity(this._clipRange.yLength(), distanceFormatterSpec);
const formattedHeight = quantityFormatter.formatQuantity(this._clipRange.zLength(), distanceFormatterSpec);
toolTipHtml += `${translateMessageBold("Length") + formattedLength}<br>`;
toolTipHtml += `${translateMessageBold("Width") + formattedWidth}<br>`;
toolTipHtml += `${translateMessageBold("Height") + formattedHeight}<br>`;
}
} else {
const arrowIndex = this._controlIds.indexOf(hit.sourceId);
if (-1 !== arrowIndex) {
toolTipHtml += `${translateMessage("ModifyProjectExtents")}<br>`;
const distanceFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length);
if (undefined !== distanceFormatterSpec && undefined !== this._clipRange) {
const arrowControl = this._controls[arrowIndex];
let arrowLabel = "";
let arrowLength = 0.0;
let arrowLengthMax = 0.0;
if (arrowControl.direction.isParallelTo(Vector3d.unitX(), true)) {
arrowLabel = "Length";
arrowLength = this._clipRange.xLength();
if (!this._extentsLengthValid)
arrowLengthMax = this.maxExtentLength;
} else if (arrowControl.direction.isParallelTo(Vector3d.unitY(), true)) {
arrowLabel = "Width";
arrowLength = this._clipRange.yLength();
if (!this._extentsWidthValid)
arrowLengthMax = this.maxExtentLength;
} else {
arrowLabel = "Height";
arrowLength = this._clipRange.zLength();
if (!this._extentsHeightValid)
arrowLengthMax = this.maxExtentHeight;
const coordFormatterSpec = (this.iModel.isGeoLocated ? quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Coordinate) : undefined);
if (undefined !== coordFormatterSpec) {
const heightPt = ("zLow" === arrowControl.name ? this._clipRange.low : this._clipRange.high);
const cartographic = this.iModel.spatialToCartographicFromEcef(heightPt);
const formattedAltitude = quantityFormatter.formatQuantity(cartographic.height, coordFormatterSpec);
toolTipHtml += `${translateCoreMeasureBold("Altitude") + formattedAltitude}<br>`;
}
}
const formattedLength = quantityFormatter.formatQuantity(arrowLength, distanceFormatterSpec);
toolTipHtml += `${translateMessageBold(arrowLabel) + formattedLength}<br>`;
if (0.0 !== arrowLengthMax) {
const formattedMaxLength = quantityFormatter.formatQuantity(arrowLengthMax, distanceFormatterSpec);
toolTipHtml += `${translateMessageBold("MaxExtent") + formattedMaxLength}<br>`;
}
}
}
}
toolTip.innerHTML = toolTipHtml;
return toolTip;
}
public testDecorationHit(id: string): boolean { return (id === this._monumentId || id === this._northId || id === this._clipId || this._controlIds.includes(id)); }
protected override updateDecorationListener(_add: boolean): void { super.updateDecorationListener(undefined !== this._clipId); } // Decorator isn't just for resize controls...
public getMonumentPoint(): Point3d {
const origin = Point3d.createZero();
if (this.iModel.ecefLocation && this.iModel.ecefLocation.cartographicOrigin)
return this.iModel.cartographicToSpatialFromEcef(this.iModel.ecefLocation.cartographicOrigin, origin);
origin.setFrom(this.iModel.projectExtents.low);
if (0.0 > this.iModel.projectExtents.low.z && 0.0 < this.iModel.projectExtents.high.z)
origin.z = 0.0;
return origin;
}
public getClockwiseAngleToNorth(): Angle {
const angle = this.getNorthAngle();
angle.setRadians(Angle.adjustRadians0To2Pi(angle.radians));
return angle;
}
public getNorthAngle(): Angle {
const northDirection = (undefined !== this._northDirection ? this._northDirection : this.getNorthDirection());
return northDirection.direction.angleToXY(Vector3d.unitY());
}
public getNorthDirection(refOrigin?: Point3d): Ray3d {
const origin = (undefined !== refOrigin ? refOrigin : this.iModel.projectExtents.center);
if (!this.iModel.isGeoLocated)
return Ray3d.create(origin, Vector3d.unitY());
const cartographic = this.iModel.spatialToCartographicFromEcef(origin);
cartographic.latitude += Angle.createDegrees(0.01).radians;
const pt2 = this.iModel.cartographicToSpatialFromEcef(cartographic);
const northVec = Vector3d.createStartEnd(origin, pt2);
northVec.z = 0.0;
northVec.normalizeInPlace();
return Ray3d.create(origin, northVec);
}
public drawNorthArrow(context: DecorateContext, northDir: Ray3d, id?: string): void {
const vp = context.viewport;
const pixelSize = vp.pixelsFromInches(0.55);
const scale = vp.viewingSpace.getPixelSizeAtPoint(northDir.origin) * pixelSize;
const matrix = Matrix3d.createRigidFromColumns(northDir.direction, Vector3d.unitZ(), AxisOrder.YZX);
if (undefined === matrix)
return;
matrix.scaleColumnsInPlace(scale, scale, scale);
const arrowTrans = Transform.createRefs(northDir.origin, matrix);
const northArrowBuilder = context.createGraphicBuilder(GraphicType.WorldOverlay, arrowTrans, id);
const color = ColorDef.white;
const arrowOutline: Point3d[] = [];
arrowOutline[0] = Point3d.create(0.0, 0.65);
arrowOutline[1] = Point3d.create(-0.45, -0.5);
arrowOutline[2] = Point3d.create(0.0, -0.2);
arrowOutline[3] = Point3d.create(0.45, -0.5);
arrowOutline[4] = arrowOutline[0].clone();
const arrowLeftFill: Point3d[] = [];
arrowLeftFill[0] = arrowOutline[0].clone();
arrowLeftFill[1] = arrowOutline[1].clone();
arrowLeftFill[2] = arrowOutline[2].clone();
arrowLeftFill[3] = arrowLeftFill[0].clone();
const arrowRightFill: Point3d[] = [];
arrowRightFill[0] = arrowOutline[0].clone();
arrowRightFill[1] = arrowOutline[3].clone();
arrowRightFill[2] = arrowOutline[2].clone();
arrowRightFill[3] = arrowRightFill[0].clone();
northArrowBuilder.setSymbology(color, ColorDef.from(0, 0, 0, 200), 1);
northArrowBuilder.addArc(Arc3d.createXY(Point3d.createZero(), 0.6), true, true);
northArrowBuilder.addArc(Arc3d.createXY(Point3d.create(0.0, 0.85), 0.2), true, true);
northArrowBuilder.setSymbology(color, color, 2);
northArrowBuilder.addArc(Arc3d.createXY(Point3d.createZero(), 0.5), false, false);
northArrowBuilder.addLineString([Point3d.create(0.6, 0.0), Point3d.create(-0.6, 0.0)]);
northArrowBuilder.addLineString([Point3d.create(0.0, 0.6), Point3d.create(0.0, -0.6)]);
northArrowBuilder.setSymbology(color, ColorDef.from(150, 150, 150), 1);
northArrowBuilder.addShape(arrowLeftFill);
northArrowBuilder.setSymbology(color, ColorDef.black, 1);
northArrowBuilder.addShape(arrowRightFill);
northArrowBuilder.setSymbology(color, color, 1);
northArrowBuilder.addLineString(arrowOutline);
northArrowBuilder.setSymbology(color, color, 3);
northArrowBuilder.addLineString([Point3d.create(-0.1, 0.75), Point3d.create(-0.1, 0.95), Point3d.create(0.1, 0.75), Point3d.create(0.1, 0.95)]);
context.addDecorationFromBuilder(northArrowBuilder);
}
public drawMonumentPoint(context: DecorateContext, point: Point3d, scaleFactor: number, id?: string): void {
const vp = context.viewport;
const pixelSize = vp.pixelsFromInches(0.25) * scaleFactor;
const scale = vp.viewingSpace.getPixelSizeAtPoint(point) * pixelSize;
const matrix = Matrix3d.createRotationAroundAxisIndex(AxisIndex.Z, Angle.createDegrees(45.0));
matrix.scaleColumnsInPlace(scale, scale, scale);
const monumentTrans = Transform.createRefs(point, matrix);
const monumentPointBuilder = context.createGraphicBuilder(GraphicType.WorldOverlay, monumentTrans, id);
const color = ColorDef.white;
monumentPointBuilder.setSymbology(color, ColorDef.from(0, 0, 0, 150), 1);
monumentPointBuilder.addArc(Arc3d.createXY(Point3d.createZero(), 0.7), true, true);
monumentPointBuilder.setSymbology(color, color, 2);
monumentPointBuilder.addArc(Arc3d.createXY(Point3d.createZero(), 0.5), false, false);
monumentPointBuilder.addLineString([Point3d.create(0.5, 0.0), Point3d.create(-0.5, 0.0)]);
monumentPointBuilder.addLineString([Point3d.create(0.0, 0.5), Point3d.create(0.0, -0.5)]);
context.addDecorationFromBuilder(monumentPointBuilder);
}
protected drawAreaTooLargeIndicator(context: DecorateContext): void {
if ((this._extentsLengthValid && this._extentsWidthValid) || undefined === this._clipRange)
return;
const corners = this._clipRange.corners();
const indices = Range3d.faceCornerIndices(5);
const points: Point3d[] = [];
for (const index of indices)
points.push(corners[index]);
const areaWarnColor = ColorDef.red.withAlpha(50);
const areaWarnBuilder = context.createGraphicBuilder(GraphicType.WorldDecoration);
areaWarnBuilder.setSymbology(areaWarnColor, areaWarnColor, 1);
areaWarnBuilder.addShape(points);
context.addDecorationFromBuilder(areaWarnBuilder);
}
protected drawExtentTooLargeIndicator(context: DecorateContext, worldPoint: Point3d, sizePixels: number): void {
const position = context.viewport.worldToView(worldPoint); position.x = Math.floor(position.x) + 0.5; position.y = Math.floor(position.y) + 0.5;
const drawDecoration = (ctx: CanvasRenderingContext2D) => {
ctx.lineWidth = 4;
ctx.lineCap = "round";
ctx.strokeStyle = "rgba(255,0,0,.75)";
ctx.fillStyle = "rgba(255,255,255,.75)";
ctx.shadowColor = "black";
ctx.shadowBlur = 5;
ctx.beginPath();
ctx.moveTo(0, -sizePixels);
ctx.lineTo(-sizePixels, sizePixels);
ctx.lineTo(sizePixels, sizePixels);
ctx.lineTo(0, -sizePixels);
ctx.fill();
ctx.shadowBlur = 0;
ctx.beginPath();
ctx.moveTo(0, -sizePixels);
ctx.lineTo(-sizePixels, sizePixels);
ctx.lineTo(sizePixels, sizePixels);
ctx.lineTo(0, -sizePixels);
ctx.stroke();
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, -sizePixels * 0.2);
ctx.lineTo(0, sizePixels * 0.3);
ctx.moveTo(0, (sizePixels * 0.3) + 4);
ctx.lineTo(0, (sizePixels * 0.3) + 4.5);
ctx.stroke();
};
context.addCanvasDecoration({ position, drawDecoration });
}
public override decorate(context: DecorateContext): void {
if (this._suspendDecorator)
return;
if (undefined === this._clipId || undefined === this._clipShape || undefined === this._clipRange)
return;
const vp = context.viewport;
if (this.viewport !== vp)
return;
if (!this.suspendGeolocationDecorations && undefined !== this._northDirection && this.iModel.isGeoLocated)
this.drawNorthArrow(context, this._northDirection, this._allowEcefLocationChange ? this._northId : undefined); // Show north, but don't make pickable if it shouldn't be modified...
const maxSizeInches = ((this._clipRange.maxLength() / vp.viewingSpace.getPixelSizeAtPoint(this._clipRange.center)) / vp.pixelsPerInch) * 0.5; // Display size limit when zooming out...
if (maxSizeInches < 0.5)
return;
if (!this.suspendGeolocationDecorations && undefined !== this._monumentPoint && this._allowEcefLocationChange)
this.drawMonumentPoint(context, this._monumentPoint, 1.0, this._monumentId);
ViewClipTool.drawClipShape(context, this._clipShape, this._clipShapeExtents!, ColorDef.white.adjustedForContrast(context.viewport.view.backgroundColor), 3, this._clipId);
this.drawAreaTooLargeIndicator(context);
if (!this._isActive)
return;
const outlineColor = ColorDef.from(0, 0, 0, 50).adjustedForContrast(vp.view.backgroundColor);
const fillVisColor = ColorDef.from(150, 250, 200, 225).adjustedForContrast(vp.view.backgroundColor);
const fillHidColor = fillVisColor.withAlpha(200);
const fillSelColor = fillVisColor.inverse().withAlpha(75);
const shapePts = EditManipulator.HandleUtils.getArrowShape(0.0, 0.15, 0.55, 1.0, 0.3, 0.5, 0.1);
for (let iFace = 0; iFace < this._controlIds.length; iFace++) {
const sizeInches = Math.min(this._controls[iFace].sizeInches, maxSizeInches);
if (0.0 === sizeInches)
continue;
const anchorRay = ViewClipTool.getClipRayTransformed(this._controls[iFace].origin, this._controls[iFace].direction, undefined !== this._clipShape ? this._clipShape.transformFromClip : undefined);
const transform = EditManipulator.HandleUtils.getArrowTransform(vp, anchorRay.origin, anchorRay.direction, sizeInches);
if (undefined === transform)
continue;
const visPts: Point3d[] = []; for (const pt of shapePts) visPts.push(pt.clone()); // deep copy because we're using a builder transform w/addLineString...
const hidPts: Point3d[] = []; for (const pt of shapePts) hidPts.push(pt.clone());
const arrowVisBuilder = context.createGraphicBuilder(GraphicType.WorldOverlay, transform, this._controlIds[iFace]);
const arrowHidBuilder = context.createGraphicBuilder(GraphicType.WorldDecoration, transform);
const isSelected = this.iModel.selectionSet.has(this._controlIds[iFace]);
let outlineColorOvr = this._controls[iFace].outline;
if (undefined !== outlineColorOvr) {
outlineColorOvr = outlineColorOvr.adjustedForContrast(vp.view.backgroundColor);
outlineColorOvr = outlineColorOvr.withAlpha(outlineColor.getAlpha());
} else {
outlineColorOvr = outlineColor;
}
let fillVisColorOvr = this._controls[iFace].fill;
let fillHidColorOvr = fillHidColor;
let fillSelColorOvr = fillSelColor;
if (undefined !== fillVisColorOvr) {
fillVisColorOvr = fillVisColorOvr.adjustedForContrast(vp.view.backgroundColor);
fillVisColorOvr = fillVisColorOvr.withAlpha(fillVisColor.getAlpha());
fillHidColorOvr = fillVisColorOvr.withAlpha(fillHidColor.getAlpha());
fillSelColorOvr = fillVisColorOvr.inverse().withAlpha(fillSelColor.getAlpha());
} else {
fillVisColorOvr = fillVisColor;
}
arrowVisBuilder.setSymbology(outlineColorOvr, outlineColorOvr, isSelected ? 4 : 2);
arrowVisBuilder.addLineString(visPts);
arrowVisBuilder.setBlankingFill(isSelected ? fillSelColorOvr : fillVisColorOvr);
arrowVisBuilder.addShape(visPts);
context.addDecorationFromBuilder(arrowVisBuilder);
arrowHidBuilder.setSymbology(fillHidColorOvr, fillHidColorOvr, 1);
arrowHidBuilder.addShape(hidPts);
context.addDecorationFromBuilder(arrowHidBuilder);
if (this._controls[iFace].extentValid)
continue;
const warnPixels = 15.0;
const warnOffset = vp.viewingSpace.getPixelSizeAtPoint(anchorRay.origin) * warnPixels * 1.5;
const warnOrigin = anchorRay.origin.plusScaled(anchorRay.direction, -warnOffset);
this.drawExtentTooLargeIndicator(context, warnOrigin, warnPixels);
}
}
public resetViewClip(): boolean {
if (!clearViewClip(this.viewport))
return false;
if (undefined !== this.getModifiedExtents())
this.onChanged.raiseEvent(this.iModel, ProjectLocationChanged.ResetExtents);
return true;
}
public resetGeolocation(): boolean {
if (!this._allowEcefLocationChange)
return false;
if (undefined === this.getModifiedEcefLocation())
return false; // Wasn't changed...
this.iModel.disableGCS(false);
this.iModel.ecefLocation = this._ecefLocation;
this._monumentPoint = this.getMonumentPoint();
this._northDirection = this.getNorthDirection();
updateMapDisplay(this.viewport, false);
this.onChanged.raiseEvent(this.iModel, ProjectLocationChanged.ResetGeolocation);
return true;
}
public updateEcefLocation(origin: Cartographic, point?: Point3d, angle?: Angle): boolean {
if (!this._allowEcefLocationChange)
return false;
const newEcefLocation = EcefLocation.createFromCartographicOrigin(origin, point, (undefined !== angle ? angle : this.getNorthAngle())); // Preserve modified north direction...
const ecefLocation = this.iModel.ecefLocation;
if (undefined !== ecefLocation && ecefLocation.isAlmostEqual(newEcefLocation))
return false;
this.iModel.disableGCS(true); // Map display will ignore change to ecef location when GCS is present...
this.iModel.setEcefLocation(newEcefLocation);
this._monumentPoint = this.getMonumentPoint();
this._northDirection = this.getNorthDirection(undefined !== this._northDirection ? this._northDirection.origin : undefined); // Preserve modified north reference point...
updateMapDisplay(this.viewport, true);
this.onChanged.raiseEvent(this.iModel, ProjectLocationChanged.Geolocation);
return true;
}
public updateNorthDirection(northDir: Ray3d): boolean {
if (!this._allowEcefLocationChange || !this.iModel.isGeoLocated)
return false;
const point = (undefined !== this._monumentPoint ? this._monumentPoint : this.getMonumentPoint()); // Preserve modified monument point...
const origin = this.iModel.spatialToCartographicFromEcef(point);
const saveDirection = this._northDirection;
this._northDirection = northDir; // Change reference point to input location...
const angle = this.getNorthAngle();
if (!this.updateEcefLocation(origin, point, angle)) {
this._northDirection = saveDirection;
return false;
}
return true;
}
public getModifiedEcefLocation(): EcefLocation | undefined {
const ecefLocation = this.iModel.ecefLocation;
if (undefined === ecefLocation)
return undefined; // geolocation wasn't added...
if (undefined === this._ecefLocation)
return ecefLocation; // geolocation didn't exist previously...
if (this._ecefLocation.isAlmostEqual(ecefLocation))
return undefined;
return ecefLocation;
}
public getModifiedExtents(): Range3d | undefined {
if (undefined === this._clipRange)
return undefined;
return this._clipRange.isAlmostEqual(this.iModel.projectExtents) ? undefined : this._clipRange;
}
public static allowEcefLocationChange(requireExisting: boolean, outputError: boolean = true): boolean {
if (undefined === ProjectExtentsClipDecoration._decorator) {
if (outputError)
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("NotActive")));
return false;
} else if (!ProjectExtentsClipDecoration._decorator._allowEcefLocationChange) {
if (outputError)
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("NotAllowed")));
return false;
} else if (requireExisting && !ProjectExtentsClipDecoration._decorator.iModel.isGeoLocated) {
if (outputError)
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("NotGeolocated")));
return false;
}
return true;
}
public fitExtents(): void {
if (undefined === this._clipRange)
return undefined;
const options = { animateFrustumChange: true, animationTime: BeDuration.fromSeconds(2).milliseconds };
const aspect = this.viewport.viewRect.aspect;
this.viewport.view.lookAtVolume(this._clipRange, aspect);
this.viewport.synchWithView(options);
this.viewport.viewCmdTargetCenter = undefined;
}
public static get(): ProjectExtentsClipDecoration | undefined {
if (undefined === ProjectExtentsClipDecoration._decorator)
return undefined;
return ProjectExtentsClipDecoration._decorator;
}
public static show(vp: ScreenViewport, fitExtents: boolean = true): boolean {
if (!vp.view.isSpatialView())
return false;
if (undefined !== ProjectExtentsClipDecoration._decorator) {
const deco = ProjectExtentsClipDecoration._decorator;
if (vp === deco.viewport && undefined !== deco._clipId && undefined !== deco._clip) {
if (deco._clip !== vp.view.getViewClip()) {
clearViewClip(vp);
ViewClipTool.enableClipVolume(vp);
ViewClipTool.setViewClip(vp, deco._clip);
}
if (undefined === deco._removeManipulatorToolListener) {
deco._removeManipulatorToolListener = IModelApp.toolAdmin.manipulatorToolEvent.addListener((tool, event) => deco.onManipulatorToolEvent(tool, event));
deco.start();
deco.onChanged.raiseEvent(deco.iModel, ProjectLocationChanged.Show);
}
return true;
}
ProjectExtentsClipDecoration.clear();
}
if (!clipToProjectExtents(vp))
return false;
ProjectExtentsClipDecoration._decorator = new ProjectExtentsClipDecoration(vp);
if (fitExtents)
ProjectExtentsClipDecoration._decorator.fitExtents();
vp.onChangeView.addOnce(() => this.clear(false, true));
return (undefined !== ProjectExtentsClipDecoration._decorator._clipId);
}
public static hide(): void {
if (undefined === ProjectExtentsClipDecoration._decorator)
return;
const saveClipId = ProjectExtentsClipDecoration._decorator._clipId; // cleared by stop to trigger decorator removal...
ProjectExtentsClipDecoration._decorator.stop();
ProjectExtentsClipDecoration._decorator._clipId = saveClipId;
ProjectExtentsClipDecoration._decorator.onChanged.raiseEvent(ProjectExtentsClipDecoration._decorator.iModel, ProjectLocationChanged.Hide);
}
public static clear(clearClip: boolean = true, resetGeolocation: boolean = true): void {
if (undefined === ProjectExtentsClipDecoration._decorator)
return;
if (clearClip)
ProjectExtentsClipDecoration._decorator.resetViewClip(); // Clear project extents view clip...
if (resetGeolocation)
ProjectExtentsClipDecoration._decorator.resetGeolocation(); // Restore modified geolocation back to create state...
ProjectExtentsClipDecoration._decorator.stop();
ProjectExtentsClipDecoration._decorator = undefined;
}
public static async update(): Promise<void> {
const deco = ProjectExtentsClipDecoration._decorator;
if (undefined === deco)
return;
clipToProjectExtents(deco.viewport);
deco.init();
return deco.updateControls();
}
}
/** Show project location decoration. Project extents represented by view clip.
* @beta
*/
export class ProjectLocationShowTool extends Tool {
public static override toolId = "ProjectLocation.Show";
public override async run(): Promise<boolean> {
const vp = IModelApp.viewManager.selectedView;
if (undefined === vp || !ProjectExtentsClipDecoration.show(vp))
return false;
await IModelApp.toolAdmin.startDefaultTool();
return true;
}
}
/** Hide project location decoration. Preserves changes to project extents view clip and geolocation.
* @beta
*/
export class ProjectLocationHideTool extends Tool {
public static override toolId = "ProjectLocation.Hide";
public override async run(): Promise<boolean> {
ProjectExtentsClipDecoration.hide();
await IModelApp.toolAdmin.startDefaultTool();
return true;
}
}
/** Clear project location decoration. Restore modified geolocation and remove view clip.
* @beta
*/
export class ProjectLocationCancelTool extends Tool {
public static override toolId = "ProjectLocation.Cancel";
public override async run(): Promise<boolean> {
ProjectExtentsClipDecoration.clear();
await IModelApp.toolAdmin.startDefaultTool();
return true;
}
}
/** Save modified project extents and geolocation. Updates decoration to reflect saved state.
* @note Allowing this change to be undone is both problematic and undesirable.
* Warns the user if called with previous changes to cancel restarting the TxnManager session.
* @beta
*/
export class ProjectLocationSaveTool extends Tool {
public static override toolId = "ProjectLocation.Save";
public static callCommand<T extends keyof BasicManipulationCommandIpc>(method: T, ...args: Parameters<BasicManipulationCommandIpc[T]>): ReturnType<BasicManipulationCommandIpc[T]> {
return EditTools.callCommand(method, ...args) as ReturnType<BasicManipulationCommandIpc[T]>;
}
protected async allowRestartTxnSession(iModel: BriefcaseConnection): Promise<boolean> {
if (!await iModel.txns.isUndoPossible())
return true;
// NOTE: Default if openMessageBox isn't implemented is MessageBoxValue.Ok, so we'll check No instead of Yes...
if (MessageBoxValue.No === await IModelApp.notifications.openMessageBox(MessageBoxType.YesNo, translateMessage("RestartTxn"), MessageBoxIconType.Question))
return false;
return true;
}
protected async saveChanges(deco: ProjectExtentsClipDecoration, extents?: Range3dProps, ecefLocation?: EcefLocationProps): Promise<void> {
if (!deco.iModel.isBriefcaseConnection())
return;
if (!await this.allowRestartTxnSession(deco.iModel))
return;
try {
await EditTools.startCommand<string>(editorBuiltInCmdIds.cmdBasicManipulation, deco.iModel.key);
if (undefined !== extents)
await ProjectLocationSaveTool.callCommand("updateProjectExtents", extents);
if (undefined !== ecefLocation)
await ProjectLocationSaveTool.callCommand("updateEcefLocation", ecefLocation);
await deco.iModel.saveChanges(this.toolId);
await deco.iModel.txns.restartTxnSession();
} catch (err) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred."));
}
deco.onChanged.raiseEvent(deco.iModel, ProjectLocationChanged.Save);
await ProjectExtentsClipDecoration.update();
return IModelApp.toolAdmin.startDefaultTool();
}
public override async run(): Promise<boolean> {
const deco = ProjectExtentsClipDecoration.get();
if (undefined === deco) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("NotActive")));
return false;
}
if (deco.iModel.isReadonly) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("Readonly")));
return true;
}
const extents = deco.getModifiedExtents();
const ecefLocation = deco.getModifiedEcefLocation();
if (undefined === extents && undefined === ecefLocation) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, translateMessage("NoChanges")));
return true;
}
await this.saveChanges(deco, extents, ecefLocation);
return true;
}
} | the_stack |
import {assert} from 'chrome://resources/js/assert.m.js';
import {Action} from 'chrome://resources/js/cr/ui/store.js';
import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
import {CurrentWallpaper, WallpaperCollection, WallpaperImage} from '../personalization_app.mojom-webui.js';
import {DisplayableImage} from '../personalization_reducers.js';
/**
* @fileoverview Defines the actions to change wallpaper state.
*/
export enum WallpaperActionName {
BEGIN_LOAD_GOOGLE_PHOTOS_ALBUM = 'begin_load_google_photos_album',
BEGIN_LOAD_GOOGLE_PHOTOS_ALBUMS = 'begin_load_google_photos_albums',
BEGIN_LOAD_GOOGLE_PHOTOS_COUNT = 'begin_load_google_photos_count',
BEGIN_LOAD_GOOGLE_PHOTOS_PHOTOS = 'begin_load_google_photos_photos',
BEGIN_LOAD_IMAGES_FOR_COLLECTIONS = 'begin_load_images_for_collections',
BEGIN_LOAD_LOCAL_IMAGES = 'begin_load_local_images',
BEGIN_LOAD_LOCAL_IMAGE_DATA = 'begin_load_local_image_data',
BEGIN_LOAD_SELECTED_IMAGE = 'begin_load_selected_image',
BEGIN_SELECT_IMAGE = 'begin_select_image',
BEGIN_UPDATE_DAILY_REFRESH_IMAGE = 'begin_update_daily_refresh_image',
END_SELECT_IMAGE = 'end_select_image',
SET_COLLECTIONS = 'set_collections',
SET_DAILY_REFRESH_COLLECTION_ID = 'set_daily_refresh_collection_id',
SET_GOOGLE_PHOTOS_ALBUM = 'set_google_photos_album',
SET_GOOGLE_PHOTOS_ALBUMS = 'set_google_photos_albums',
SET_GOOGLE_PHOTOS_COUNT = 'set_google_photos_count',
SET_GOOGLE_PHOTOS_PHOTOS = 'set_google_photos_photos',
SET_IMAGES_FOR_COLLECTION = 'set_images_for_collection',
SET_LOCAL_IMAGES = 'set_local_images',
SET_LOCAL_IMAGE_DATA = 'set_local_image_data',
SET_SELECTED_IMAGE = 'set_selected_image',
SET_UPDATED_DAILY_REFRESH_IMAGE = 'set_updated_daily_refreshed_image',
SET_FULLSCREEN_ENABLED = 'set_fullscreen_enabled',
}
export type WallpaperActions =
BeginLoadGooglePhotosAlbumAction|BeginLoadGooglePhotosAlbumsAction|
BeginLoadGooglePhotosCountAction|BeginLoadGooglePhotosPhotosAction|
BeginLoadImagesForCollectionsAction|BeginLoadLocalImagesAction|
BeginLoadLocalImageDataAction|BeginUpdateDailyRefreshImageAction|
BeginLoadSelectedImageAction|BeginSelectImageAction|EndSelectImageAction|
SetCollectionsAction|SetDailyRefreshCollectionIdAction|
SetGooglePhotosAlbumAction|SetGooglePhotosAlbumsAction|
SetGooglePhotosCountAction|SetGooglePhotosPhotosAction|
SetImagesForCollectionAction|SetLocalImageDataAction|SetLocalImagesAction|
SetUpdatedDailyRefreshImageAction|SetSelectedImageAction|
SetFullscreenEnabledAction;
export type BeginLoadGooglePhotosAlbumAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUM;
albumId: string;
};
/**
* Notify that the app is loading the list of Google Photos photos for the album
* associated with the specified id.
*/
export function beginLoadGooglePhotosAlbumAction(albumId: string):
BeginLoadGooglePhotosAlbumAction {
return {albumId, name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUM};
}
export type BeginLoadGooglePhotosAlbumsAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUMS;
};
/**
* Notify that the app is loading the list of Google Photos albums.
*/
export function beginLoadGooglePhotosAlbumsAction():
BeginLoadGooglePhotosAlbumsAction {
return {name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_ALBUMS};
}
export type BeginLoadGooglePhotosCountAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_COUNT;
};
/**
* Notify that the app is loading the count of Google Photos photos.
*/
export function beginLoadGooglePhotosCountAction():
BeginLoadGooglePhotosCountAction {
return {name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_COUNT};
}
export type BeginLoadGooglePhotosPhotosAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_PHOTOS;
};
/**
* Notify that the app is loading the list of Google Photos photos.
*/
export function beginLoadGooglePhotosPhotosAction():
BeginLoadGooglePhotosPhotosAction {
return {name: WallpaperActionName.BEGIN_LOAD_GOOGLE_PHOTOS_PHOTOS};
}
export type BeginLoadImagesForCollectionsAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_IMAGES_FOR_COLLECTIONS;
collections: WallpaperCollection[];
};
/**
* Notify that app is loading image list for the given collection.
*/
export function beginLoadImagesForCollectionsAction(
collections: WallpaperCollection[]): BeginLoadImagesForCollectionsAction {
return {
collections,
name: WallpaperActionName.BEGIN_LOAD_IMAGES_FOR_COLLECTIONS,
};
}
export type BeginLoadLocalImagesAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGES;
};
/**
* Notify that app is loading local image list.
*/
export function beginLoadLocalImagesAction(): BeginLoadLocalImagesAction {
return {name: WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGES};
}
export type BeginLoadLocalImageDataAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGE_DATA;
id: string;
};
/**
* Notify that app is loading thumbnail for the given local image.
*/
export function beginLoadLocalImageDataAction(image: FilePath):
BeginLoadLocalImageDataAction {
return {
id: image.path,
name: WallpaperActionName.BEGIN_LOAD_LOCAL_IMAGE_DATA,
};
}
export type BeginUpdateDailyRefreshImageAction = Action&{
name: WallpaperActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE;
};
/**
* Notify that a user has clicked on the refresh button.
*/
export function beginUpdateDailyRefreshImageAction():
BeginUpdateDailyRefreshImageAction {
return {
name: WallpaperActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE,
};
}
export type BeginLoadSelectedImageAction = Action&{
name: WallpaperActionName.BEGIN_LOAD_SELECTED_IMAGE;
};
/**
* Notify that app is loading currently selected image information.
*/
export function beginLoadSelectedImageAction(): BeginLoadSelectedImageAction {
return {name: WallpaperActionName.BEGIN_LOAD_SELECTED_IMAGE};
}
export type BeginSelectImageAction = Action&{
name: WallpaperActionName.BEGIN_SELECT_IMAGE;
image: DisplayableImage;
};
/**
* Notify that a user has clicked on an image to set as wallpaper.
*/
export function beginSelectImageAction(image: DisplayableImage):
BeginSelectImageAction {
return {name: WallpaperActionName.BEGIN_SELECT_IMAGE, image};
}
export type EndSelectImageAction = Action&{
name: WallpaperActionName.END_SELECT_IMAGE;
image: DisplayableImage;
success: boolean;
};
/**
* Notify that the user-initiated action to set image has finished.
*/
export function endSelectImageAction(
image: DisplayableImage, success: boolean): EndSelectImageAction {
return {name: WallpaperActionName.END_SELECT_IMAGE, image, success};
}
export type SetCollectionsAction = Action&{
name: WallpaperActionName.SET_COLLECTIONS;
collections: WallpaperCollection[]|null;
};
/**
* Set the collections. May be called with null if an error occurred.
*/
export function setCollectionsAction(collections: WallpaperCollection[]|
null): SetCollectionsAction {
return {
name: WallpaperActionName.SET_COLLECTIONS,
collections,
};
}
export type SetDailyRefreshCollectionIdAction = Action&{
name: WallpaperActionName.SET_DAILY_REFRESH_COLLECTION_ID;
collectionId: string|null;
};
/**
* Set and enable daily refresh for given collectionId.
*/
export function setDailyRefreshCollectionIdAction(collectionId: string|null):
SetDailyRefreshCollectionIdAction {
return {
collectionId,
name: WallpaperActionName.SET_DAILY_REFRESH_COLLECTION_ID,
};
}
export type SetGooglePhotosAlbumAction = Action&{
name: WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUM;
albumId: string;
photos: unknown[];
};
/**
* Sets the list of Google Photos photos for the album associated with the
* specified id. May be called with null on error.
*/
export function setGooglePhotosAlbumAction(
albumId: string, photos: unknown[]): SetGooglePhotosAlbumAction {
return {albumId, photos, name: WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUM};
}
export type SetGooglePhotosAlbumsAction = Action&{
name: WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUMS;
albums: WallpaperCollection[]|null;
};
/**
* Sets the list of Google Photos albums. May be called with null on error.
*/
export function setGooglePhotosAlbumsAction(albums: WallpaperCollection[]|
null): SetGooglePhotosAlbumsAction {
return {albums, name: WallpaperActionName.SET_GOOGLE_PHOTOS_ALBUMS};
}
export type SetGooglePhotosCountAction = Action&{
name: WallpaperActionName.SET_GOOGLE_PHOTOS_COUNT;
count: number|null;
};
/**
* Sets the count of Google Photos photos. May be called with null on error.
*/
export function setGooglePhotosCountAction(count: number|
null): SetGooglePhotosCountAction {
return {count, name: WallpaperActionName.SET_GOOGLE_PHOTOS_COUNT};
}
export type SetGooglePhotosPhotosAction = Action&{
name: WallpaperActionName.SET_GOOGLE_PHOTOS_PHOTOS;
photos: Url[]|null;
};
/** Sets the list of Google Photos photos. May be called with null on error. */
export function setGooglePhotosPhotosAction(photos: Url[]|
null): SetGooglePhotosPhotosAction {
return {photos, name: WallpaperActionName.SET_GOOGLE_PHOTOS_PHOTOS};
}
export type SetImagesForCollectionAction = Action&{
name: WallpaperActionName.SET_IMAGES_FOR_COLLECTION;
collectionId: string;
images: WallpaperImage[]|null;
};
/**
* Set the images for a given collection. May be called with null if an error
* occurred.
*/
export function setImagesForCollectionAction(
collectionId: string,
images: WallpaperImage[]|null): SetImagesForCollectionAction {
return {
collectionId,
images,
name: WallpaperActionName.SET_IMAGES_FOR_COLLECTION,
};
}
export type SetLocalImageDataAction = Action&{
name: WallpaperActionName.SET_LOCAL_IMAGE_DATA;
id: string;
data: string;
};
/**
* Set the thumbnail data for a local image.
*/
export function setLocalImageDataAction(
filePath: FilePath, data: string): SetLocalImageDataAction {
return {
id: filePath.path,
data,
name: WallpaperActionName.SET_LOCAL_IMAGE_DATA,
};
}
export type SetLocalImagesAction = Action&{
name: WallpaperActionName.SET_LOCAL_IMAGES;
images: FilePath[]|null;
};
/** Set the list of local images. */
export function setLocalImagesAction(images: FilePath[]|
null): SetLocalImagesAction {
return {
images,
name: WallpaperActionName.SET_LOCAL_IMAGES,
};
}
export type SetUpdatedDailyRefreshImageAction = Action&{
name: WallpaperActionName.SET_UPDATED_DAILY_REFRESH_IMAGE;
};
/**
* Notify that a image has been refreshed.
*/
export function setUpdatedDailyRefreshImageAction():
SetUpdatedDailyRefreshImageAction {
return {
name: WallpaperActionName.SET_UPDATED_DAILY_REFRESH_IMAGE,
};
}
export type SetSelectedImageAction = Action&{
name: WallpaperActionName.SET_SELECTED_IMAGE;
image: CurrentWallpaper|null;
};
/**
* Returns an action to set the current image as currently selected across the
* app. Can be called with null to represent no image currently selected or that
* an error occurred.
*/
export function setSelectedImageAction(image: CurrentWallpaper|
null): SetSelectedImageAction {
return {
image,
name: WallpaperActionName.SET_SELECTED_IMAGE,
};
}
export type SetFullscreenEnabledAction = Action&{
name: WallpaperActionName.SET_FULLSCREEN_ENABLED;
enabled: boolean;
};
/**
* Enable/disable the fullscreen preview mode for wallpaper.
*/
export function setFullscreenEnabledAction(enabled: boolean):
SetFullscreenEnabledAction {
assert(typeof enabled === 'boolean');
return {name: WallpaperActionName.SET_FULLSCREEN_ENABLED, enabled};
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Topics } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { EventGridManagementClient } from "../eventGridManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
Topic,
TopicsListBySubscriptionNextOptionalParams,
TopicsListBySubscriptionOptionalParams,
TopicsListByResourceGroupNextOptionalParams,
TopicsListByResourceGroupOptionalParams,
EventType,
TopicsListEventTypesOptionalParams,
TopicsGetOptionalParams,
TopicsGetResponse,
TopicsCreateOrUpdateOptionalParams,
TopicsCreateOrUpdateResponse,
TopicsDeleteOptionalParams,
TopicUpdateParameters,
TopicsUpdateOptionalParams,
TopicsListBySubscriptionResponse,
TopicsListByResourceGroupResponse,
TopicsListSharedAccessKeysOptionalParams,
TopicsListSharedAccessKeysResponse,
TopicRegenerateKeyRequest,
TopicsRegenerateKeyOptionalParams,
TopicsRegenerateKeyResponse,
TopicsListEventTypesResponse,
TopicsListBySubscriptionNextResponse,
TopicsListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Topics operations. */
export class TopicsImpl implements Topics {
private readonly client: EventGridManagementClient;
/**
* Initialize a new instance of the class Topics class.
* @param client Reference to the service client
*/
constructor(client: EventGridManagementClient) {
this.client = client;
}
/**
* List all the topics under an Azure subscription.
* @param options The options parameters.
*/
public listBySubscription(
options?: TopicsListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<Topic> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: TopicsListBySubscriptionOptionalParams
): AsyncIterableIterator<Topic[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: TopicsListBySubscriptionOptionalParams
): AsyncIterableIterator<Topic> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* List all the topics under a resource group.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: TopicsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<Topic> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: TopicsListByResourceGroupOptionalParams
): AsyncIterableIterator<Topic[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: TopicsListByResourceGroupOptionalParams
): AsyncIterableIterator<Topic> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* List event types for a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param providerNamespace Namespace of the provider of the topic.
* @param resourceTypeName Name of the topic type.
* @param resourceName Name of the topic.
* @param options The options parameters.
*/
public listEventTypes(
resourceGroupName: string,
providerNamespace: string,
resourceTypeName: string,
resourceName: string,
options?: TopicsListEventTypesOptionalParams
): PagedAsyncIterableIterator<EventType> {
const iter = this.listEventTypesPagingAll(
resourceGroupName,
providerNamespace,
resourceTypeName,
resourceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listEventTypesPagingPage(
resourceGroupName,
providerNamespace,
resourceTypeName,
resourceName,
options
);
}
};
}
private async *listEventTypesPagingPage(
resourceGroupName: string,
providerNamespace: string,
resourceTypeName: string,
resourceName: string,
options?: TopicsListEventTypesOptionalParams
): AsyncIterableIterator<EventType[]> {
let result = await this._listEventTypes(
resourceGroupName,
providerNamespace,
resourceTypeName,
resourceName,
options
);
yield result.value || [];
}
private async *listEventTypesPagingAll(
resourceGroupName: string,
providerNamespace: string,
resourceTypeName: string,
resourceName: string,
options?: TopicsListEventTypesOptionalParams
): AsyncIterableIterator<EventType> {
for await (const page of this.listEventTypesPagingPage(
resourceGroupName,
providerNamespace,
resourceTypeName,
resourceName,
options
)) {
yield* page;
}
}
/**
* Get properties of a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
topicName: string,
options?: TopicsGetOptionalParams
): Promise<TopicsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, topicName, options },
getOperationSpec
);
}
/**
* Asynchronously creates a new topic with the specified parameters.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param topicInfo Topic information.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
topicName: string,
topicInfo: Topic,
options?: TopicsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<TopicsCreateOrUpdateResponse>,
TopicsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<TopicsCreateOrUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, topicName, topicInfo, options },
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Asynchronously creates a new topic with the specified parameters.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param topicInfo Topic information.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
topicName: string,
topicInfo: Topic,
options?: TopicsCreateOrUpdateOptionalParams
): Promise<TopicsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
topicName,
topicInfo,
options
);
return poller.pollUntilDone();
}
/**
* Delete existing topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
topicName: string,
options?: TopicsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, topicName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Delete existing topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
topicName: string,
options?: TopicsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(
resourceGroupName,
topicName,
options
);
return poller.pollUntilDone();
}
/**
* Asynchronously updates a topic with the specified parameters.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param topicUpdateParameters Topic update information.
* @param options The options parameters.
*/
async beginUpdate(
resourceGroupName: string,
topicName: string,
topicUpdateParameters: TopicUpdateParameters,
options?: TopicsUpdateOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, topicName, topicUpdateParameters, options },
updateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Asynchronously updates a topic with the specified parameters.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param topicUpdateParameters Topic update information.
* @param options The options parameters.
*/
async beginUpdateAndWait(
resourceGroupName: string,
topicName: string,
topicUpdateParameters: TopicUpdateParameters,
options?: TopicsUpdateOptionalParams
): Promise<void> {
const poller = await this.beginUpdate(
resourceGroupName,
topicName,
topicUpdateParameters,
options
);
return poller.pollUntilDone();
}
/**
* List all the topics under an Azure subscription.
* @param options The options parameters.
*/
private _listBySubscription(
options?: TopicsListBySubscriptionOptionalParams
): Promise<TopicsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* List all the topics under a resource group.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: TopicsListByResourceGroupOptionalParams
): Promise<TopicsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* List the two keys used to publish to a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param options The options parameters.
*/
listSharedAccessKeys(
resourceGroupName: string,
topicName: string,
options?: TopicsListSharedAccessKeysOptionalParams
): Promise<TopicsListSharedAccessKeysResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, topicName, options },
listSharedAccessKeysOperationSpec
);
}
/**
* Regenerate a shared access key for a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param regenerateKeyRequest Request body to regenerate key.
* @param options The options parameters.
*/
async beginRegenerateKey(
resourceGroupName: string,
topicName: string,
regenerateKeyRequest: TopicRegenerateKeyRequest,
options?: TopicsRegenerateKeyOptionalParams
): Promise<
PollerLike<
PollOperationState<TopicsRegenerateKeyResponse>,
TopicsRegenerateKeyResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<TopicsRegenerateKeyResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, topicName, regenerateKeyRequest, options },
regenerateKeyOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Regenerate a shared access key for a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param topicName Name of the topic.
* @param regenerateKeyRequest Request body to regenerate key.
* @param options The options parameters.
*/
async beginRegenerateKeyAndWait(
resourceGroupName: string,
topicName: string,
regenerateKeyRequest: TopicRegenerateKeyRequest,
options?: TopicsRegenerateKeyOptionalParams
): Promise<TopicsRegenerateKeyResponse> {
const poller = await this.beginRegenerateKey(
resourceGroupName,
topicName,
regenerateKeyRequest,
options
);
return poller.pollUntilDone();
}
/**
* List event types for a topic.
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param providerNamespace Namespace of the provider of the topic.
* @param resourceTypeName Name of the topic type.
* @param resourceName Name of the topic.
* @param options The options parameters.
*/
private _listEventTypes(
resourceGroupName: string,
providerNamespace: string,
resourceTypeName: string,
resourceName: string,
options?: TopicsListEventTypesOptionalParams
): Promise<TopicsListEventTypesResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
providerNamespace,
resourceTypeName,
resourceName,
options
},
listEventTypesOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: TopicsListBySubscriptionNextOptionalParams
): Promise<TopicsListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group within the user's subscription.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: TopicsListByResourceGroupNextOptionalParams
): Promise<TopicsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Topic
},
default: {}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Topic
},
201: {
bodyMapper: Mappers.Topic
},
202: {
bodyMapper: Mappers.Topic
},
204: {
bodyMapper: Mappers.Topic
},
default: {}
},
requestBody: Parameters.topicInfo,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}",
httpMethod: "DELETE",
responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}",
httpMethod: "PATCH",
responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: {} },
requestBody: Parameters.topicUpdateParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/providers/Microsoft.EventGrid/topics",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.TopicsListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.TopicsListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listSharedAccessKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}/listKeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.TopicSharedAccessKeys
},
default: {}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
headerParameters: [Parameters.accept],
serializer
};
const regenerateKeyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}/regenerateKey",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.TopicSharedAccessKeys
},
201: {
bodyMapper: Mappers.TopicSharedAccessKeys
},
202: {
bodyMapper: Mappers.TopicSharedAccessKeys
},
204: {
bodyMapper: Mappers.TopicSharedAccessKeys
},
default: {}
},
requestBody: Parameters.regenerateKeyRequest1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.topicName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listEventTypesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{providerNamespace}/{resourceTypeName}/{resourceName}/providers/Microsoft.EventGrid/eventTypes",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EventTypesListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.providerNamespace,
Parameters.resourceTypeName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.TopicsListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.TopicsListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion, Parameters.filter, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Provides an AWS EBS Volume Attachment as a top level resource, to attach and
* detach volumes from AWS Instances.
*
* > **NOTE on EBS block devices:** If you use `ebsBlockDevice` on an `aws.ec2.Instance`, this provider will assume management over the full set of non-root EBS block devices for the instance, and treats additional block devices as drift. For this reason, `ebsBlockDevice` cannot be mixed with external `aws.ebs.Volume` + `awsEbsVolumeAttachment` resources for a given instance.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const web = new aws.ec2.Instance("web", {
* ami: "ami-21f78e11",
* availabilityZone: "us-west-2a",
* instanceType: "t2.micro",
* tags: {
* Name: "HelloWorld",
* },
* });
* const example = new aws.ebs.Volume("example", {
* availabilityZone: "us-west-2a",
* size: 1,
* });
* const ebsAtt = new aws.ec2.VolumeAttachment("ebsAtt", {
* deviceName: "/dev/sdh",
* volumeId: example.id,
* instanceId: web.id,
* });
* ```
*
* ## Import
*
* EBS Volume Attachments can be imported using `DEVICE_NAME:VOLUME_ID:INSTANCE_ID`, e.g.
*
* ```sh
* $ pulumi import aws:ec2/volumeAttachment:VolumeAttachment example /dev/sdh:vol-049df61146c4d7901:i-12345678
* ```
*
* [1]https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html#available-ec2-device-names [2]https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/device_naming.html#available-ec2-device-names [3]https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html
*/
export class VolumeAttachment extends pulumi.CustomResource {
/**
* Get an existing VolumeAttachment resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: VolumeAttachmentState, opts?: pulumi.CustomResourceOptions): VolumeAttachment {
return new VolumeAttachment(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:ec2/volumeAttachment:VolumeAttachment';
/**
* Returns true if the given object is an instance of VolumeAttachment. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is VolumeAttachment {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === VolumeAttachment.__pulumiType;
}
/**
* The device name to expose to the instance (for
* example, `/dev/sdh` or `xvdh`). See [Device Naming on Linux Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html#available-ec2-device-names) and [Device Naming on Windows Instances](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/device_naming.html#available-ec2-device-names) for more information.
*/
public readonly deviceName!: pulumi.Output<string>;
/**
* Set to `true` if you want to force the
* volume to detach. Useful if previous attempts failed, but use this option only
* as a last resort, as this can result in **data loss**. See
* [Detaching an Amazon EBS Volume from an Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) for more information.
*/
public readonly forceDetach!: pulumi.Output<boolean | undefined>;
/**
* ID of the Instance to attach to
*/
public readonly instanceId!: pulumi.Output<string>;
/**
* Set this to true if you do not wish
* to detach the volume from the instance to which it is attached at destroy
* time, and instead just remove the attachment from this provider state. This is
* useful when destroying an instance which has volumes created by some other
* means attached.
*/
public readonly skipDestroy!: pulumi.Output<boolean | undefined>;
/**
* Set this to true to ensure that the target instance is stopped
* before trying to detach the volume. Stops the instance, if it is not already stopped.
*/
public readonly stopInstanceBeforeDetaching!: pulumi.Output<boolean | undefined>;
/**
* ID of the Volume to be attached
*/
public readonly volumeId!: pulumi.Output<string>;
/**
* Create a VolumeAttachment resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: VolumeAttachmentArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: VolumeAttachmentArgs | VolumeAttachmentState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as VolumeAttachmentState | undefined;
inputs["deviceName"] = state ? state.deviceName : undefined;
inputs["forceDetach"] = state ? state.forceDetach : undefined;
inputs["instanceId"] = state ? state.instanceId : undefined;
inputs["skipDestroy"] = state ? state.skipDestroy : undefined;
inputs["stopInstanceBeforeDetaching"] = state ? state.stopInstanceBeforeDetaching : undefined;
inputs["volumeId"] = state ? state.volumeId : undefined;
} else {
const args = argsOrState as VolumeAttachmentArgs | undefined;
if ((!args || args.deviceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'deviceName'");
}
if ((!args || args.instanceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'instanceId'");
}
if ((!args || args.volumeId === undefined) && !opts.urn) {
throw new Error("Missing required property 'volumeId'");
}
inputs["deviceName"] = args ? args.deviceName : undefined;
inputs["forceDetach"] = args ? args.forceDetach : undefined;
inputs["instanceId"] = args ? args.instanceId : undefined;
inputs["skipDestroy"] = args ? args.skipDestroy : undefined;
inputs["stopInstanceBeforeDetaching"] = args ? args.stopInstanceBeforeDetaching : undefined;
inputs["volumeId"] = args ? args.volumeId : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(VolumeAttachment.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering VolumeAttachment resources.
*/
export interface VolumeAttachmentState {
/**
* The device name to expose to the instance (for
* example, `/dev/sdh` or `xvdh`). See [Device Naming on Linux Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html#available-ec2-device-names) and [Device Naming on Windows Instances](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/device_naming.html#available-ec2-device-names) for more information.
*/
deviceName?: pulumi.Input<string>;
/**
* Set to `true` if you want to force the
* volume to detach. Useful if previous attempts failed, but use this option only
* as a last resort, as this can result in **data loss**. See
* [Detaching an Amazon EBS Volume from an Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) for more information.
*/
forceDetach?: pulumi.Input<boolean>;
/**
* ID of the Instance to attach to
*/
instanceId?: pulumi.Input<string>;
/**
* Set this to true if you do not wish
* to detach the volume from the instance to which it is attached at destroy
* time, and instead just remove the attachment from this provider state. This is
* useful when destroying an instance which has volumes created by some other
* means attached.
*/
skipDestroy?: pulumi.Input<boolean>;
/**
* Set this to true to ensure that the target instance is stopped
* before trying to detach the volume. Stops the instance, if it is not already stopped.
*/
stopInstanceBeforeDetaching?: pulumi.Input<boolean>;
/**
* ID of the Volume to be attached
*/
volumeId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a VolumeAttachment resource.
*/
export interface VolumeAttachmentArgs {
/**
* The device name to expose to the instance (for
* example, `/dev/sdh` or `xvdh`). See [Device Naming on Linux Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html#available-ec2-device-names) and [Device Naming on Windows Instances](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/device_naming.html#available-ec2-device-names) for more information.
*/
deviceName: pulumi.Input<string>;
/**
* Set to `true` if you want to force the
* volume to detach. Useful if previous attempts failed, but use this option only
* as a last resort, as this can result in **data loss**. See
* [Detaching an Amazon EBS Volume from an Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) for more information.
*/
forceDetach?: pulumi.Input<boolean>;
/**
* ID of the Instance to attach to
*/
instanceId: pulumi.Input<string>;
/**
* Set this to true if you do not wish
* to detach the volume from the instance to which it is attached at destroy
* time, and instead just remove the attachment from this provider state. This is
* useful when destroying an instance which has volumes created by some other
* means attached.
*/
skipDestroy?: pulumi.Input<boolean>;
/**
* Set this to true to ensure that the target instance is stopped
* before trying to detach the volume. Stops the instance, if it is not already stopped.
*/
stopInstanceBeforeDetaching?: pulumi.Input<boolean>;
/**
* ID of the Volume to be attached
*/
volumeId: pulumi.Input<string>;
} | the_stack |
/// <reference path="../core/UIComponent.ts" />
namespace eui {
let UIImpl = sys.UIComponentImpl;
/**
* BitmapLabel is one line or multiline uneditable BitmapText
* @version Egret 2.5.3
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* BitmapLabel 组件是一行或多行不可编辑的位图文本
* @version Egret 2.5.3
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
export class BitmapLabel extends egret.BitmapText implements UIComponent, IDisplayText {
public constructor(text?: string) {
super();
this.initializeUIValues();
this.text = text;
}
/**
* @private
*/
$invalidateContentBounds(): void {
super.$invalidateContentBounds();
this.invalidateSize();
}
/**
* @private
*
* @param value
*/
$setWidth(value: number): boolean {
let result1: boolean = super.$setWidth(value);
let result2: boolean = UIImpl.prototype.$setWidth.call(this, value);
return result1 && result2;
}
/**
* @private
*
* @param value
*/
$setHeight(value: number): boolean {
let result1: boolean = super.$setHeight(value);
let result2: boolean = UIImpl.prototype.$setHeight.call(this, value);
return result1 && result2;
}
/**
* @private
*
* @param value
*/
$setText(value: string): boolean {
let result: boolean = super.$setText(value);
PropertyEvent.dispatchPropertyEvent(this, PropertyEvent.PROPERTY_CHANGE, "text");
return result;
}
private $fontForBitmapLabel: string | egret.BitmapFont;
$setFont(value: any): boolean {
if (this.$fontForBitmapLabel == value) {
return false;
}
this.$fontForBitmapLabel = value;
if (this.$createChildrenCalled) {
this.$parseFont();
} else {
this.$fontChanged = true;
}
this.$fontStringChanged = true;
return true;
}
private $createChildrenCalled: boolean = false;
private $fontChanged: boolean = false;
/**
* 解析source
*/
private $parseFont(): void {
this.$fontChanged = false;
let font = this.$fontForBitmapLabel;
if (typeof font == "string") {
getAssets(font, function (bitmapFont) {
this.$setFontData(bitmapFont, <string>font);
}, this);
} else {
this.$setFontData(font);
}
}
$setFontData(value: egret.BitmapFont, font?: string): boolean {
if (font && font != this.$fontForBitmapLabel) {
return;
}
if (value == this.$font) {
return false;
}
this.$font = value;
this.$invalidateContentBounds();
return true;
}
/**
* @private
*/
private _widthConstraint: number = NaN;
/**
* @private
*/
private _heightConstraint: number = NaN;
//=======================UIComponent接口实现===========================
/**
* @private
* UIComponentImpl 定义的所有变量请不要添加任何初始值,必须统一在此处初始化。
*/
private initializeUIValues: () => void;
/**
* @copy eui.UIComponent#createChildren
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected createChildren(): void {
if (this.$fontChanged) {
this.$parseFont();
}
this.$createChildrenCalled = true;
}
/**
* @copy eui.UIComponent#childrenCreated
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected childrenCreated(): void {
}
/**
* @copy eui.UIComponent#commitProperties
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected commitProperties(): void {
}
/**
* @copy eui.UIComponent#measure
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected measure(): void {
let values = this.$UIComponent;
let oldWidth = this.$textFieldWidth;
let oldHeight = this.$textFieldHeight;
let availableWidth = NaN;
if (!isNaN(this._widthConstraint)) {
availableWidth = this._widthConstraint;
this._widthConstraint = NaN;
}
else if (!isNaN(values[sys.UIKeys.explicitWidth])) {
availableWidth = values[sys.UIKeys.explicitWidth];
}
else if (values[sys.UIKeys.maxWidth] != 100000) {
availableWidth = values[sys.UIKeys.maxWidth];
}
super.$setWidth(availableWidth);
let availableHeight = NaN;
if (!isNaN(this._heightConstraint)) {
availableHeight = this._heightConstraint;
this._heightConstraint = NaN;
}
else if (!isNaN(values[sys.UIKeys.explicitHeight])) {
availableHeight = values[sys.UIKeys.explicitHeight];
}
else if (values[sys.UIKeys.maxHeight] != 100000) {
availableHeight = values[sys.UIKeys.maxHeight];
}
super.$setHeight(availableHeight);
this.setMeasuredSize(this.textWidth, this.textHeight);
super.$setWidth(oldWidth);
super.$setHeight(oldHeight);
}
/**
* @copy eui.UIComponent#updateDisplayList
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected updateDisplayList(unscaledWidth: number, unscaledHeight: number): void {
super.$setWidth(unscaledWidth);
super.$setHeight(unscaledHeight);
}
/**
* @copy eui.UIComponent#invalidateParentLayout
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected invalidateParentLayout(): void {
}
/**
* @private
*/
$UIComponent: Object;
/**
* @private
*/
$includeInLayout: boolean;
/**
* @copy eui.UIComponent#includeInLayout
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public includeInLayout: boolean;
/**
* @copy eui.UIComponent#left
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public left: any;
/**
* @copy eui.UIComponent#right
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public right: any;
/**
* @copy eui.UIComponent#top
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public top: any;
/**
* @copy eui.UIComponent#bottom
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public bottom: any;
/**
* @copy eui.UIComponent#horizontalCenter
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public horizontalCenter: any;
/**
* @copy eui.UIComponent#verticalCenter
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public verticalCenter: any;
/**
* @copy eui.UIComponent#percentWidth
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public percentWidth: number;
/**
* @copy eui.UIComponent#percentHeight
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public percentHeight: number;
/**
* @copy eui.UIComponent#explicitWidth
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public explicitWidth: number;
/**
* @copy eui.UIComponent#explicitHeight
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public explicitHeight: number;
/**
* @copy eui.UIComponent#minWidth
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public minWidth: number;
/**
* @copy eui.UIComponent#maxWidth
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public maxWidth: number;
/**
* @copy eui.UIComponent#minHeight
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public minHeight: number;
/**
* @copy eui.UIComponent#maxHeight
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public maxHeight: number;
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public setMeasuredSize(width: number, height: number): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public invalidateProperties(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public validateProperties(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public invalidateSize(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public validateSize(recursive?: boolean): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public invalidateDisplayList(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public validateDisplayList(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public validateNow(): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public setLayoutBoundsSize(layoutWidth: number, layoutHeight: number): void {
UIImpl.prototype.setLayoutBoundsSize.call(this, layoutWidth, layoutHeight);
if (isNaN(layoutWidth) || layoutWidth === this._widthConstraint || layoutWidth == 0) {
return;
}
let values = this.$UIComponent;
if (!isNaN(values[sys.UIKeys.explicitHeight])) {
return;
}
if (layoutWidth == values[sys.UIKeys.measuredWidth]) {
return;
}
this._widthConstraint = layoutWidth;
this._heightConstraint = layoutHeight;
this.invalidateSize();
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public setLayoutBoundsPosition(x: number, y: number): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public getLayoutBounds(bounds: egret.Rectangle): void {
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public getPreferredBounds(bounds: egret.Rectangle): void {
}
}
sys.implementUIComponent(BitmapLabel, egret.BitmapText);
registerBindable(BitmapLabel.prototype, "text");
} | the_stack |
import snowflake, { Column, Connection, Statement } from 'snowflake-sdk';
import {
BaseDriver, DownloadTableCSVData,
DriverInterface,
GenericDataBaseType,
StreamTableData,
UnloadOptions,
} from '@cubejs-backend/query-orchestrator';
import * as crypto from 'crypto';
import { formatToTimeZone } from 'date-fns-timezone';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { S3, GetObjectCommand } from '@aws-sdk/client-s3';
import { Storage } from '@google-cloud/storage';
import { getEnv } from '@cubejs-backend/shared';
import { HydrationMap, HydrationStream } from './HydrationStream';
// eslint-disable-next-line import/order
const util = require('snowflake-sdk/lib/util');
// TODO Remove when https://github.com/snowflakedb/snowflake-connector-nodejs/pull/158 is resolved
util.construct_hostname = (region: any, account: any) => {
let host;
if (region === 'us-west-2') {
region = null;
}
if (account.indexOf('.') > 0) {
account = account.substring(0, account.indexOf('.'));
}
if (region) {
host = `${account}.${region}.snowflakecomputing.com`;
} else {
host = `${account}.snowflakecomputing.com`;
}
return host;
};
type HydrationConfiguration = {
types: string[], toValue: (column: Column) => ((value: any) => any) | null
};
type UnloadResponse = {
// eslint-disable-next-line camelcase
rows_unloaded: string
};
// It's not possible to declare own map converters by passing config to snowflake-sdk
const hydrators: HydrationConfiguration[] = [
{
types: ['fixed', 'real'],
toValue: (column) => {
if (column.isNullable()) {
return (value) => {
// We use numbers as strings by fetchAsString
if (value === 'NULL') {
return null;
}
return value;
};
}
// Nothing to fix, let's skip this field
return null;
},
},
{
// The TIMESTAMP_* variation associated with TIMESTAMP, default to TIMESTAMP_NTZ
types: [
'date',
// TIMESTAMP_LTZ internally stores UTC time with a specified precision.
'timestamp_ltz',
// TIMESTAMP_NTZ internally stores “wallclock” time with a specified precision.
// All operations are performed without taking any time zone into account.
'timestamp_ntz',
// TIMESTAMP_TZ internally stores UTC time together with an associated time zone offset.
// When a time zone is not provided, the session time zone offset is used.
'timestamp_tz'
],
toValue: () => (value) => {
if (!value) {
return null;
}
return formatToTimeZone(
value,
'YYYY-MM-DDTHH:mm:ss.SSS',
{
timeZone: 'UTC'
}
);
},
}
];
const SnowflakeToGenericType: Record<string, GenericDataBaseType> = {
// It's a limitation for now, because anyway we dont work with JSON objects in Cube Store.
object: 'HLL_SNOWFLAKE',
number: 'decimal',
timestamp_ntz: 'timestamp'
};
// User can create own stage to pass permission restrictions.
interface SnowflakeDriverExportAWS {
bucketType: 's3',
bucketName: string,
keyId: string,
secretKey: string,
region: string,
}
interface SnowflakeDriverExportGCS {
bucketType: 'gcs',
integrationName: string,
bucketName: string,
credentials: object,
}
export type SnowflakeDriverExportBucket = SnowflakeDriverExportAWS | SnowflakeDriverExportGCS;
interface SnowflakeDriverOptions {
account: string,
username: string,
password: string,
region?: string,
warehouse?: string,
role?: string,
clientSessionKeepAlive?: boolean,
database?: string,
authenticator?: string,
privateKeyPath?: string,
privateKeyPass?: string,
resultPrefetch?: number,
exportBucket?: SnowflakeDriverExportBucket,
}
/**
* Attention:
* Snowflake is using UPPER_CASE for table, schema and column names
* Similar to data in response, column_name will be COLUMN_NAME
*/
export class SnowflakeDriver extends BaseDriver implements DriverInterface {
protected connection: Promise<Connection> | null = null;
protected readonly config: SnowflakeDriverOptions;
public constructor(config: Partial<SnowflakeDriverOptions> = {}) {
super();
this.config = {
account: <string>process.env.CUBEJS_DB_SNOWFLAKE_ACCOUNT,
region: process.env.CUBEJS_DB_SNOWFLAKE_REGION,
warehouse: process.env.CUBEJS_DB_SNOWFLAKE_WAREHOUSE,
role: process.env.CUBEJS_DB_SNOWFLAKE_ROLE,
clientSessionKeepAlive: process.env.CUBEJS_DB_SNOWFLAKE_CLIENT_SESSION_KEEP_ALIVE === 'true',
database: process.env.CUBEJS_DB_NAME,
username: <string>process.env.CUBEJS_DB_USER,
password: <string>process.env.CUBEJS_DB_PASS,
authenticator: process.env.CUBEJS_DB_SNOWFLAKE_AUTHENTICATOR,
privateKeyPath: process.env.CUBEJS_DB_SNOWFLAKE_PRIVATE_KEY_PATH,
privateKeyPass: process.env.CUBEJS_DB_SNOWFLAKE_PRIVATE_KEY_PASS,
exportBucket: this.getExportBucket(),
resultPrefetch: 1,
...config
};
}
protected createExportBucket(bucketType: string): SnowflakeDriverExportBucket {
if (bucketType === 's3') {
return {
bucketType,
bucketName: getEnv('dbExportBucket'),
keyId: getEnv('dbExportBucketAwsKey'),
secretKey: getEnv('dbExportBucketAwsSecret'),
region: getEnv('dbExportBucketAwsRegion'),
};
}
if (bucketType === 'gcs') {
return {
bucketType,
bucketName: getEnv('dbExportBucket'),
integrationName: getEnv('dbExportIntegration'),
credentials: getEnv('dbExportGCSCredentials'),
};
}
throw new Error(
`Unsupported EXPORT_BUCKET_TYPE, supported: ${['s3', 'gcs'].join(',')}`
);
}
/**
* @todo Move to BaseDriver in the future?
*/
protected getExportBucket(): SnowflakeDriverExportBucket | undefined {
const bucketType = getEnv('dbExportBucketType', {
supported: ['s3', 'gcs']
});
if (bucketType) {
const exportBucket = this.createExportBucket(
bucketType,
);
const emptyKeys = Object.keys(exportBucket)
.filter((key: string) => exportBucket[<keyof SnowflakeDriverExportBucket>key] === undefined);
if (emptyKeys.length) {
throw new Error(
`Unsupported configuration exportBucket, some configuration keys are empty: ${emptyKeys.join(',')}`
);
}
return exportBucket;
}
return undefined;
}
public static driverEnvVariables() {
return [
'CUBEJS_DB_NAME',
'CUBEJS_DB_USER',
'CUBEJS_DB_PASS',
'CUBEJS_DB_SNOWFLAKE_ACCOUNT',
'CUBEJS_DB_SNOWFLAKE_REGION',
'CUBEJS_DB_SNOWFLAKE_WAREHOUSE',
'CUBEJS_DB_SNOWFLAKE_ROLE',
'CUBEJS_DB_SNOWFLAKE_CLIENT_SESSION_KEEP_ALIVE',
'CUBEJS_DB_SNOWFLAKE_AUTHENTICATOR',
'CUBEJS_DB_SNOWFLAKE_PRIVATE_KEY_PATH',
'CUBEJS_DB_SNOWFLAKE_PRIVATE_KEY_PASS'
];
}
public async testConnection() {
await this.query('SELECT 1 as number');
}
protected async initConnection() {
try {
const connection = snowflake.createConnection(this.config);
await new Promise(
(resolve, reject) => connection.connect((err, conn) => (err ? reject(err) : resolve(conn)))
);
await this.execute(connection, 'ALTER SESSION SET TIMEZONE = \'UTC\'', [], false);
await this.execute(connection, 'ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = 600', [], false);
return connection;
} catch (e) {
this.connection = null;
throw e;
}
}
protected async getConnection(): Promise<Connection> {
if (this.connection) {
const connection = await this.connection;
// Return a connection if not in a fatal state.
if (connection.isUp()) {
return connection;
}
}
// eslint-disable-next-line no-return-assign
return this.connection = this.initConnection();
}
public async query<R = unknown>(query: string, values?: unknown[]): Promise<R> {
return this.getConnection().then((connection) => this.execute<R>(connection, query, values));
}
public async isUnloadSupported() {
if (!this.config.exportBucket) {
return false;
}
return true;
}
public async unload(tableName: string, options: UnloadOptions): Promise<DownloadTableCSVData> {
const connection = await this.getConnection();
if (!this.config.exportBucket) {
throw new Error('Unload is not configured');
}
const { bucketType, bucketName } = this.config.exportBucket;
const exportPathName = crypto.randomBytes(10).toString('hex');
// @link https://docs.snowflake.com/en/sql-reference/sql/copy-into-location.html
const optionsToExport: Record<string, string> = {
HEADER: 'true',
INCLUDE_QUERY_ID: 'true',
// the upper size limit (in bytes) of each file to be generated in parallel per thread
MAX_FILE_SIZE: (options.maxFileSize * 1024 * 1024).toFixed(),
FILE_FORMAT: '(TYPE = CSV, COMPRESSION = GZIP, FIELD_OPTIONALLY_ENCLOSED_BY = \'"\')',
};
let unloadExtractor: () => Promise<DownloadTableCSVData> = async () => {
throw new Error('Unsupported');
};
// eslint-disable-next-line default-case
switch (bucketType) {
case 's3':
{
const { keyId, secretKey, region } = <SnowflakeDriverExportAWS> this.config.exportBucket;
optionsToExport.CREDENTIALS = `(AWS_KEY_ID = '${keyId}' AWS_SECRET_KEY = '${secretKey}')`;
unloadExtractor = () => this.extractFilesFromS3(
new S3({
credentials: {
accessKeyId: keyId,
secretAccessKey: secretKey,
},
region,
}),
bucketName,
exportPathName,
);
}
break;
case 'gcs':
{
const { integrationName, credentials } = <SnowflakeDriverExportGCS> this.config.exportBucket;
optionsToExport.STORAGE_INTEGRATION = `${integrationName}`;
unloadExtractor = () => this.extractFilesFromGCS(
new Storage({
credentials
}),
bucketName,
exportPathName,
);
}
break;
default:
throw new Error(
`Unsupported EXPORT_BUCKET_TYPE, supported: ${['s3', 'gcs'].join(',')}`
);
}
const optionsPart = Object.entries(optionsToExport)
.map(([key, value]) => `${key} = ${value}`)
.join(' ');
const result = await this.execute<UnloadResponse[]>(
connection,
`COPY INTO '${bucketType}://${bucketName}/${exportPathName}/' FROM ${tableName} ${optionsPart}`,
[],
false
);
if (!result) {
throw new Error('Snowflake doesn\'t return anything on UNLOAD operation');
}
if (result[0].rows_unloaded === '0') {
return {
csvFile: [],
};
}
return unloadExtractor();
}
protected async extractFilesFromS3(
storage: S3,
bucketName: string,
exportPathName: string
): Promise<DownloadTableCSVData> {
const list = await storage.listObjectsV2({
Bucket: bucketName,
Prefix: exportPathName,
});
if (list && list.Contents) {
const csvFile = await Promise.all(
list.Contents.map(async (file) => {
const command = new GetObjectCommand({
Bucket: bucketName,
Key: file.Key,
});
return getSignedUrl(storage, command, { expiresIn: 3600 });
})
);
return {
csvFile,
};
}
throw new Error('Unable to UNLOAD table, there are no files in S3 storage');
}
protected async extractFilesFromGCS(
storage: Storage,
bucketName: string,
exportPathName: string
): Promise<DownloadTableCSVData> {
const bucket = storage.bucket(bucketName);
const [files] = await bucket.getFiles({ prefix: `${exportPathName}/` });
if (files.length) {
const csvFile = await Promise.all(files.map(async (file) => {
const [url] = await file.getSignedUrl({
action: 'read',
expires: new Date(new Date().getTime() + 60 * 60 * 1000)
});
return url;
}));
return { csvFile };
}
throw new Error('Unable to UNLOAD table, there are no files in GCS storage');
}
public async stream(
query: string,
values: unknown[],
): Promise<StreamTableData> {
const connection = await this.getConnection();
const stmt = await new Promise<Statement>((resolve, reject) => connection.execute({
sqlText: query,
binds: <string[] | undefined>values,
fetchAsString: [
// It's not possible to store big numbers in Number, It's a common way how to handle it in Cube.js
'Number',
// VARIANT, OBJECT, ARRAY are mapped to JSON type in Snowflake SDK
'JSON'
],
streamResult: true,
complete: (err, statement) => {
if (err) {
reject(err);
return;
}
resolve(statement);
}
}));
const hydrationMap = this.generateHydrationMap(stmt.getColumns());
if (Object.keys(hydrationMap).length) {
const rowStream = new HydrationStream(hydrationMap);
stmt.streamRows().pipe(rowStream);
return {
rowStream,
release: async () => {
//
}
};
}
return {
rowStream: stmt.streamRows(),
release: async () => {
//
}
};
}
protected generateHydrationMap(columns: Column[]): HydrationMap {
const hydrationMap: Record<string, any> = {};
for (const column of columns) {
for (const hydrator of hydrators) {
if (hydrator.types.includes(column.getType())) {
const fnOrNull = hydrator.toValue(column);
if (fnOrNull) {
hydrationMap[column.getName()] = fnOrNull;
}
}
}
}
return hydrationMap;
}
protected async execute<R = unknown>(
connection: Connection,
query: string,
values?: unknown[],
rehydrate: boolean = true
): Promise<R> {
return new Promise((resolve, reject) => connection.execute({
sqlText: query,
binds: <string[] | undefined>values,
fetchAsString: ['Number'],
complete: (err, stmt, rows) => {
if (err) {
reject(err);
return;
}
if (rehydrate && rows?.length) {
const hydrationMap = this.generateHydrationMap(stmt.getColumns());
if (Object.keys(hydrationMap).length) {
for (const row of rows) {
for (const [field, toValue] of Object.entries(hydrationMap)) {
if (row.hasOwnProperty(field)) {
row[field] = toValue(row[field]);
}
}
}
}
}
resolve(<any>rows);
}
}));
}
public informationSchemaQuery() {
return `
SELECT COLUMNS.COLUMN_NAME as "column_name",
COLUMNS.TABLE_NAME as "table_name",
COLUMNS.TABLE_SCHEMA as "table_schema",
COLUMNS.DATA_TYPE as "data_type"
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNS.TABLE_SCHEMA NOT IN ('INFORMATION_SCHEMA')
`;
}
public async release(): Promise<void> {
if (this.connection) {
this.connection.then((connection) => new Promise<void>(
(resolve, reject) => connection.destroy((err) => (err ? reject(err) : resolve()))
));
}
}
public toGenericType(columnType: string) {
return SnowflakeToGenericType[columnType.toLowerCase()] || super.toGenericType(columnType);
}
public async tableColumnTypes(table: string) {
const [schema, name] = table.split('.');
const columns = await this.query<{ COLUMN_NAME: string, DATA_TYPE: string }[]>(
`SELECT COLUMNS.COLUMN_NAME,
COLUMNS.DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ${this.param(0)} AND TABLE_SCHEMA = ${this.param(1)}
ORDER BY ORDINAL_POSITION`,
[name.toUpperCase(), schema.toUpperCase()]
);
return columns.map(c => ({ name: c.COLUMN_NAME, type: this.toGenericType(c.DATA_TYPE) }));
}
public async getTablesQuery(schemaName: string) {
const tables = await super.getTablesQuery(schemaName.toUpperCase());
return tables.map(t => ({ table_name: t.TABLE_NAME && t.TABLE_NAME.toLowerCase() }));
}
} | the_stack |
import { TranslationSectionDefinition } from "@/types";
const SECTIONS: TranslationSectionDefinition[] = [{
title: "Common - Ranked Tiers",
description: "The names of the 10 different ranked tiers, used in various places.",
// <editor-fold defaultstate="collapsed" desc="Common - Ranked Tiers">
keyGroups: [{
keys: [
"ranked_tier_unranked",
"ranked_tier_iron",
"ranked_tier_bronze",
"ranked_tier_silver",
"ranked_tier_gold",
"ranked_tier_platinum",
"ranked_tier_diamond",
"ranked_tier_master",
"ranked_tier_grandmaster",
"ranked_tier_challenger"
],
embed: 0
}],
embeds: [{
"header": "Example",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T13:09:42.238Z",
"title": [
{
"name": "command_roles_message_title",
"args": null
}
],
"description": [
{
"name": "command_roles_message_description",
"args": null
}
],
"fields": [
{
"name": [
"Challenger"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_challenger",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Grandmaster"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_grandmaster",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Master"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_master",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Diamond"
],
"value": [
"✅ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_diamond",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Platinum"
],
"value": [
"✅ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_platinum",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Silver"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_silver",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Bronze"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_bronze",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Iron"
],
"value": [
"✅ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_iron",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Unranked"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_unranked",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
}
]
}]
// </editor-fold>
}, {
title: "Common - Ranked Queues",
description: "The names of the various ranked queues that Orianna has assigning capabilities for.",
// <editor-fold defaultstate="collapsed" desc="Common - Ranked Queues">
keyGroups: [{
keys: [
"queue_ranked_solo",
"queue_ranked_flex",
"queue_ranked_tft",
"queue_ranked_any",
"queue_ranked_highest",
"queue_ranked_highest_tft"
],
embed: 0
}],
embeds: [{
"header": "Example",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T13:27:21.452Z",
"title": [
{
"name": "command_roles_message_title",
"args": null
}
],
"description": [
{
"name": "command_roles_message_description",
"args": null
}
],
"fields": [
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_highest_tft",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_highest",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_any",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_tft",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_flex",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_solo",
"args": null
}
]
}
}
]
}
}
]
}
]
}]
// </editor-fold>
}, {
title: "Common - Time Ago",
description: "How to describe something that happened a while ago.",
// <editor-fold defaultstate="collapsed" desc="Common - Time Ago">
keyGroups: [{
keys: [
"time_ago_today",
"time_ago_yesterday",
"time_ago_days_ago"
],
embed: 0
}],
embeds: [{
"header": "Example",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T13:33:57.786Z",
"title": [
{
"name": "command_profile_title",
"args": {
"name": [
"molenzwiebel <a:Bot_Owner:468045368517722153>"
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_profile_top_champions",
"args": null
}
],
"value": [
"<:Syndra:411977428227850241> ", { champion: "Syndra" }, " - **790k**\n<:Soraka:411977195506892802> ", { champion: "Soraka" }, " - **220k**\n<:Xayah:411977428718714900> ", { champion: "Xayah" }, " - **130k**"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_statistics",
"args": null
}
],
"value": [
"5x<:Level_7:411977489707958282> 6x<:Level_6:411977489351704587> 16x<:Level_5:411977803144364032><:__:447420442819690506>\n",
{
"name": "command_profile_statistics_total_points",
"args": {
"amount": 2790473
}
},
"<:__:447420442819690506>\n",
{
"name": "command_profile_statistics_avg_champ",
"args": {
"amount": [
"20,368.42"
]
}
},
"<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_recently_played",
"args": null
}
],
"value": [
"<:Amumu:411977195532189708> ", { champion: "Amumu" }, " - **",
{
"name": "time_ago_today",
"args": null
},
"**\n<:Diana:411977428311736340> ", { champion: "Diana" }, " - **",
{
"name": "time_ago_yesterday",
"args": null
},
"**\n<:Leona:411977323806720011> ", { champion: "Leona" }, " - **",
{
"name": "time_ago_days_ago",
"args": {
"days": 2
}
},
"**"
],
"inline": true
}
]
}]
// </editor-fold>
}, {
title: "Common - Misc",
description: "Miscellaneous strings that didn't really fit anywhere else.",
// <editor-fold defaultstate="collapsed" desc="Common - Misc">
keyGroups: [{
keys: ["command_page_n_of_n"],
embed: 0
}, {
keys: [
"command_other_bot_title",
"command_other_bot_description"
],
embed: 1
}],
embeds: [{
"header": "Example",
"color": 4832538,
"timestamp": "2019-12-15T14:31:10.377Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 10
}
},
" • molenzwiebel 👑"
]
}
}, {
"header": "Example: User tries to assign Orianna role with a different bot.",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:11:49.928Z",
"title": [
{
"name": "command_other_bot_title",
"args": null
}
],
"description": [
{
"name": "command_other_bot_description",
"args": {
"role": [
"Gold"
]
}
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command Errors",
description: "Various errors that can happen during command execution, such as a user forgetting to specify a champion or the command failing entirely.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command Errors">
keyGroups: [{
keys: [
"command_error_title",
"command_error_description"
],
embed: 0
}, {
keys: [
"command_error_no_accounts",
"command_error_no_accounts_description",
],
embed: 1,
}, {
keys: [
"command_error_no_permissions",
"command_error_no_permissions_description",
],
embed: 2,
}, {
keys: [
"command_error_no_champion",
"command_error_no_champion_description",
],
embed: 3,
}, {
keys: ["command_muted_preamble"]
}],
embeds: [{
"header": "Example: Generic Error",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:05:14.053Z",
"title": [
{
"name": "command_error_title",
"args": null
}
],
"description": [
{
"name": "command_error_description",
"args": null
}
]
}, {
"header": "Example: No Accounts",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:05:14.053Z",
"title": [
{
"name": "command_error_no_accounts",
"args": {
"user": [
"molenzwiebel <a:Bot_Owner:468045368517722153>"
]
}
}
],
"description": [
{
"name": "command_error_no_accounts_description",
"args": null
}
]
}, {
"header": "Example: No Permissions",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:05:14.053Z",
"title": [
{
"name": "command_error_no_permissions",
"args": null
}
],
"description": [
{
"name": "command_error_no_permissions_description",
"args": null
}
]
}, {
"header": "Example: No Champion",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:05:14.053Z",
"title": [
{
"name": "command_error_no_champion",
"args": null
}
],
"description": [
{
"name": "command_error_no_champion_description",
"args": null
}
]
}]
// </editor-fold>
}, {
title: "Discord - Engagement",
description: "The various messages that are sent when a user first interacts with Orianna. Note that there are multiple starting paragraphs based on how the user first interacted with Orianna.",
// <editor-fold defaultstate="collapsed" desc="Discord - Engagement">
keyGroups: [{
keys: [
"first_use_title",
"first_use_intro_on_command",
"first_use_message"
],
embed: 0
}, {
keys: [
"first_use_intro_on_join",
],
embed: 1,
}, {
keys: [
"first_use_intro_on_react",
],
embed: 2
}],
embeds: [{
"header": "Example: Full Message",
"color": 4832538,
"footer": {
"text": [
"Orianna Bot v2"
]
},
"timestamp": "2019-12-15T13:39:38.637Z",
"title": [
{
"name": "first_use_title",
"args": {
"username": [
"molenzwiebel"
]
}
}
],
"description": [
{
"name": "first_use_message",
"args": {
"intro": [
{
"name": "first_use_intro_on_command",
"args": null
}
],
"link": [
"https://orianna.molenzwiebel.xyz/login/fc5bb491e0cca00713403311ba1f5e0a"
]
}
}
],
"thumbnail": {
"url": "https://ddragon.leagueoflegends.com/cdn/7.7.1/img/champion/Orianna.png"
}
}, {
"header": "Example: On Join Message",
"color": 4832538,
"footer": {
"text": [
"Orianna Bot v2"
]
},
"timestamp": "2019-12-15T13:39:38.637Z",
"title": [
{
"name": "first_use_title",
"args": {
"username": [
"molenzwiebel"
]
}
}
],
"description": [
{
"name": "first_use_intro_on_join",
"args": {
"server": [
"Orianna Mains"
]
}
},
"\n\n_..._"
],
"thumbnail": {
"url": "https://ddragon.leagueoflegends.com/cdn/7.7.1/img/champion/Orianna.png"
}
}, {
"header": "Example: On React Message",
"color": 4832538,
"footer": {
"text": [
"Orianna Bot v2"
]
},
"timestamp": "2019-12-15T13:39:38.637Z",
"title": [
{
"name": "first_use_title",
"args": {
"username": [
"molenzwiebel"
]
}
}
],
"description": [
{
"name": "first_use_intro_on_react",
"args": {
"server": [
"Orianna Mains"
]
}
},
"\n\n_..._"
],
"thumbnail": {
"url": "https://ddragon.leagueoflegends.com/cdn/7.7.1/img/champion/Orianna.png"
}
}]
// </editor-fold>
}, {
title: "Discord - Updating",
description: "The various messages that happen when Orianna updates the stats for a user. This is mostly people transferring or when they get promoted to a role.",
// <editor-fold defaultstate="collapsed" desc="Discord - Updating">
keyGroups: [{
keys: [
"transfer_title",
"transfer_body"
],
embed: 0
}, {
keys: [
"promotion_title"
],
embed: 1
}],
embeds: [{
"header": "Example: Account Transfer",
"color": 693982,
"title": [
{
"name": "transfer_title",
"args": null
}
],
"description": [
{
"name": "transfer_body",
"args": {
"username": [
"Doublelift"
],
"region": [
"NA"
]
}
}
]
}, {
"header": "Example: User Promotion",
"color": 4832538,
"timestamp": "2019-12-15T14:31:10.377Z",
"author": {
"name": [
{
"name": "promotion_title",
"args": {
"username": [
"molenzwiebel 👑"
],
"role": [
"Archmage (700k)"
]
}
}
],
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif"
},
"image": {
"url": "https://media.discordapp.net/attachments/186908309989752832/625086113157218304/promotion.gif?format=png&width=400&height=110",
"width": 400,
"height": 110
}
}]
// </editor-fold>
}, {
title: "Discord - Command - About",
description: "All the strings used in the about command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - About">
keyGroups: [{
keys: [
"command_about_title",
"command_about_field_author",
"command_about_field_version",
"command_about_field_source",
"command_about_field_servers",
"command_about_field_channels",
"command_about_field_users",
"command_about_field_memory_usage",
"command_about_field_support",
"command_about_field_vote"
],
embed: 0
}],
embeds: [{
"header": "Example",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:46:30.233Z",
"title": [
{
"name": "command_about_title",
"args": null
}
],
"fields": [
{
"name": [
{
"name": "command_about_field_author",
"args": null
}
],
"value": [
"molenzwiebel#2773 (EUW - Yahoo Answers)"
]
},
{
"name": [
{
"name": "command_about_field_version",
"args": null
}
],
"value": [
"[9b33707 - [trans] Lots of progress](https://github.com/molenzwiebel/OriannaBot/commit/9b33707887f31a3d62ac989a91f17af50118ad95)"
]
},
{
"name": [
{
"name": "command_about_field_source",
"args": null
}
],
"value": [
"[Orianna Bot on Github](https://github.com/molenzwiebel/oriannabot)"
]
},
{
"name": [
{
"name": "command_about_field_servers",
"args": null
}
],
"value": [
"9,999"
],
"inline": true
},
{
"name": [
{
"name": "command_about_field_channels",
"args": null
}
],
"value": [
"231,703"
],
"inline": true
},
{
"name": [
{
"name": "command_about_field_users",
"args": null
}
],
"value": [
"1,309,265"
],
"inline": true
},
{
"name": [
{
"name": "command_about_field_memory_usage",
"args": null
}
],
"value": [
"1556.11 MB"
],
"inline": true
},
{
"name": [
{
"name": "command_about_field_support",
"args": null
}
],
"value": [
"[discord.gg/bfxdsRC](https://discord.gg/bfxdsRC)"
],
"inline": true
},
{
"name": [
{
"name": "command_about_field_vote",
"args": null
}
],
"value": [
"[discordbots.org](https://discordbots.org/bot/244234418007441408)"
],
"inline": true
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Edit",
description: "All the strings used in the edit command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Edit">
keyGroups: [{
keys: [
"command_edit_small_description",
"command_edit_description"
],
embed: 0
}, {
keys: [
"command_edit_server_title",
"command_edit_server_description"
],
embed: 1
}, {
keys: [
"command_edit_dm_title",
"command_edit_dm_description"
],
embed: 2
}, {
keys: [
"command_edit_dm_failed_title",
"command_edit_dm_failed_description"
],
embed: 3
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:52:28.712Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Edit Profile"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_edit_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`edit`, `config`, `configure`, `add`, `remove`"
]
}
]
}, {
"header": "Example: Edit Server",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:53:10.607Z",
"title": [
{
"name": "command_edit_server_title",
"args": null
}
],
"description": [
{
"name": "command_edit_server_description",
"args": null
}
]
}, {
"header": "Example: DM with edit link",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:53:41.102Z",
"title": [
{
"name": "command_edit_dm_title",
"args": null
}
],
"description": [
{
"name": "command_edit_dm_description",
"args": {
"link": [
"https://orianna.molenzwiebel.xyz/login/f337890fd339fd978ff1d2957f6b2095"
]
}
}
]
}, {
"header": "Example: DM failed",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T14:54:51.837Z",
"title": [
{
"name": "command_edit_dm_failed_title",
"args": null
}
],
"description": [
{
"name": "command_edit_dm_failed_description",
"args": null
}
],
"image": {
"url": "https://i.imgur.com/qLgkXiv.png",
"width": 400,
"height": 109
}
}]
// </editor-fold>
}, {
title: "Discord - Command - Help",
description: "All the strings used in the help command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Help">
keyGroups: [{
keys: [
"command_help_title",
"command_help_description"
],
embed: 0
}, {
keys: [
"command_help_command_title",
"command_help_command_description",
"command_help_command_keywords"
],
embed: 1
}],
embeds: [{
"header": "Example: Help Overview",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:06:55.199Z",
"title": [
{
"name": "command_help_title",
"args": null
}
],
"description": [
{
"name": "command_help_description",
"args": null
}
],
"fields": [
{
"name": [
"1 - Edit Profile"
],
"value": [
{
"name": "command_edit_small_description",
"args": null
}
]
},
{
"name": [
"2 - Refresh"
],
"value": [
{
"name": "command_refresh_small_description",
"args": null
}
]
}
]
}, {
"header": "Example: Help For Command",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:07:36.420Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Edit Profile"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_edit_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`edit`, `config`, `configure`, `add`, `remove`"
]
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Invite",
description: "All the strings used in the invite command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Invite">
keyGroups: [{
keys: [
"command_invite_title",
"command_invite_message_description"
],
embed: 0
}],
embeds: [{
"header": "Example: DM with invite link",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:09:58.309Z",
"title": [
{
"name": "command_invite_title",
"args": null
}
],
"description": [
{
"name": "command_invite_message_description",
"args": {
"link": [
"https://orianna.molenzwiebel.xyz/api/v1/discord-invite"
]
}
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Points",
description: "All the strings used in the points command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Points">
keyGroups: [{
keys: [
"command_points_small_description",
"command_points_description"
],
embed: 0
}, {
keys: [
"command_points_message_title",
"command_points_message_description"
],
embed: 1
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:14:06.272Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Show Mastery Points"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_points_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`points`, `mastery`, `score`"
]
}
]
}, {
"header": "Example: Command Response",
"color": 4832538,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T15:14:42.158Z",
"title": [
{
"name": "command_points_message_title",
"args": null
}
],
"description": [
{
"name": "command_points_message_description",
"args": {
"user": [
"<@!86540964021161984> <a:Bot_Owner:468045368517722153>"
],
"points": [
"<:Level_7:411977489707958282> 787,562"
],
"champion": [
"<:Syndra:411977428227850241> ", { champion: "Syndra" }
]
}
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Profile",
description: "All the strings used in the profile command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Profile">
keyGroups: [{
keys: [
"command_profile_small_description",
"command_profile_description"
],
embed: 0
}, {
keys: [
"command_profile_title",
"command_profile_top_champions",
"command_profile_statistics",
"command_profile_statistics_total_points",
"command_profile_statistics_avg_champ",
"command_profile_recently_played",
"command_profile_ranked_tiers",
"command_profile_account"
],
embed: 1
}, {
keys: [
"command_profile_recently_played_no_games",
"command_profile_accounts"
],
embed: 2
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:30:16.152Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Show User Profile"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_profile_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`list`, `accounts`, `name`, `show`, `profile`, `account`, `summoner`"
]
}
]
}, {
"header": "Example: Profile with a single account and games played.",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:30:55.953Z",
"title": [
{
"name": "command_profile_title",
"args": {
"name": [
"molenzwiebel <a:Bot_Owner:468045368517722153>"
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_profile_top_champions",
"args": null
}
],
"value": [
"<:Syndra:411977428227850241> ", { champion: "Syndra" }, " - **790k**\n<:Soraka:411977195506892802> ", { champion: "Soraka" }, " - **220k**\n<:Xayah:411977428718714900> ", { champion: "Xayah" }, " - **130k**"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_statistics",
"args": null
}
],
"value": [
"5x<:Level_7:411977489707958282> 6x<:Level_6:411977489351704587> 16x<:Level_5:411977803144364032><:__:447420442819690506>\n",
{
"name": "command_profile_statistics_total_points",
"args": {
"amount": 2790473
}
},
"<:__:447420442819690506>\n",
{
"name": "command_profile_statistics_avg_champ",
"args": {
"amount": [
"20,368.42"
]
}
},
"<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_recently_played",
"args": null
}
],
"value": [
"<:Amumu:411977195532189708> ", { champion: "Amumu" }, " - **",
{
"name": "time_ago_today",
"args": null
},
"**\n<:Diana:411977428311736340> ", { champion: "Diana" }, " - **",
{
"name": "time_ago_yesterday",
"args": null
},
"**\n<:Leona:411977323806720011> ", { champion: "Leona" }, " - **",
{
"name": "time_ago_days_ago",
"args": {
"days": 2
}
},
"**"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_ranked_tiers",
"args": null
}
],
"value": [
{
"name": "queue_ranked_solo",
"args": null
},
": **<:Platinum:519953533500391445> ",
{
"name": "ranked_tier_platinum",
"args": null
},
"**\n",
{
"name": "queue_ranked_flex",
"args": null
},
": **<:Diamond:519953533769089044> ",
{
"name": "ranked_tier_diamond",
"args": null
},
"**\n",
{
"name": "queue_ranked_tft",
"args": null
},
": **<:Iron:519953534356160532> ",
{
"name": "ranked_tier_iron",
"args": null
},
"**\n<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_account",
"args": null
}
],
"value": [
"EUW - Yahoo Answers\n<:__:447420442819690506>"
],
"inline": true
}
]
}, {
"header": "Example: Multiple accounts, no recent games",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:33:02.744Z",
"title": [
{
"name": "command_profile_title",
"args": {
"name": [
"molenzwiebel <a:Bot_Owner:468045368517722153>"
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_profile_top_champions",
"args": null
}
],
"value": [
"<:Syndra:411977428227850241> ", { champion: "Syndra" }, " - **790k**\n<:Soraka:411977195506892802> ", { champion: "Soraka" }, " - **220k**\n<:Xayah:411977428718714900> ", { champion: "Xayah" }, " - **130k**"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_statistics",
"args": null
}
],
"value": [
"5x<:Level_7:411977489707958282> 6x<:Level_6:411977489351704587> 16x<:Level_5:411977803144364032><:__:447420442819690506>\n",
{
"name": "command_profile_statistics_total_points",
"args": {
"amount": 2790473
}
},
"<:__:447420442819690506>\n",
{
"name": "command_profile_statistics_avg_champ",
"args": {
"amount": [
"20,368.42"
]
}
},
"<:__:447420442819690506>\n<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_recently_played",
"args": null
}
],
"value": [
{
"name": "command_profile_recently_played_no_games",
"args": null
},
"\n<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_profile_ranked_tiers",
"args": null
}
],
"value": [
{
"name": "queue_ranked_solo",
"args": null
},
": **<:Platinum:519953533500391445> ",
{
"name": "ranked_tier_platinum",
"args": null
},
"**\n",
{
"name": "queue_ranked_flex",
"args": null
},
": **<:Diamond:519953533769089044> ",
{
"name": "ranked_tier_diamond",
"args": null
},
"**\n",
{
"name": "queue_ranked_tft",
"args": null
},
": **<:Iron:519953534356160532> ",
{
"name": "ranked_tier_iron",
"args": null
},
"**\n<:__:447420442819690506>"
],
"inline": false
},
{
"name": [
{
"name": "command_profile_accounts",
"args": null
}
],
"value": [
"EUW - Test\n<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
""
],
"value": [
"EUW - Yahoo Answers\n<:__:447420442819690506>"
],
"inline": true
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Refresh",
description: "The help text for the refresh command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Refresh">
keyGroups: [{
keys: [
"command_refresh_small_description",
"command_refresh_description"
],
embed: 0
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:38:29.544Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Refresh"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_refresh_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`refresh`, `reload`, `update`, `recalculate`"
]
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Roles",
description: "All the strings used in the roles command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Roles">
keyGroups: [{
keys: [
"command_roles_small_description",
"command_roles_description"
],
embed: 0
}, {
keys: [
"command_roles_no_server_title",
"command_roles_no_server_description"
],
embed: 1
}, {
keys: [
"command_roles_no_roles_title",
"command_roles_no_roles_description"
],
embed: 2
}, {
keys: [
"command_roles_at_least",
"command_roles_at_most",
"command_roles_exactly",
"command_roles_between",
"command_roles_ranked_tier_equal",
"command_roles_ranked_tier_lower",
"command_roles_ranked_tier_higher"
],
embed: 3
}, {
keys: [
"command_roles_mastery_level",
"command_roles_total_mastery_level",
"command_roles_mastery_score",
"command_roles_total_mastery_score",
"command_roles_ranked_tier",
"command_roles_region"
],
embed: 4
}, {
keys: [
"command_roles_message_title",
"command_roles_message_description",
"command_roles_all_match",
"command_roles_any_match",
"command_roles_at_least_n",
"command_roles_no_conditions",
"command_roles_continued"
],
embed: 5
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:45:29.535Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Show Server Roles"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_roles_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`roles`, `config`, `ranks`"
]
}
]
}, {
"header": "Example: Command used in DMs.",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:47:30.618Z",
"title": [
{
"name": "command_roles_no_server_title",
"args": null
}
],
"description": [
{
"name": "command_roles_no_server_description",
"args": null
}
]
}, {
"header": "Example: Command used in a server without roles.",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T17:47:30.618Z",
"title": [
{
"name": "command_roles_no_roles_title",
"args": null
}
],
"description": [
{
"name": "command_roles_no_roles_description",
"args": null
}
]
}, {
"header": "Example: Ranges",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T18:04:48.011Z",
"title": [
{
"name": "command_roles_message_title",
"args": null
}
],
"description": [
{
"name": "command_roles_message_description",
"args": null
}
],
"fields": [
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_score",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_score",
"args": {
"range": [
{
"name": "command_roles_at_most",
"args": {
"value": 1000000
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_score",
"args": {
"range": [
{
"name": "command_roles_between",
"args": {
"min": 10000,
"max": 25000
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_score",
"args": {
"range": [
{
"name": "command_roles_exactly",
"args": {
"value": 123456
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_higher",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_solo",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_lower",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_solo",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_solo",
"args": null
}
]
}
}
]
}
}
]
}
]
}, {
"header": "Example: Conditions",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T18:12:39.736Z",
"title": [
{
"name": "command_roles_message_title",
"args": null
}
],
"description": [
{
"name": "command_roles_message_description",
"args": null
}
],
"fields": [
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_mastery_level",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1
}
}
],
"champion": [
"<:Aatrox:469632168130379798> ", { champion: "Aatrox" }
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_mastery_score",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1000000
}
}
],
"champion": [
"<:Aatrox:469632168130379798> ", { champion: "Aatrox" }
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_level",
"args": {
"range": [
{
"name": "command_roles_exactly",
"args": {
"value": 100
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_total_mastery_score",
"args": {
"range": [
{
"name": "command_roles_exactly",
"args": {
"value": 123456
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_ranked_tier",
"args": {
"ranked": [
{
"name": "command_roles_ranked_tier_equal",
"args": {
"tier": [
{
"name": "ranked_tier_gold",
"args": null
}
],
"queue": [
{
"name": "queue_ranked_solo",
"args": null
}
]
}
}
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
"❌ ",
{
"name": "command_roles_region",
"args": {
"region": [
"EUW"
]
}
}
]
}
]
}, {
"header": "Example: Title and message formatting.",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T18:12:39.736Z",
"title": [
{
"name": "command_roles_message_title",
"args": null
}
],
"description": [
{
"name": "command_roles_message_description",
"args": null
}
],
"fields": [
{
"name": [
"Gold ",
{ "name": "command_roles_continued", "args": null }
],
"value": [
{ "name": "command_roles_all_match", "args": null },
"\n❌ ",
{
"name": "command_roles_mastery_level",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1
}
}
],
"champion": [
"<:Aatrox:469632168130379798> ", { champion: "Aatrox" }
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
{ "name": "command_roles_any_match", "args": null },
"\n❌ ",
{
"name": "command_roles_mastery_level",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1
}
}
],
"champion": [
"<:Aatrox:469632168130379798> ", { champion: "Aatrox" }
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
{ "name": "command_roles_at_least_n", "args": { "amount": 2 } },
"\n❌ ",
{
"name": "command_roles_mastery_level",
"args": {
"range": [
{
"name": "command_roles_at_least",
"args": {
"value": 1
}
}
],
"champion": [
"<:Aatrox:469632168130379798> ", { champion: "Aatrox" }
]
}
}
]
},
{
"name": [
"Gold"
],
"value": [
{ "name": "command_roles_no_conditions", "args": null }
]
}
]
}]
// </editor-fold>
}, {
title: "Discord - Command - Stats",
description: "All the strings used in the stats command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Stats">
keyGroups: [{
keys: [
"command_stats_small_description",
"command_stats_description"
],
embed: 0
}, {
keys: [
"command_stats_no_values_title",
"command_stats_no_values_description"
],
embed: 1
}, {
keys: [
"command_stats_message_title",
"command_stats_message_data",
"command_stats_message_data_value",
"command_stats_message_games",
"command_stats_message_games_value"
],
embed: 2
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T18:23:21.259Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Show Stats"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_stats_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`stats`, `graph`, `chart`, `progression`, `progress`"
]
}
]
}, {
"header": "Example: No Stats Recorded",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-17T20:06:40.410Z",
"title": [
{
"name": "command_stats_no_values_title",
"args": null
}
],
"description": [
{
"name": "command_stats_no_values_description",
"args": {
"user": [
"<@!86540964021161984> <a:Bot_Owner:468045368517722153>"
],
"champion": [
{ champion: "Syndra" }
]
}
}
]
}, {
"header": "Example: Plenty of Stats",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-17T20:12:40.420Z",
"title": [
{
"name": "command_stats_message_title",
"args": {
"name": [
"molenzwiebel"
],
"champion": [
{ champion: "Velkoz" }
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_stats_message_data",
"args": null
}
],
"value": [
{
"name": "command_stats_message_data_value",
"args": {
"numGames": 150,
"firstGameDate": [
"2017-06-27"
],
"lastGameDate": [
"2019-04-25"
]
}
},
"<:__:447420442819690506>"
],
"inline": true
},
{
"name": [
{
"name": "command_stats_message_games",
"args": null
}
],
"value": [
{
"name": "command_stats_message_games_value",
"args": {
"win": 74,
"loss": 76,
"winrate": [
"49.33"
]
}
},
"<:__:447420442819690506>"
],
"inline": true
}
],
"thumbnail": {
"url": "https://ddragon.leagueoflegends.com/cdn/9.24.2/img/champion/Velkoz.png"
},
"image": {
"url": "https://cdn.discordapp.com/attachments/460933300769259521/656604703265652736/chart.png",
"width": 399,
"height": 250
}
}]
// </editor-fold>
}, {
title: "Discord - Command - Leaderboard",
description: "All the strings used in the leaderboard command.",
// <editor-fold defaultstate="collapsed" desc="Discord - Command - Leaderboard">
keyGroups: [{
keys: [
"command_top_small_description",
"command_top_description"
],
embed: 0
}, {
keys: [
"command_top_no_server_title",
"command_top_no_server_description"
],
embed: 1
}, {
keys: [
"command_top_points",
"command_top_personal_title"
],
embed: 2
}, {
keys: [
"command_top_title",
"command_top_server_title",
"command_top_global_title",
"command_top_global_server_title",
"command_top_graphic_name",
"command_top_graphic_score",
"command_top_rank"
],
embed: 3
}],
embeds: [{
"header": "Example: Help Listing",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-15T18:23:21.259Z",
"title": [
{
"name": "command_help_command_title",
"args": {
"name": [
"Show Leaderboards"
]
}
}
],
"description": [
{
"name": "command_help_command_description",
"args": {
"description": [
{
"name": "command_top_description",
"args": null
}
]
}
}
],
"fields": [
{
"name": [
{
"name": "command_help_command_keywords",
"args": null
}
],
"value": [
"`top`, `leaderboard`, `leaderboards`, `most`, `highest`"
]
}
]
}, {
"header": "Example: 'Server' Supplied in DMs",
"color": 16604252,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
"molenzwiebel 👑"
]
},
"timestamp": "2019-12-17T21:23:03.058Z",
"title": [
{
"name": "command_top_no_server_title",
"args": null
}
],
"description": [
{
"name": "command_top_no_server_description",
"args": null
}
]
}, {
"header": "Example: Personal Top Champions",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 12
}
},
" • molenzwiebel 👑"
]
},
"timestamp": "2019-12-17T21:23:42.942Z",
"title": [
{
"name": "command_top_personal_title",
"args": {
"name": [
"molenzwiebel <a:Bot_Owner:468045368517722153>"
]
}
}
],
"fields": [
{
"name": [
"**<:Syndra:411977428227850241> 1 - ", { champion: "Syndra" }, "**"
],
"value": [
"<:Level_7:411977489707958282> 787,562 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Soraka:411977195506892802> 2 - ", { champion: "Soraka" }, "**"
],
"value": [
"<:Level_7:411977489707958282> 219,149 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Xayah:411977428718714900> 3 - ", { champion: "Xayah" }, "**"
],
"value": [
"<:Level_7:411977489707958282> 133,159 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Orianna:411977322510680067> 4 - ", { champion: "Orianna" }, "**"
],
"value": [
"<:Level_7:411977489707958282> 85,468 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Ashe:411977196606062602> 5 - ", { champion: "Ashe" }, "**"
],
"value": [
"<:Level_6:411977489351704587> 76,798 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Lucian:411977427989037058> 6 - ", { champion: "Lucian" }, "**"
],
"value": [
"<:Level_6:411977489351704587> 66,328 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Janna:411977195792105484> 7 - ", { champion: "Janna" }, "**"
],
"value": [
"<:Level_7:411977489707958282> 56,379 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Thresh:411977428291026968> 8 - ", { champion: "Thresh" }, "**"
],
"value": [
"<:Level_6:411977489351704587> 48,841 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Irelia:469632305699487755> 9 - ", { champion: "Irelia" }, "**"
],
"value": [
"<:Level_6:411977489351704587> 44,741 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Lulu:411977323529895936> 10 - ", { champion: "Lulu" }, "**"
],
"value": [
"<:Level_6:411977489351704587> 44,152 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Zyra:411977428378976286> 11 - ", { champion: "Zyra" }, "**"
],
"value": [
"<:Level_5:411977803144364032> 41,927 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
},
{
"name": [
"**<:Karma:411977195297439745> 12 - ", { champion: "Karma" }, "**"
],
"value": [
"<:Level_5:411977803144364032> 37,420 ",
{
"name": "command_top_points",
"args": null
}
],
"inline": true
}
]
}, {
"header": "Example: Other Strings",
"color": 693982,
"footer": {
"icon_url": "https://cdn.discordapp.com/avatars/86540964021161984/a_d53161375302810ca80c12eef8dee291.gif?size=128",
"text": [
{
"name": "command_page_n_of_n",
"args": {
"n": 1,
"total": 1
}
},
" • molenzwiebel 👑"
]
},
"description": [
"Since this is a generated image, I unfortunately cannot display a live preview. Here's some examples of the strings being used though:\n\n",
{
"name": "command_top_title",
"args": {
"champ": [
{ champion: "Syndra" }
]
}
},
"\n",
{
"name": "command_top_server_title",
"args": {
"champ": [
{ champion: "Syndra" }
]
}
},
"\n",
{
"name": "command_top_global_title",
"args": null
},
"\n",
{
"name": "command_top_global_server_title",
"args": null
},
"\n\nThe following strings are used in the generated image (as column headers):\n",
{
"name": "command_top_graphic_name",
"args": null
},
"\n",
{
"name": "command_top_graphic_score",
"args": null
},
"\n\nThe following strings are used in the footer:\n",
{
"name": "command_top_rank",
"args": null
}
],
"timestamp": "2019-12-17T21:24:58.460Z"
}]
// </editor-fold>
}];
export default SECTIONS; | the_stack |
import color from '@heroku-cli/color'
import {APIClient} from '@heroku-cli/command'
import {IOptions} from '@heroku-cli/command/lib/api-client'
import {Notification, notify} from '@heroku-cli/notifications'
import {Dyno as APIDyno} from '@heroku-cli/schema'
import {spawn} from 'child_process'
import cli from 'cli-ux'
import debugFactory from 'debug'
import {HTTP} from 'http-call'
import * as https from 'https'
import * as net from 'net'
import {Duplex, Transform} from 'stream'
import * as tls from 'tls'
import * as tty from 'tty'
// eslint-disable-next-line node/no-deprecated-api
import {URL, parse} from 'url'
import {buildEnvFromFlag} from '../lib/helpers'
const debug = debugFactory('heroku:run')
const wait = (ms: number) => new Promise(resolve => setTimeout(() => resolve(), ms))
interface HerokuApiClientRun extends APIClient {
options: IOptions & {
rejectUnauthorized?: boolean;
};
}
interface DynoOpts {
'exit-code'?: boolean;
'no-tty'?: boolean;
app: string;
attach?: boolean;
command: string;
dyno?: string;
env?: string;
heroku: APIClient;
listen?: boolean;
notify?: boolean;
showStatus?: boolean;
size?: string;
type?: string;
}
export default class Dyno extends Duplex {
get _useSSH() {
if (this.uri) {
/* tslint:disable:no-http-string */
return this.uri.protocol === 'http:' || this.uri.protocol === 'https:'
/* tslint:enable:no-http-string */
}
}
dyno?: APIDyno
heroku: HerokuApiClientRun
input: any
p: any
reject?: (reason?: any) => void
resolve?: (value?: unknown) => void
uri?: URL
legacyUri?: {[key: string]: any}
unpipeStdin: any
useSSH: any
private _notified?: boolean
private _startedAt?: number
constructor(public opts: DynoOpts) {
super()
this.cork()
this.opts = opts
this.heroku = opts.heroku
if (this.opts.showStatus === undefined) {
this.opts.showStatus = true
}
}
/**
* Starts the dyno
*/
async start() {
this._startedAt = Date.now()
if (this.opts.showStatus) {
cli.action.start(`Running ${color.cyan.bold(this.opts.command)} on ${color.app(this.opts.app)}`)
}
await this._doStart()
}
async _doStart(retries = 2): Promise<HTTP<unknown>> {
const command = this.opts['exit-code'] ? `${this.opts.command}; echo "\uFFFF heroku-command-exit-status: $?"` : this.opts.command
try {
const dyno = await this.heroku.post(this.opts.dyno ? `/apps/${this.opts.app}/dynos/${this.opts.dyno}` : `/apps/${this.opts.app}/dynos`, {
headers: {
Accept: this.opts.dyno ? 'application/vnd.heroku+json; version=3.run-inside' : 'application/vnd.heroku+json; version=3',
},
body: {
command,
attach: this.opts.attach,
size: this.opts.size,
type: this.opts.type,
env: this._env(),
force_no_tty: this.opts['no-tty'],
},
})
this.dyno = dyno.body
if (this.opts.attach || this.opts.dyno) {
if (this.dyno.name && this.opts.dyno === undefined) {
this.opts.dyno = this.dyno.name
}
await this.attach()
} else if (this.opts.showStatus) {
cli.action.stop(this._status('done'))
}
} catch (error) {
// Currently the runtime API sends back a 409 in the event the
// release isn't found yet. API just forwards this response back to
// the client, so we'll need to retry these. This usually
// happens when you create an app and immediately try to run a
// one-off dyno. No pause between attempts since this is
// typically a very short-lived condition.
if (error.statusCode === 409 && retries > 0) {
return this._doStart(retries - 1)
}
throw error
} finally {
cli.action.stop()
}
}
// Attaches stdin/stdout to dyno
attach() {
this.pipe(process.stdout)
if (this.dyno && this.dyno.attach_url) {
this.uri = new URL(this.dyno.attach_url)
this.legacyUri = parse(this.dyno.attach_url)
}
if (this._useSSH) {
this.p = this._ssh()
} else {
this.p = this._rendezvous()
}
return this.p.then(() => {
this.end()
})
}
_rendezvous() {
return new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
if (this.opts.showStatus) {
cli.action.status = this._status('starting')
}
const c = tls.connect(parseInt(this.uri.port, 10), this.uri.hostname, {
rejectUnauthorized: this.heroku.options.rejectUnauthorized,
})
c.setTimeout(1000 * 60 * 60)
c.setEncoding('utf8')
c.on('connect', () => {
debug('connect')
const pathnameWithSearchParams = this.uri.pathname + this.uri.search
c.write(pathnameWithSearchParams.substr(1) + '\r\n', () => {
if (this.opts.showStatus) {
cli.action.status = this._status('connecting')
}
})
})
c.on('data', this._readData(c))
c.on('close', () => {
debug('close')
this.opts['exit-code'] ? this.reject('No exit code returned') : this.resolve()
if (this.unpipeStdin) {
this.unpipeStdin()
}
})
c.on('error', this.reject)
c.on('timeout', () => {
debug('timeout')
c.end()
this.reject(new Error('timed out'))
})
process.once('SIGINT', () => c.end())
})
}
async _ssh(retries = 20): Promise<unknown> {
const interval = 1000
try {
const {body: dyno} = await this.heroku.get(`/apps/${this.opts.app}/dynos/${this.opts.dyno}`)
this.dyno = dyno
cli.action.stop(this._status(this.dyno.state))
if (this.dyno.state === 'starting' || this.dyno.state === 'up') {
return this._connect()
}
await wait(interval)
return this._ssh()
} catch (error) {
// the API sometimes responds with a 404 when the dyno is not yet ready
if (error.http.statusCode === 404 && retries > 0) {
return this._ssh(retries - 1)
}
throw error
}
}
_connect() {
return new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
const options: https.RequestOptions & { rejectUnauthorized?: boolean } = this.legacyUri
options.headers = {Connection: 'Upgrade', Upgrade: 'tcp'}
options.rejectUnauthorized = false
const r = https.request(options)
r.end()
r.on('error', this.reject)
r.on('upgrade', (_, remote) => {
const s = net.createServer(client => {
client.on('end', () => {
s.close()
this.resolve()
})
client.on('connect', () => s.close())
client.on('error', () => this.reject)
remote.on('error', () => this.reject)
client.setNoDelay(true)
remote.setNoDelay(true)
remote.on('data', data => client.write(data))
client.on('data', data => remote.write(data))
})
s.listen(0, 'localhost', () => this._handle(s))
// abort the request when the local pipe server is closed
s.on('close', () => {
r.abort()
})
})
})
}
_handle(localServer: net.Server) {
const addr = localServer.address() as net.AddressInfo
const host = addr.address
const port = addr.port
let lastErr = ''
// does not actually uncork but allows error to be displayed when attempting to read
this.uncork()
if (this.opts.listen) {
cli.log(`listening on port ${host}:${port} for ssh client`)
} else {
const params = [host, '-p', port.toString(), '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oServerAliveInterval=20']
// Debug SSH
if (this._isDebug()) {
params.push('-vvv')
}
const stdio: Array<(number | 'pipe')> = [0, 1, 'pipe']
if (this.opts['exit-code']) {
stdio[1] = 'pipe'
if (process.stdout.isTTY) {
// force tty
params.push('-t')
}
}
const sshProc = spawn('ssh', params, {stdio})
// only receives stdout with --exit-code
if (sshProc.stdout) {
sshProc.stdout.setEncoding('utf8')
sshProc.stdout.on('data', this._readData())
}
sshProc.stderr.on('data', data => {
lastErr = data
// supress host key and permission denied messages
if (this._isDebug() || (data.includes("Warning: Permanently added '[127.0.0.1]") && data.includes('Permission denied (publickey).'))) {
process.stderr.write(data)
}
})
sshProc.on('close', () => {
// there was a problem connecting with the ssh key
if (lastErr.length > 0 && lastErr.includes('Permission denied')) {
const msgs = ['There was a problem connecting to the dyno.']
if (process.env.SSH_AUTH_SOCK) {
msgs.push('Confirm that your ssh key is added to your agent by running `ssh-add`.')
}
msgs.push('Check that your ssh key has been uploaded to heroku with `heroku keys:add`.')
msgs.push(`See ${color.cyan('https://devcenter.heroku.com/articles/one-off-dynos#shield-private-spaces')}`)
cli.error(msgs.join('\n'))
}
// cleanup local server
localServer.close()
})
this.p
.then(() => sshProc.kill())
.catch(() => sshProc.kill())
}
this._notify()
}
_isDebug() {
const debug = process.env.HEROKU_DEBUG
return debug && (debug === '1' || debug.toUpperCase() === 'TRUE')
}
_env() {
const c: {[key: string]: any} = this.opts.env ? buildEnvFromFlag(this.opts.env) : {}
c.TERM = process.env.TERM
if (tty.isatty(1)) {
c.COLUMNS = process.stdout.columns
c.LINES = process.stdout.rows
}
return c
}
_status(status) {
const size = this.dyno.size ? ` (${this.dyno.size})` : ''
return `${status}, ${this.dyno.name || this.opts.dyno}${size}`
}
_readData(c?: tls.TLSSocket) {
let firstLine = true
return data => {
debug('input: %o', data)
// discard first line
if (c && firstLine) {
if (this.opts.showStatus) cli.action.stop(this._status('up'))
firstLine = false
this._readStdin(c)
return
}
this._notify()
// carriage returns break json parsing of output
if (!process.stdout.isTTY) {
// eslint-disable-next-line no-control-regex
data = data.replace(new RegExp('\r\n', 'g'), '\n')
}
const exitCode = data.match(/\uFFFF heroku-command-exit-status: (\d+)/m)
if (exitCode) {
debug('got exit code: %d', exitCode[1])
this.push(data.replace(/^\uFFFF heroku-command-exit-status: \d+$\n?/m, ''))
const code = parseInt(exitCode[1], 10)
if (code === 0) {
this.resolve()
} else {
const err: { exitCode?: number } & Error = new Error(`Process exited with code ${color.red(code.toString())}`)
err.exitCode = code
this.reject(err)
}
return
}
this.push(data)
}
}
_readStdin(c) {
this.input = c
const stdin: NodeJS.ReadStream & { unref?(): any } = process.stdin
stdin.setEncoding('utf8')
// without this the CLI will hang on rake db:migrate
// until a character is pressed
if (stdin.unref) {
stdin.unref()
}
if (!this.opts['no-tty'] && tty.isatty(0)) {
stdin.setRawMode(true)
stdin.pipe(c)
let sigints = []
stdin.on('data', function (c) {
if (c === '\u0003') {
sigints.push(Date.now())
}
sigints = sigints.filter(d => d > Date.now() - 1000)
if (sigints.length >= 4) {
cli.error('forcing dyno disconnect', {exit: 1})
}
})
} else {
stdin.pipe(new Transform({
objectMode: true,
transform: (chunk, _, next) => c.write(chunk, next),
// eslint-disable-next-line unicorn/no-hex-escape
flush: done => c.write('\x04', done),
}))
}
this.uncork()
}
_read() {
if (this.useSSH) {
throw new Error('Cannot read stream from ssh dyno')
}
// do not need to do anything to handle Readable interface
}
_write(chunk, encoding, callback) {
if (this.useSSH) {
throw new Error('Cannot write stream to ssh dyno')
}
if (!this.input) throw new Error('no input')
this.input.write(chunk, encoding, callback)
}
_notify() {
try {
if (this._notified) return
this._notified = true
if (!this.opts.notify) return
// only show notifications if dyno took longer than 20 seconds to start
if (Date.now() - this._startedAt < 1000 * 20) return
const notification: Notification & { subtitle?: string } = {
title: this.opts.app,
subtitle: `heroku run ${this.opts.command}`,
message: 'dyno is up',
// sound: true
}
notify(notification)
} catch (error) {
cli.warn(error)
}
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { buildDataTelemetryPayload, getDataTelemetry } from './get_data_telemetry';
import { DATA_DATASETS_INDEX_PATTERNS, DATA_DATASETS_INDEX_PATTERNS_UNIQUE } from './constants';
import { opensearchServiceMock } from '../../../../../../src/core/server/mocks';
describe('get_data_telemetry', () => {
describe('DATA_DATASETS_INDEX_PATTERNS', () => {
DATA_DATASETS_INDEX_PATTERNS.forEach((entry, index, array) => {
describe(`Pattern ${entry.pattern}`, () => {
test('there should only be one in DATA_DATASETS_INDEX_PATTERNS_UNIQUE', () => {
expect(
DATA_DATASETS_INDEX_PATTERNS_UNIQUE.filter(({ pattern }) => pattern === entry.pattern)
).toHaveLength(1);
});
// This test is to make us sure that we don't update one of the duplicated entries and forget about any other repeated ones
test('when a document is duplicated, the duplicates should be identical', () => {
array.slice(0, index).forEach((previousEntry) => {
if (entry.pattern === previousEntry.pattern) {
expect(entry).toStrictEqual(previousEntry);
}
});
});
});
});
});
describe('buildDataTelemetryPayload', () => {
test('return the base object when no indices provided', () => {
expect(buildDataTelemetryPayload([])).toStrictEqual([]);
});
test('return the base object when no matching indices provided', () => {
expect(
buildDataTelemetryPayload([
{ name: 'no__way__this__can_match_anything', sizeInBytes: 10 },
{ name: '.opensearch_dashboards-event-log-8.0.0' },
])
).toStrictEqual([]);
});
test('matches some indices and puts them in their own category', () => {
expect(
buildDataTelemetryPayload([
// APM Indices have known shipper (so we can infer the dataStreamType from mapping constant)
{ name: 'apm-7.7.0-error-000001', shipper: 'apm', isECS: true },
{ name: 'apm-7.7.0-metric-000001', shipper: 'apm', isECS: true },
{ name: 'apm-7.7.0-onboarding-2020.05.17', shipper: 'apm', isECS: true },
{ name: 'apm-7.7.0-profile-000001', shipper: 'apm', isECS: true },
{ name: 'apm-7.7.0-span-000001', shipper: 'apm', isECS: true },
{ name: 'apm-7.7.0-transaction-000001', shipper: 'apm', isECS: true },
// Packetbeat indices with known shipper (we can infer dataStreamType from mapping constant)
{ name: 'packetbeat-7.7.0-2020.06.11-000001', shipper: 'packetbeat', isECS: true },
// Matching patterns from the list => known dataStreamDataset but the rest is unknown
{ name: 'filebeat-12314', docCount: 100, sizeInBytes: 10 },
{ name: 'metricbeat-1234', docCount: 100, sizeInBytes: 10, isECS: false },
{ name: '.app-search-1234', docCount: 0 },
{ name: 'logs-endpoint.1234', docCount: 0 }, // Matching pattern with a dot in the name
// New Indexing strategy: everything can be inferred from the constant_keyword values
{
name: '.ds-logs-nginx.access-default-000001',
dataStreamDataset: 'nginx.access',
dataStreamType: 'logs',
shipper: 'filebeat',
isECS: true,
docCount: 1000,
sizeInBytes: 1000,
},
{
name: '.ds-logs-nginx.access-default-000002',
dataStreamDataset: 'nginx.access',
dataStreamType: 'logs',
shipper: 'filebeat',
isECS: true,
docCount: 1000,
sizeInBytes: 60,
},
{
name: '.ds-traces-something-default-000002',
dataStreamDataset: 'something',
dataStreamType: 'traces',
packageName: 'some-package',
isECS: true,
docCount: 1000,
sizeInBytes: 60,
},
{
name: '.ds-metrics-something.else-default-000002',
dataStreamDataset: 'something.else',
dataStreamType: 'metrics',
managedBy: 'ingest-manager',
isECS: true,
docCount: 1000,
sizeInBytes: 60,
},
// Filter out if it has dataStreamDataset and dataStreamType but none of the shipper, packageName or managedBy === 'ingest-manager'
{
name: 'some-index-that-should-not-show',
dataStreamDataset: 'should-not-show',
dataStreamType: 'logs',
isECS: true,
docCount: 1000,
sizeInBytes: 60,
},
{
name: 'other-index-that-should-not-show',
dataStreamDataset: 'should-not-show-either',
dataStreamType: 'metrics',
managedBy: 'me',
isECS: true,
docCount: 1000,
sizeInBytes: 60,
},
])
).toStrictEqual([
{
shipper: 'apm',
index_count: 6,
ecs_index_count: 6,
},
{
shipper: 'packetbeat',
index_count: 1,
ecs_index_count: 1,
},
{
pattern_name: 'filebeat',
shipper: 'filebeat',
index_count: 1,
doc_count: 100,
size_in_bytes: 10,
},
{
pattern_name: 'metricbeat',
shipper: 'metricbeat',
index_count: 1,
ecs_index_count: 0,
doc_count: 100,
size_in_bytes: 10,
},
{
pattern_name: 'app-search',
index_count: 1,
doc_count: 0,
},
{
pattern_name: 'logs-endpoint',
shipper: 'endpoint',
index_count: 1,
doc_count: 0,
},
{
data_stream: { dataset: 'nginx.access', type: 'logs' },
shipper: 'filebeat',
index_count: 2,
ecs_index_count: 2,
doc_count: 2000,
size_in_bytes: 1060,
},
{
data_stream: { dataset: 'something', type: 'traces' },
package: { name: 'some-package' },
index_count: 1,
ecs_index_count: 1,
doc_count: 1000,
size_in_bytes: 60,
},
{
data_stream: { dataset: 'something.else', type: 'metrics' },
index_count: 1,
ecs_index_count: 1,
doc_count: 1000,
size_in_bytes: 60,
},
]);
});
});
describe('getDataTelemetry', () => {
test('it returns the base payload (all 0s) because no indices are found', async () => {
const opensearchClient = mockOpenSearchClient();
await expect(getDataTelemetry(opensearchClient)).resolves.toStrictEqual([]);
expect(opensearchClient.indices.getMapping).toHaveBeenCalledTimes(1);
expect(opensearchClient.indices.stats).toHaveBeenCalledTimes(1);
});
test('can only see the index mappings, but not the stats', async () => {
const opensearchClient = mockOpenSearchClient(['filebeat-12314']);
await expect(getDataTelemetry(opensearchClient)).resolves.toStrictEqual([
{
pattern_name: 'filebeat',
shipper: 'filebeat',
index_count: 1,
ecs_index_count: 0,
},
]);
expect(opensearchClient.indices.getMapping).toHaveBeenCalledTimes(1);
expect(opensearchClient.indices.stats).toHaveBeenCalledTimes(1);
});
test('can see the mappings and the stats', async () => {
const opensearchClient = mockOpenSearchClient(
['filebeat-12314'],
{ isECS: true },
{
indices: {
'filebeat-12314': { total: { docs: { count: 100 }, store: { size_in_bytes: 10 } } },
},
}
);
await expect(getDataTelemetry(opensearchClient)).resolves.toStrictEqual([
{
pattern_name: 'filebeat',
shipper: 'filebeat',
index_count: 1,
ecs_index_count: 1,
doc_count: 100,
size_in_bytes: 10,
},
]);
});
test('find an index that does not match any index pattern but has mappings metadata', async () => {
const opensearchClient = mockOpenSearchClient(
['cannot_match_anything'],
{ isECS: true, dataStreamType: 'traces', shipper: 'my-beat' },
{
indices: {
cannot_match_anything: {
total: { docs: { count: 100 }, store: { size_in_bytes: 10 } },
},
},
}
);
await expect(getDataTelemetry(opensearchClient)).resolves.toStrictEqual([
{
data_stream: { dataset: undefined, type: 'traces' },
shipper: 'my-beat',
index_count: 1,
ecs_index_count: 1,
doc_count: 100,
size_in_bytes: 10,
},
]);
});
test('return empty array when there is an error', async () => {
const opensearchClient = opensearchServiceMock.createClusterClient().asInternalUser;
opensearchClient.indices.getMapping.mockRejectedValue(
new Error('Something went terribly wrong')
);
opensearchClient.indices.stats.mockRejectedValue(new Error('Something went terribly wrong'));
await expect(getDataTelemetry(opensearchClient)).resolves.toStrictEqual([]);
});
});
});
function mockOpenSearchClient(
indicesMappings: string[] = [], // an array of `indices` to get mappings from.
{ isECS = false, dataStreamDataset = '', dataStreamType = '', shipper = '' } = {},
indexStats: any = {}
) {
const opensearchClient = opensearchServiceMock.createClusterClient().asInternalUser;
// @ts-ignore
opensearchClient.indices.getMapping.mockImplementationOnce(async () => {
const body = Object.fromEntries(
indicesMappings.map((index) => [
index,
{
mappings: {
...(shipper && { _meta: { beat: shipper } }),
properties: {
...(isECS && { ecs: { properties: { version: { type: 'keyword' } } } }),
...((dataStreamType || dataStreamDataset) && {
data_stream: {
properties: {
...(dataStreamDataset && {
dataset: { type: 'constant_keyword', value: dataStreamDataset },
}),
...(dataStreamType && {
type: { type: 'constant_keyword', value: dataStreamType },
}),
},
},
}),
},
},
},
])
);
return { body };
});
// @ts-ignore
opensearchClient.indices.stats.mockImplementationOnce(async () => {
return { body: indexStats };
});
return opensearchClient;
} | the_stack |
import { Choice, PromptConfig } from "../types/core"
import { EditorConfig } from "../types/app"
import { Observable, merge, NEVER, of } from "rxjs"
import {
filter,
map,
share,
switchMap,
take,
takeUntil,
tap,
} from "rxjs/operators"
import stripAnsi from "strip-ansi"
import { Mode, Channel, UI } from "../core/enum.js"
import { assignPropsTo } from "../core/utils.js"
interface AppMessage {
channel: Channel
value?: any
input?: string
tab?: string
flag?: string
}
let displayChoices = (
choices: Choice<any>[],
className = ""
) => {
switch (typeof choices) {
case "string":
global.setPanel(choices, className)
break
case "object":
global.setChoices(checkResultInfo(choices), className)
break
}
}
let checkResultInfo = result => {
if (result?.panel) {
global.setPanel(result.panel, result?.className || "")
}
if (result?.hint) {
global.setHint(result.hint)
}
if (result?.choices) {
return result.choices
}
return result
}
let promptId = 0
let invokeChoices =
({ ct, choices, className }) =>
async (input: string) => {
let resultOrPromise = choices(input)
if (resultOrPromise && resultOrPromise.then) {
let result = await resultOrPromise
if (
ct.promptId === promptId &&
ct.tabIndex === global.onTabIndex
) {
displayChoices(result, className)
return result
}
} else {
displayChoices(resultOrPromise, className)
return resultOrPromise
}
}
let getInitialChoices = async ({
ct,
choices,
className,
}) => {
if (typeof choices === "function") {
return await invokeChoices({ ct, choices, className })(
""
)
} else {
displayChoices(choices as any, className)
return choices
}
}
let waitForPromptValue = ({
choices,
validate,
ui,
className,
}) =>
new Promise((resolve, reject) => {
promptId++
let ct = {
promptId,
tabIndex: global.onTabIndex,
}
let process$ = new Observable<AppMessage>(observer => {
let m = (data: AppMessage) => observer.next(data)
let e = (error: Error) => observer.error(error)
process.on("message", m)
process.on("error", e)
return () => {
process.off("message", m)
process.off("error", e)
}
}).pipe(
switchMap(data => of(data)),
share()
)
let tab$ = process$.pipe(
filter(data => data.channel === Channel.TAB_CHANGED),
tap(data => {
let tabIndex = global.onTabs.findIndex(
({ name }) => {
return name == data?.tab
}
)
// console.log(`\nUPDATING TAB: ${tabIndex}`)
global.onTabIndex = tabIndex
global.currentOnTab = global.onTabs[tabIndex].fn(
data?.input
)
}),
share()
)
let message$ = process$.pipe(share(), takeUntil(tab$))
let generate$ = message$.pipe(
filter(
data => data.channel === Channel.GENERATE_CHOICES
),
map(data => data.input),
switchMap(input => {
let ct = {
promptId,
tabIndex: +Number(global.onTabIndex),
}
return invokeChoices({ ct, choices, className })(
input
)
}),
switchMap(choice => NEVER)
)
let valueSubmitted$ = message$.pipe(
filter(
data => data.channel === Channel.VALUE_SUBMITTED
)
)
let value$ = valueSubmitted$.pipe(
tap(data => {
if (data.flag) {
global.flag[data.flag] = true
}
}),
map(data => data.value),
switchMap(async value => {
if (validate) {
let validateMessage = await validate(value)
if (typeof validateMessage === "string") {
let Convert = await npm("ansi-to-html")
let convert = new Convert()
global.setHint(convert.toHtml(validateMessage))
global.setChoices(global.kitPrevChoices)
} else {
return value
}
} else {
return value
}
}),
filter(value => typeof value !== "undefined"),
take(1)
)
let blur$ = message$.pipe(
filter(
data => data.channel === Channel.PROMPT_BLURRED
)
)
blur$.pipe(takeUntil(value$)).subscribe({
next: () => {
exit()
},
})
generate$.pipe(takeUntil(value$)).subscribe()
let initialChoices$ = of({
ct,
choices,
className,
}).pipe(
// filter(() => ui === UI.arg),
switchMap(getInitialChoices)
)
initialChoices$.pipe(takeUntil(value$)).subscribe()
merge(value$).subscribe({
next: value => {
resolve(value)
},
complete: () => {
// console.log(`Complete: ${promptId}`)
},
error: error => {
reject(error)
},
})
})
global.kitPrompt = async (config: PromptConfig) => {
await wait(0) //need to let tabs finish...
let {
ui = UI.arg,
placeholder = "",
validate = null,
strict = Boolean(config?.choices),
choices: choices = [],
secret = false,
hint = "",
input = "",
ignoreBlur = false,
mode = Mode.FILTER,
className = "",
flags = undefined,
selected = "",
type = "text",
} = config
if (flags) {
setFlags(flags)
}
global.setMode(
typeof choices === "function" && choices?.length > 0
? Mode.GENERATE
: mode
)
let tabs = global.onTabs?.length
? global.onTabs.map(({ name }) => name)
: []
global.send(Channel.SET_PROMPT_DATA, {
tabs,
tabIndex: global.onTabs?.findIndex(
({ name }) => global.arg?.tab
),
placeholder: stripAnsi(placeholder),
kitScript: global.kitScript,
parentScript: global.env.KIT_PARENT_NAME,
kitArgs: global.args.join(" "),
secret,
ui,
strict,
selected,
type,
ignoreBlur,
})
global.setHint(hint)
if (input) global.setInput(input)
if (ignoreBlur) global.setIgnoreBlur(true)
return await waitForPromptValue({
choices,
validate,
ui,
className,
})
}
global.drop = async (
placeholder = "Waiting for drop..."
) => {
return await global.kitPrompt({
ui: UI.drop,
placeholder,
ignoreBlur: true,
})
}
global.form = async (html = "", formData = {}) => {
send(Channel.SET_FORM_HTML, { html, formData })
return await global.kitPrompt({
ui: UI.form,
})
}
global.div = async (html = "", containerClasses = "") => {
let wrapHtml = `<div class="${containerClasses}">${html}</div>`
return await global.kitPrompt({
choices: wrapHtml,
ui: UI.div,
})
}
global.editor = async (
options: EditorConfig = {
value: "",
language: "",
scrollTo: "top",
}
) => {
send(Channel.SET_EDITOR_CONFIG, {
options:
typeof options === "string"
? { value: options }
: options,
})
return await global.kitPrompt({
ui: UI.editor,
ignoreBlur: true,
})
}
global.hotkey = async (
placeholder = "Press a key combo:"
) => {
return await global.kitPrompt({
ui: UI.hotkey,
placeholder,
})
}
global.arg = async (
placeholderOrConfig = "Type a value:",
choices
) => {
let firstArg = global.args.length
? global.args.shift()
: null
if (firstArg) {
let validate = (placeholderOrConfig as PromptConfig)
?.validate
if (typeof validate === "function") {
let valid = await validate(firstArg)
if (valid === true) return firstArg
let Convert = await npm("ansi-to-html")
let convert = new Convert()
let hint =
valid === false
? `${firstArg} is not a valid value`
: convert.toHtml(valid)
return global.arg({
...(placeholderOrConfig as PromptConfig),
hint,
})
} else {
return firstArg
}
}
if (typeof placeholderOrConfig === "string") {
return await global.kitPrompt({
ui: UI.arg,
placeholder: placeholderOrConfig,
choices: choices,
})
}
return await global.kitPrompt({
choices: choices,
...placeholderOrConfig,
})
}
global.textarea = async (
options = {
value: "",
placeholder: `cmd + s to submit\ncmd + w to close`,
}
) => {
send(Channel.SET_TEXTAREA_CONFIG, {
options:
typeof options === "string"
? { value: options }
: options,
})
return await global.kitPrompt({
ui: UI.textarea,
ignoreBlur: true,
})
}
let { default: minimist } = (await import(
"minimist"
)) as any
global.args = []
global.updateArgs = arrayOfArgs => {
let argv = minimist(arrayOfArgs)
global.args = [...argv._, ...global.args]
global.argOpts = Object.entries(argv)
.filter(([key]) => key != "_")
.flatMap(([key, value]) => {
if (typeof value === "boolean") {
if (value) return [`--${key}`]
if (!value) return [`--no-${key}`]
}
return [`--${key}`, value]
})
assignPropsTo(argv, global.arg)
global.flag = { ...argv, ...global.flag }
delete global.flag._
}
global.updateArgs(process.argv.slice(2))
let appInstall = async packageName => {
if (!global.arg?.trust) {
let placeholder = `${packageName} is required for this script`
let packageLink = `https://npmjs.com/package/${packageName}`
let hint = `[${packageName}](${packageLink}) has had ${
(
await get(
`https://api.npmjs.org/downloads/point/last-week/` +
packageName
)
).data.downloads
} downloads from npm in the past week`
let trust = await global.arg(
{ placeholder, hint: md(hint) },
[
{
name: `Abort`,
value: "false",
},
{
name: `Install ${packageName}`,
value: "true",
},
]
)
if (trust === "false") {
echo(`Ok. Exiting...`)
exit()
}
}
setHint(`Installing ${packageName}...`)
await global.cli("install", packageName)
}
let { createNpm } = await import("../api/npm.js")
global.npm = createNpm(appInstall)
global.setPanel = async (html, containerClasses = "") => {
let wrapHtml = `<div class="${containerClasses}">${html}</div>`
global.send(Channel.SET_PANEL, {
html: wrapHtml,
})
}
global.setMode = async mode => {
global.send(Channel.SET_MODE, {
mode,
})
}
global.setHint = async hint => {
global.send(Channel.SET_HINT, {
hint,
})
}
global.setInput = async input => {
global.send(Channel.SET_INPUT, {
input,
})
}
global.setIgnoreBlur = async ignore => {
global.send(Channel.SET_IGNORE_BLUR, { ignore })
}
global.getDataFromApp = async channel => {
if (process?.send) {
return await new Promise((res, rej) => {
let messageHandler = data => {
if (data.channel === channel) {
res(data)
process.off("message", messageHandler)
}
}
process.on("message", messageHandler)
send(`GET_${channel}`)
})
} else {
return {}
}
}
global.getBackgroundTasks = () =>
global.getDataFromApp("BACKGROUND")
global.getSchedule = () => global.getDataFromApp("SCHEDULE")
global.getScriptsState = () =>
global.getDataFromApp("SCRIPTS_STATE") | the_stack |
import { Chain } from '../classes/Chain'
import Pose, { BoneTransform } from '../classes/Pose'
import { Quaternion, Vector3, Matrix4 } from 'three'
import { Axis } from '../classes/Axis'
import { cosSSS } from './IKFunctions'
import { IKRigComponentType } from '../components/IKRigComponent'
import { CameraIKComponentType } from '../components/CameraIKComponent'
///////////////////////////////////////////////////////////////////
// Multi Bone Solvers
///////////////////////////////////////////////////////////////////
export type IKSolverFunction = (
chain: Chain,
tpose: Pose,
pose: Pose,
axis: Axis,
cLen: number,
p_wt: BoneTransform
) => void
const vec3 = new Vector3()
const quat = new Quaternion()
const tempQuat1 = new Quaternion()
const tempQuat2 = new Quaternion()
const tempQuat3 = new Quaternion()
const tempVec1 = new Vector3()
const tempVec2 = new Vector3()
const tempVec3 = new Vector3()
/**
*
* @param chain
* @param tpose
* @param pose
* @param axis IKPose.target.axis
* @param cLen IKPose.target.len
* @param p_wt parent world transform
*/
export function solveLimb(chain: Chain, tpose: Pose, pose: Pose, axis: Axis, cLen: number, p_wt: BoneTransform) {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Using law of cos SSS, we need the length of all sides of the triangle
let bindA = tpose.bones[chain.chainBones[0].index], // Bone Reference from Bind
bindB = tpose.bones[chain.chainBones[1].index],
poseA = pose.bones[chain.chainBones[0].index], // Bone Reference from Pose
poseB = pose.bones[chain.chainBones[1].index],
aLen = bindA.length,
bLen = bindB.length,
rot = tempQuat1,
rad: number
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FIRST BONE - Aim then rotate by the angle.
_aim_bone2(chain, tpose, axis, p_wt, rot) // Aim the first bone toward the target oriented with the bend direction.
const rotAfterAim = tempQuat2.copy(rot)
const acbLen = { aLen, cLen, bLen }
rad = cosSSS(aLen, cLen, bLen) // Get the Angle between First Bone and Target.
const firstRad = rad
rot
.premultiply(tempQuat3.setFromAxisAngle(axis.x, -rad)) // Use the Target's X axis for rotation along with the angle from SSS
.premultiply(tempQuat3.copy(p_wt.quaternion).invert()) // Convert to Bone's Local Space by mul invert of parent bone rotation
pose.setBone(bindA.idx, rot) // Save result to bone.
// Update World Data for future use
poseA.world.position.copy(p_wt.position)
poseA.world.quaternion.copy(p_wt.quaternion)
poseA.world.scale.copy(p_wt.scale)
transformAdd(
// transform
poseA.world,
// add
{
quaternion: rot,
position: bindA.local.position,
scale: bindA.local.scale
}
)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SECOND BONE
// Need to rotate from Right to Left, So take the angle and subtract it from 180 to rotate from
// the other direction. Ex. L->R 70 degrees == R->L 110 degrees
rad = Math.PI - cosSSS(aLen, bLen, cLen)
rot
.copy(poseA.world.quaternion)
.multiply(bindB.local.quaternion) // Add Bone 2's Local Bind Rotation to Bone 1's new World Rotation.
.premultiply(tempQuat3.setFromAxisAngle(axis.x, rad)) // Rotate it by the target's x-axis
.premultiply(tempQuat3.copy(poseA.world.quaternion).invert()) // Convert to Bone's Local Space
pose.setBone(bindB.idx, rot) // Save result to bone.
// Update World Data for future use
poseB.world.position.copy(poseA.world.position)
poseB.world.quaternion.copy(poseA.world.quaternion)
poseB.world.scale.copy(poseA.world.scale)
transformAdd(
// transform
poseB.world,
// add
{
quaternion: rot,
position: bindB.local.position,
scale: bindB.local.scale
}
)
// TODO: Because of the quaternion object prop, it is better to
// Accept an output object parameter instead of returning new object
// and push the object construction up the chain
return {
rotAfterAim,
acbLen,
firstRad
}
}
export function solveThreeBone(chain: Chain, tpose: Pose, pose: Pose, axis: Axis, cLen: number, p_wt: BoneTransform) {
//------------------------------------
// Get the length of the bones, the calculate the ratio length for the bones based on the chain length
// The 3 bones when placed in a zig-zag pattern creates a Parallelogram shape. We can break the shape down into two triangles
// By using the ratio of the Target length divided between the 2 triangles, then using the first bone + half of the second bound
// to solve for the top 2 joints, then uing the half of the second bone + 3rd bone to solve for the bottom joint.
// If all bones are equal length, then we only need to use half of the target length and only test one triangle and use that for
// both triangles, but if bones are uneven, then we need to solve an angle for each triangle which this function does.
//------------------------------------
let bind_a = tpose.bones[chain.chainBones[0].index], // Bone Reference from Bind
bind_b = tpose.bones[chain.chainBones[1].index],
bind_c = tpose.bones[chain.chainBones[2].index],
pose_a = pose.bones[chain.chainBones[0].index], // Bone Reference from Pose
pose_b = pose.bones[chain.chainBones[1].index],
pose_c = pose.bones[chain.chainBones[2].index],
a_len = bind_a.length, // First Bone length
b_len = bind_b.length, // Second Bone Length
c_len = bind_c.length, // Third Bone Length
bh_len = bind_b.length * 0.5, // How Much of Bone 2 to use with Bone 1
t_ratio = (a_len + bh_len) / (a_len + b_len + c_len), // How much to subdivide the Target length between the two triangles
ta_len = cLen * t_ratio, // Goes with A & B
tb_len = cLen - ta_len, // Goes with B & C
rot = new Quaternion(),
rad
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Bone A
_aim_bone2(chain, tpose, axis, p_wt, rot) // Aim the first bone toward the target oriented with the bend direction.
rad = cosSSS(a_len, ta_len, bh_len) // Get the Angle between First Bone and Target.
rot
.premultiply(quat.setFromAxisAngle(axis.x, -rad)) // Rotate the the aimed bone by the angle from SSS
.premultiply(quat.copy(p_wt.quaternion).invert()) // Convert to Bone's Local Space by mul invert of parent bone rotation
pose.setBone(bind_a.idx, rot)
pose_a.world.position.copy(p_wt.position)
pose_a.world.quaternion.copy(p_wt.quaternion)
pose_a.world.scale.copy(p_wt.scale)
transformAdd(pose_a.world, { ...bind_a.local, quaternion: rot })
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Bone B
rad = Math.PI - cosSSS(a_len, bh_len, ta_len)
rot
.copy(pose_a.world.quaternion)
.multiply(bind_b.local.quaternion) // Add Bone Local to get its WS rot
.premultiply(quat.setFromAxisAngle(axis.x, rad)) // Rotate it by the target's x-axis .pmul( tmp.from_axis_angle( this.axis.x, rad ) )
.premultiply(quat.copy(pose_a.world.quaternion).invert()) // Convert to Local Space in temp to save WS rot for next bone.
pose.setBone(bind_b.idx, rot)
pose_b.world.position.copy(pose_a.world.position)
pose_b.world.quaternion.copy(pose_a.world.quaternion)
pose_b.world.scale.copy(pose_a.world.scale)
transformAdd(pose_b.world, { ...bind_b.local, quaternion: rot })
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Bone C
rad = Math.PI - cosSSS(c_len, bh_len, tb_len)
rot
.copy(pose_b.world.quaternion)
.multiply(bind_c.local.quaternion) // Still contains WS from previous bone, Add next bone's local
.premultiply(quat.setFromAxisAngle(axis.x, -rad)) // Rotate it by the target's x-axis
.premultiply(quat.copy(pose_b.world.quaternion).invert()) // Convert to Bone's Local Space
pose.setBone(bind_c.idx, rot)
pose_c.world.position.copy(pose_b.world.position)
pose_c.world.quaternion.copy(pose_b.world.quaternion)
pose_c.world.scale.copy(pose_b.world.scale)
transformAdd(pose_c.world, { ...bind_c.local, quaternion: rot })
}
// Computing Transforms, Parent -> Child
/**
*
* @param target target transform (will be modified)
* @param source source transform
*/
export function transformAdd(target: BoneTransform, source: BoneTransform) {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// POSITION - parent.position + ( parent.rotation * ( parent.scale * child.position ) )
// pos.add( Vec3.mul( this.scl, cp ).transform_quat( this.rot ) );
target.position.add(vec3.copy(source.position).multiply(target.scale).applyQuaternion(target.quaternion))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SCALE - parent.scale * child.scale
if (source.scale) target.scale.multiply(source.scale)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ROTATION - parent.rotation * child.rotation
target.quaternion.multiply(source.quaternion)
}
//// helpers
const rot = new Quaternion()
const rot2 = new Quaternion()
const rotationMatrix = new Matrix4()
function _aim_bone2(chain: Chain, tpose: Pose, axis: Axis, p_wt: BoneTransform, out: Quaternion) {
const bone = tpose.bones[chain.first()].bone
rotationMatrix.extractRotation(bone.matrixWorld)
const dir = vec3.copy(chain.altForward).applyQuaternion(rot.setFromRotationMatrix(rotationMatrix)) // Get Bone's WS Forward Dir
//Swing
rot2.setFromUnitVectors(dir, axis.z)
out.copy(rot2).multiply(rot)
// Twist
// let u_dir = chain.altUp.clone().applyQuaternion(out)
// let twistx = u_dir.angleTo(axis.y)
//App.Debug.ln( ct.pos, Vec3.add( ct.pos, u_dir), "white" );
dir.copy(chain.altUp).applyQuaternion(out) // After Swing, Whats the UP Direction
let twist = dir.angleTo(axis.y) // Get difference between Swing Up and Target Up
if (twist <= 0.00017453292) twist = 0
else {
//let l_dir = Vec3.cross( dir, this.axis.z );
dir.crossVectors(dir, axis.z) // Get Swing LEFT, used to test if twist is on the negative side.
//App.Debug.ln( ct.pos, Vec3.add( ct.pos, l_dir), "black" );
if (dir.dot(axis.y) >= 0) twist = -twist
}
out.premultiply(rot.setFromAxisAngle(axis.z, twist)) // Apply Twist
}
function getFwdVector(matrix: Matrix4, outVec: Vector3) {
const e = matrix.elements
outVec.set(e[8], e[9], e[10]).normalize()
}
export function applyCameraLook(rig: IKRigComponentType, solver: CameraIKComponentType) {
const bone = rig.pose!.skeleton.bones[solver.boneIndex]
if (!bone) {
return
}
bone.matrixWorld.decompose(tempVec1, tempQuat1, tempVec2)
const toLocal = tempQuat1.invert()
const boneFwd = tempVec1
const targetDir = tempVec2
getFwdVector(bone.matrix, boneFwd)
getFwdVector(solver.camera.matrixWorld, targetDir)
targetDir.multiplyScalar(-1).applyQuaternion(toLocal).normalize()
const angle = Math.acos(boneFwd.dot(targetDir))
if (solver.rotationClamp > 0 && angle > solver.rotationClamp) {
const deltaTarget = tempVec3.copy(targetDir).sub(boneFwd)
// clamp delta target to within the ratio
deltaTarget.multiplyScalar(solver.rotationClamp / angle)
// set new target
targetDir.copy(boneFwd).add(deltaTarget).normalize()
}
tempQuat1.setFromUnitVectors(boneFwd, targetDir)
bone.quaternion.premultiply(tempQuat1)
} | the_stack |
import {LocationManager} from '../../../../../src/backend/model/database/LocationManager';
import {SearchManager} from '../../../../../src/backend/model/database/sql/SearchManager';
import {SearchResultDTO} from '../../../../../src/common/entities/SearchResultDTO';
import {Utils} from '../../../../../src/common/Utils';
import {DBTestHelper} from '../../../DBTestHelper';
import {
ANDSearchQuery,
DistanceSearch,
FromDateSearch,
MaxRatingSearch,
MaxResolutionSearch,
MinRatingSearch,
MinResolutionSearch,
OrientationSearch,
ORSearchQuery,
SearchListQuery,
SearchQueryDTO,
SearchQueryTypes,
SomeOfSearchQuery,
TextSearch,
TextSearchQueryMatchTypes,
ToDateSearch
} from '../../../../../src/common/entities/SearchQueryDTO';
import {IndexingManager} from '../../../../../src/backend/model/database/sql/IndexingManager';
import {DirectoryBaseDTO, ParentDirectoryDTO, SubDirectoryDTO} from '../../../../../src/common/entities/DirectoryDTO';
import {TestHelper} from './TestHelper';
import {ObjectManagers} from '../../../../../src/backend/model/ObjectManagers';
import {GalleryManager} from '../../../../../src/backend/model/database/sql/GalleryManager';
import {Connection} from 'typeorm';
import {DirectoryEntity} from '../../../../../src/backend/model/database/sql/enitites/DirectoryEntity';
import {GPSMetadata, PhotoDTO, PhotoMetadata} from '../../../../../src/common/entities/PhotoDTO';
import {VideoDTO} from '../../../../../src/common/entities/VideoDTO';
import {AutoCompleteItem} from '../../../../../src/common/entities/AutoCompleteItem';
import {Config} from '../../../../../src/common/config/private/Config';
import {SearchQueryParser} from '../../../../../src/common/SearchQueryParser';
import {FileDTO} from '../../../../../src/common/entities/FileDTO';
const deepEqualInAnyOrder = require('deep-equal-in-any-order');
const chai = require('chai');
chai.use(deepEqualInAnyOrder);
const {expect} = chai;
// to help WebStorm to handle the test cases
declare let describe: any;
declare const after: any;
declare const before: any;
const tmpDescribe = describe;
describe = DBTestHelper.describe(); // fake it os IDE plays nicely (recognize the test)
class IndexingManagerTest extends IndexingManager {
public async saveToDB(scannedDirectory: ParentDirectoryDTO): Promise<void> {
return super.saveToDB(scannedDirectory);
}
}
class SearchManagerTest extends SearchManager {
public flattenSameOfQueries(query: SearchQueryDTO): SearchQueryDTO {
return super.flattenSameOfQueries(query);
}
}
class GalleryManagerTest extends GalleryManager {
public async selectParentDir(connection: Connection, directoryName: string, directoryParent: string): Promise<ParentDirectoryDTO> {
return super.selectParentDir(connection, directoryName, directoryParent);
}
public async fillParentDir(connection: Connection, dir: ParentDirectoryDTO): Promise<void> {
return super.fillParentDir(connection, dir);
}
}
describe('SearchManager', (sqlHelper: DBTestHelper) => {
describe = tmpDescribe;
/**
* dir
* |- v
* |- p
* |- p2
* |- gpx
* |-> subDir
* |- pFaceLess
* |-> subDir2
* |- p4
*/
let dir: ParentDirectoryDTO;
let subDir: SubDirectoryDTO;
let subDir2: SubDirectoryDTO;
let v: VideoDTO;
let p: PhotoDTO;
let p2: PhotoDTO;
let pFaceLess: PhotoDTO;
let p4: PhotoDTO;
let gpx: FileDTO;
const setUpTestGallery = async (): Promise<void> => {
const directory: ParentDirectoryDTO = TestHelper.getDirectoryEntry();
subDir = TestHelper.getDirectoryEntry(directory, 'The Phantom Menace');
subDir2 = TestHelper.getDirectoryEntry(directory, 'Return of the Jedi');
p = TestHelper.getPhotoEntry1(directory);
p2 = TestHelper.getPhotoEntry2(directory);
v = TestHelper.getVideoEntry1(directory);
gpx = TestHelper.getRandomizedGPXEntry(directory);
p4 = TestHelper.getPhotoEntry4(subDir2);
const pFaceLessTmp = TestHelper.getPhotoEntry3(subDir);
delete pFaceLessTmp.metadata.faces;
dir = await DBTestHelper.persistTestDir(directory);
subDir = dir.directories[0];
subDir2 = dir.directories[1];
p = (dir.media.filter(m => m.name === p.name)[0] as any);
p2 = (dir.media.filter(m => m.name === p2.name)[0] as any);
gpx = (dir.metaFile[0] as any);
v = (dir.media.filter(m => m.name === v.name)[0] as any);
p4 = (dir.directories[1].media[0] as any);
pFaceLess = (dir.directories[0].media[0] as any);
};
const setUpSqlDB = async () => {
await sqlHelper.initDB();
await setUpTestGallery();
await ObjectManagers.InitSQLManagers();
};
before(async () => {
await setUpSqlDB();
Config.Client.Search.listDirectories = true;
Config.Client.Search.listMetafiles = false;
});
after(async () => {
await sqlHelper.clearDB();
Config.Client.Search.listDirectories = false;
Config.Client.Search.listMetafiles = false;
});
it('should get autocomplete', async () => {
const sm = new SearchManager();
const cmp = (a: AutoCompleteItem, b: AutoCompleteItem) => {
if (a.text === b.text) {
return a.type - b.type;
}
return a.text.localeCompare(b.text);
};
expect((await sm.autocomplete('tat', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('Tatooine', SearchQueryTypes.position)]);
expect((await sm.autocomplete('star', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('star wars', SearchQueryTypes.keyword),
new AutoCompleteItem('death star', SearchQueryTypes.keyword)]);
expect((await sm.autocomplete('wars', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('star wars', SearchQueryTypes.keyword),
new AutoCompleteItem('wars dir', SearchQueryTypes.directory)]);
expect((await sm.autocomplete('arch', SearchQueryTypes.any_text))).eql([
new AutoCompleteItem('Research City', SearchQueryTypes.position)]);
Config.Client.Search.AutoComplete.maxItemsPerCategory = 99999;
expect((await sm.autocomplete('wa', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('star wars', SearchQueryTypes.keyword),
new AutoCompleteItem('Anakin Skywalker', SearchQueryTypes.person),
new AutoCompleteItem('Luke Skywalker', SearchQueryTypes.person),
new AutoCompleteItem('wars dir', SearchQueryTypes.directory)]);
Config.Client.Search.AutoComplete.maxItemsPerCategory = 1;
expect((await sm.autocomplete('a', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('Ajan Kloss', SearchQueryTypes.position),
new AutoCompleteItem('Amber stone', SearchQueryTypes.caption),
new AutoCompleteItem('star wars', SearchQueryTypes.keyword),
new AutoCompleteItem('Anakin Skywalker', SearchQueryTypes.person),
new AutoCompleteItem('Castilon', SearchQueryTypes.position),
new AutoCompleteItem('Devaron', SearchQueryTypes.position),
new AutoCompleteItem('The Phantom Menace', SearchQueryTypes.directory)]);
Config.Client.Search.AutoComplete.maxItemsPerCategory = 5;
expect((await sm.autocomplete('sw', SearchQueryTypes.any_text))).to.deep.equalInAnyOrder([
new AutoCompleteItem('sw1.jpg', SearchQueryTypes.file_name),
new AutoCompleteItem('sw2.jpg', SearchQueryTypes.file_name),
new AutoCompleteItem('sw3.jpg', SearchQueryTypes.file_name),
new AutoCompleteItem('sw4.jpg', SearchQueryTypes.file_name),
new AutoCompleteItem(v.name, SearchQueryTypes.file_name)]);
expect((await sm.autocomplete(v.name, SearchQueryTypes.any_text))).to.deep.equalInAnyOrder(
[new AutoCompleteItem(v.name, SearchQueryTypes.file_name)]);
});
const searchifyMedia = <T extends FileDTO | PhotoDTO>(m: T): T => {
const tmpDir: DirectoryBaseDTO = m.directory as DirectoryBaseDTO;
const tmpM = tmpDir.media;
const tmpD = tmpDir.directories;
const tmpP = tmpDir.preview;
const tmpMT = tmpDir.metaFile;
delete tmpDir.directories;
delete tmpDir.media;
delete tmpDir.preview;
delete tmpDir.metaFile;
const ret = Utils.clone(m);
delete (ret.directory as DirectoryBaseDTO).lastScanned;
delete (ret.directory as DirectoryBaseDTO).lastModified;
delete (ret.directory as DirectoryBaseDTO).mediaCount;
if ((ret as PhotoDTO).metadata &&
((ret as PhotoDTO).metadata as PhotoMetadata).faces && !((ret as PhotoDTO).metadata as PhotoMetadata).faces.length) {
delete ((ret as PhotoDTO).metadata as PhotoMetadata).faces;
}
tmpDir.directories = tmpD;
tmpDir.media = tmpM;
tmpDir.preview = tmpP;
tmpDir.metaFile = tmpMT;
return ret;
};
const searchifyDir = (d: DirectoryBaseDTO): DirectoryBaseDTO => {
const tmpM = d.media;
const tmpD = d.directories;
const tmpP = d.preview;
const tmpMT = d.metaFile;
delete d.directories;
delete d.media;
delete d.preview;
delete d.metaFile;
const ret = Utils.clone(d);
d.directories = tmpD;
d.media = tmpM;
d.preview = tmpP;
d.metaFile = tmpMT;
ret.isPartial = true;
return ret;
};
const removeDir = (result: SearchResultDTO) => {
result.media = result.media.map(m => searchifyMedia(m));
result.metaFile = result.metaFile.map(m => searchifyMedia(m));
result.directories = result.directories.map(m => searchifyDir(m) as SubDirectoryDTO);
return Utils.clone(result);
};
describe('advanced search', async () => {
afterEach(async () => {
Config.Client.Search.listDirectories = false;
Config.Client.Search.listMetafiles = false;
});
afterEach(async () => {
Config.Client.Search.listDirectories = false;
Config.Client.Search.listMetafiles = false;
});
it('should AND', async () => {
const sm = new SearchManager();
let query: SearchQueryDTO = {
type: SearchQueryTypes.AND,
list: [{text: p.metadata.faces[0].name, type: SearchQueryTypes.person} as TextSearch,
{text: p2.metadata.caption, type: SearchQueryTypes.caption} as TextSearch]
} as ANDSearchQuery;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.AND,
list: [{text: p.metadata.faces[0].name, type: SearchQueryTypes.person} as TextSearch,
{text: p.metadata.caption, type: SearchQueryTypes.caption} as TextSearch]
} as ANDSearchQuery);
expect(await sm.search(query)).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
// make sure that this shows both photos. We need this the the rest of the tests
query = ({text: 'a', type: SearchQueryTypes.person} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.AND,
list: [{
type: SearchQueryTypes.AND,
list: [{text: 'a', type: SearchQueryTypes.person} as TextSearch,
{text: p.metadata.keywords[0], type: SearchQueryTypes.keyword} as TextSearch]
} as ANDSearchQuery,
{text: p.metadata.caption, type: SearchQueryTypes.caption} as TextSearch
]
} as ANDSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should OR', async () => {
const sm = new SearchManager();
let query: SearchQueryDTO = {
type: SearchQueryTypes.OR,
list: [{text: 'Not a person', type: SearchQueryTypes.person} as TextSearch,
{text: 'Not a caption', type: SearchQueryTypes.caption} as TextSearch]
} as ORSearchQuery;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.OR,
list: [{text: p.metadata.faces[0].name, type: SearchQueryTypes.person} as TextSearch,
{text: p2.metadata.caption, type: SearchQueryTypes.caption} as TextSearch]
} as ORSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.OR,
list: [{text: p.metadata.faces[0].name, type: SearchQueryTypes.person} as TextSearch,
{text: p.metadata.caption, type: SearchQueryTypes.caption} as TextSearch]
} as ORSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
// make sure that this shows both photos. We need this the the rest of the tests
query = ({text: 'a', type: SearchQueryTypes.person} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.OR,
list: [{
type: SearchQueryTypes.OR,
list: [{text: 'a', type: SearchQueryTypes.person} as TextSearch,
{text: p.metadata.keywords[0], type: SearchQueryTypes.keyword} as TextSearch]
} as ORSearchQuery,
{text: p.metadata.caption, type: SearchQueryTypes.caption} as TextSearch
]
} as ORSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.OR,
list: [{
type: SearchQueryTypes.OR,
list: [{text: p.metadata.keywords[0], type: SearchQueryTypes.keyword} as TextSearch,
{text: p2.metadata.keywords[0], type: SearchQueryTypes.keyword} as TextSearch]
} as ORSearchQuery,
{text: pFaceLess.metadata.caption, type: SearchQueryTypes.caption} as TextSearch
]
} as ORSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should minimum of', async () => {
const sm = new SearchManager();
let query: SomeOfSearchQuery = {
type: SearchQueryTypes.SOME_OF,
list: [{text: 'jpg', type: SearchQueryTypes.file_name} as TextSearch,
{text: 'mp4', type: SearchQueryTypes.file_name} as TextSearch]
} as SomeOfSearchQuery;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, p4, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.SOME_OF,
list: [{text: 'R2', type: SearchQueryTypes.person} as TextSearch,
{text: 'Anakin', type: SearchQueryTypes.person} as TextSearch,
{text: 'Luke', type: SearchQueryTypes.person} as TextSearch]
} as SomeOfSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query.min = 2;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query.min = 3;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
type: SearchQueryTypes.SOME_OF,
min: 3,
list: [{text: 'sw', type: SearchQueryTypes.file_name} as TextSearch,
{text: 'R2', type: SearchQueryTypes.person} as TextSearch,
{text: 'Kamino', type: SearchQueryTypes.position} as TextSearch,
{text: 'Han', type: SearchQueryTypes.person} as TextSearch]
} as SomeOfSearchQuery);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
describe('should search text', async () => {
it('as any', async () => {
const sm = new SearchManager();
let query = {text: 'sw', type: SearchQueryTypes.any_text} as TextSearch;
expect(Utils.clone(await sm.search({text: 'sw', type: SearchQueryTypes.any_text} as TextSearch)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, v, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({text: 'sw', negate: true, type: SearchQueryTypes.any_text} as TextSearch);
expect(removeDir(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({text: 'Boba', type: SearchQueryTypes.any_text} as TextSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({text: 'Boba', negate: true, type: SearchQueryTypes.any_text} as TextSearch);
expect(removeDir(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p2, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({text: 'Boba', negate: true, type: SearchQueryTypes.any_text} as TextSearch);
// all should have faces
const sRet = await sm.search(query);
for (const item of sRet.media) {
if (item.id === pFaceLess.id) {
continue;
}
expect((item as PhotoDTO).metadata.faces).to.be.not.an('undefined');
expect((item as PhotoDTO).metadata.faces).to.be.lengthOf.above(1);
}
query = ({
text: 'Boba',
type: SearchQueryTypes.any_text,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({
text: 'Boba Fett',
type: SearchQueryTypes.any_text,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
});
it('as position', async () => {
const sm = new SearchManager();
const query = {text: 'Tatooine', type: SearchQueryTypes.position} as TextSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('as keyword', async () => {
const sm = new SearchManager();
let query = {
text: 'kie',
type: SearchQueryTypes.keyword
} as TextSearch;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p2, pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'wa',
type: SearchQueryTypes.keyword
} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'han',
type: SearchQueryTypes.keyword
} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'star wars',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.keyword
} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'wookiees',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.keyword
} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('as caption', async () => {
const sm = new SearchManager();
const query = {
text: 'han',
type: SearchQueryTypes.caption
} as TextSearch;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('as file_name', async () => {
const sm = new SearchManager();
let query = {
text: 'sw',
type: SearchQueryTypes.file_name
} as TextSearch;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, v, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'sw4',
type: SearchQueryTypes.file_name
} as TextSearch);
expect(Utils.clone(await sm.search({
text: 'sw4',
type: SearchQueryTypes.file_name
} as TextSearch))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('as directory', async () => {
const sm = new SearchManager();
let query = {
text: 'of the J',
type: SearchQueryTypes.directory
} as TextSearch;
expect(removeDir(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({
text: 'wars dir',
type: SearchQueryTypes.directory
} as TextSearch);
expect(removeDir(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, v, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({
text: '/wars dir',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.directory
} as TextSearch);
expect(removeDir(await sm.search({
text: '/wars dir',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.directory
} as TextSearch))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({
text: '/wars dir/Return of the Jedi',
// matchType: TextSearchQueryMatchTypes.like,
type: SearchQueryTypes.directory
} as TextSearch);
expect(removeDir(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
query = ({
text: '/wars dir/Return of the Jedi',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.directory
} as TextSearch);
expect(removeDir(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO), JSON.stringify(query));
});
it('as person', async () => {
const sm = new SearchManager();
let query = {
text: 'Boba',
type: SearchQueryTypes.person
} as TextSearch;
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'Boba',
type: SearchQueryTypes.person,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch);
expect(Utils.clone(await sm.search(query))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
text: 'Boba Fett',
type: SearchQueryTypes.person,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch);
expect(Utils.clone(await sm.search({
text: 'Boba Fett',
type: SearchQueryTypes.person,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch))).to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
});
it('should search date', async () => {
const sm = new SearchManager();
let query: any = {value: 0, type: SearchQueryTypes.to_date} as ToDateSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
value: p.metadata.creationDate, type: SearchQueryTypes.from_date
} as FromDateSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
value: p.metadata.creationDate,
negate: true,
type: SearchQueryTypes.from_date
} as FromDateSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p2, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
value: p.metadata.creationDate + 1000000000,
type: SearchQueryTypes.to_date
} as ToDateSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, v, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should search rating', async () => {
const sm = new SearchManager();
let query: MinRatingSearch | MaxRatingSearch = {value: 0, type: SearchQueryTypes.max_rating} as MaxRatingSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 5, type: SearchQueryTypes.max_rating} as MaxRatingSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 5, negate: true, type: SearchQueryTypes.max_rating} as MaxRatingSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 2, type: SearchQueryTypes.min_rating} as MinRatingSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p2, pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 2, negate: true, type: SearchQueryTypes.min_rating} as MinRatingSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should search resolution', async () => {
const sm = new SearchManager();
let query: MinResolutionSearch | MaxResolutionSearch =
{value: 0, type: SearchQueryTypes.max_resolution} as MaxResolutionSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 1, type: SearchQueryTypes.max_resolution} as MaxResolutionSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 3, type: SearchQueryTypes.min_resolution} as MinResolutionSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 3, negate: true, type: SearchQueryTypes.min_resolution} as MinResolutionSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, pFaceLess, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({value: 3, negate: true, type: SearchQueryTypes.max_resolution} as MaxResolutionSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should search orientation', async () => {
const sm = new SearchManager();
let query = {
landscape: false,
type: SearchQueryTypes.orientation
} as OrientationSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, p4, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
landscape: true,
type: SearchQueryTypes.orientation
} as OrientationSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, pFaceLess, v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('should search distance', async () => {
ObjectManagers.getInstance().LocationManager = new LocationManager();
const sm = new SearchManager();
ObjectManagers.getInstance().LocationManager.getGPSData = async (): Promise<GPSMetadata> => {
return {
longitude: 10,
latitude: 10,
altitude: 0
};
};
let query = {
from: {text: 'Tatooine'},
distance: 1,
type: SearchQueryTypes.distance
} as DistanceSearch;
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
from: {GPSData: {latitude: 0, longitude: 0}},
distance: 112 * 10, // number of km per degree = ~111km
type: SearchQueryTypes.distance
} as DistanceSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
from: {GPSData: {latitude: 0, longitude: 0}},
distance: 112 * 10, // number of km per degree = ~111km
negate: true,
type: SearchQueryTypes.distance
} as DistanceSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
from: {GPSData: {latitude: 10, longitude: 10}},
distance: 1,
type: SearchQueryTypes.distance
} as DistanceSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
query = ({
from: {GPSData: {latitude: 10, longitude: 10}},
distance: 112 * 5, // number of km per degree = ~111km
type: SearchQueryTypes.distance
} as DistanceSearch);
expect(Utils.clone(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, pFaceLess, p4],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
/**
* flattenSameOfQueries converts converts some-of querries to AND and OR queries
* E.g.:
* 2-of:(A B C) to (A and (B or C)) or (B and C)
* this tests makes sure that all queries has at least 2 constraints
*/
(it('should flatter SOME_OF query', () => {
const sm = new SearchManagerTest();
const parser = new SearchQueryParser();
const alphabet = 'abcdefghijklmnopqrstu';
const shortestDepth = (q: SearchQueryDTO): number => {
let depth = 0;
if ((q as SearchListQuery).list) {
if (q.type === SearchQueryTypes.AND) {
for (const l of (q as SearchListQuery).list) {
depth += shortestDepth(l);
}
return depth;
}
// its an or
const lengths = (q as SearchListQuery).list.map(l => shortestDepth(l)).sort();
if (lengths[0] !== lengths[lengths.length - 1]) {
for (const l of (q as SearchListQuery).list) {
}
}
return lengths[0];
}
return 1;
};
const checkBoolLogic = (q: SearchQueryDTO) => {
if ((q as SearchListQuery).list) {
expect((q as SearchListQuery).list).to.not.equal(1);
for (const l of (q as SearchListQuery).list) {
checkBoolLogic(l);
}
}
};
// tslint:disable-next-line:prefer-for-of
for (let i = 1; i < alphabet.length / 2; ++i) {
const query: SomeOfSearchQuery = {
type: SearchQueryTypes.SOME_OF,
min: i,
//
list: alphabet.split('').map(t => ({
type: SearchQueryTypes.file_name,
text: t
} as TextSearch))
};
const q = sm.flattenSameOfQueries(query);
expect(shortestDepth(q)).to.equal(i, parser.stringify(query) + '\n' + parser.stringify(q));
checkBoolLogic(q);
}
}) as any).timeout(20000);
(it('should execute complex SOME_OF query', async () => {
const sm = new SearchManager();
const query: SomeOfSearchQuery = {
type: SearchQueryTypes.SOME_OF,
min: 5,
//
list: 'abcdefghijklmnopqrstu'.split('').map(t => ({
type: SearchQueryTypes.file_name,
text: t
} as TextSearch))
};
expect(removeDir(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [v],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
}) as any).timeout(40000);
it('search result should return directory', async () => {
Config.Client.Search.listDirectories = true;
const sm = new SearchManager();
const query = {
text: subDir.name,
type: SearchQueryTypes.any_text
} as TextSearch;
expect(removeDir(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [subDir],
media: [pFaceLess],
metaFile: [],
resultOverflow: false
} as SearchResultDTO));
});
it('search result should return meta files', async () => {
Config.Client.Search.listMetafiles = true;
const sm = new SearchManager();
const query = {
text: dir.name,
type: SearchQueryTypes.any_text,
matchType: TextSearchQueryMatchTypes.exact_match
} as TextSearch;
expect(removeDir(await sm.search(query)))
.to.deep.equalInAnyOrder(removeDir({
searchQuery: query,
directories: [],
media: [p, p2, v],
metaFile: [gpx],
resultOverflow: false
} as SearchResultDTO));
});
});
it('should get random photo', async () => {
const sm = new SearchManager();
let query = {
text: 'xyz',
type: SearchQueryTypes.keyword
} as TextSearch;
// tslint:disable-next-line
expect(await sm.getRandomPhoto(query)).to.not.exist;
query = ({
text: 'wookiees',
matchType: TextSearchQueryMatchTypes.exact_match,
type: SearchQueryTypes.keyword
} as TextSearch);
expect(Utils.clone(await sm.getRandomPhoto(query))).to.deep.equalInAnyOrder(searchifyMedia(pFaceLess));
});
}); | the_stack |
import {
OrganizationRequest,
RequestParams,
Role,
Roles,
UpdateMembersRequest,
UserPayload,
} from '@compito/api-interfaces';
import {
ConflictException,
ForbiddenException,
HttpException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
import { CompitoLoggerService } from '../core/utils/logger.service';
import { getUserDetails } from '../core/utils/payload.util';
import { parseQuery } from '../core/utils/query-parse.util';
import { PrismaService } from '../prisma.service';
import { USER_BASIC_DETAILS } from '../task/task.config';
@Injectable()
export class OrganizationService {
private logger = this.compitoLogger.getLogger('ORG');
constructor(private prisma: PrismaService, private compitoLogger: CompitoLoggerService) {}
async create(data: OrganizationRequest, user: UserPayload) {
const { userId } = getUserDetails(user);
let role: Role;
try {
role = await this.prisma.role.findFirst({
where: {
name: 'super-admin',
},
rejectOnNotFound: true,
});
} catch (error) {
this.logger.error('create', 'Failed to fetch the roles', error);
throw new InternalServerErrorException('Failed to create org!');
}
try {
let members = [];
if (data.members?.length > 0) {
members = data.members.map((id) => ({ id }));
if (!data.members.includes(userId)) {
members.push({ id: userId });
}
} else {
members.push({ id: userId });
}
const orgData: Prisma.OrganizationCreateInput = {
name: data.name,
slug: data.slug,
createdBy: {
connect: {
id: userId,
},
},
userRoleOrgs: {
create: {
roleId: role.id,
userId,
},
},
members: {
connect: members,
},
};
return await this.prisma.organization.create({
data: orgData,
include: {
userRoleOrgs: {
where: {
userId,
},
select: {
role: {
select: {
label: true,
},
},
},
},
},
});
} catch (error) {
this.logger.error('create', 'Failed to create org', error);
throw new InternalServerErrorException();
}
}
async findAll(query: RequestParams, user: UserPayload) {
const { userId } = getUserDetails(user);
const { skip, limit, sort = 'createdAt', order = 'asc' } = parseQuery(query);
const where: Prisma.OrganizationWhereInput = {
OR: [
{
createdById: userId,
},
{
members: {
some: {
id: userId,
},
},
},
],
};
try {
const count$ = this.prisma.organization.count({
where,
});
const orgs$ = this.prisma.organization.findMany({
where,
skip,
take: limit,
orderBy: {
[sort]: order,
},
include: {
userRoleOrgs: {
where: {
userId,
},
select: {
role: {
select: {
label: true,
},
},
},
},
},
});
const [payload, count] = await Promise.all([orgs$, count$]);
return {
payload,
meta: {
count,
},
};
} catch (error) {
this.logger.error('findAll', 'Failed to fetch orgs', error);
throw new InternalServerErrorException();
}
}
async findOne(id: string, user: UserPayload) {
const { userId, role } = getUserDetails(user);
const findOptions: Prisma.OrganizationFindFirstArgs = {
where: {
id,
},
select: {
id: true,
createdAt: true,
updatedAt: true,
createdBy: {
select: USER_BASIC_DETAILS,
},
members: {
select: USER_BASIC_DETAILS,
},
boards: true,
name: true,
projects: {
include: {
members: {
select: USER_BASIC_DETAILS,
},
},
},
slug: true,
tags: true,
tasks: true,
},
};
switch (role.name as Roles) {
case 'user':
case 'project-admin': {
try {
const userData = await this.prisma.user.findUnique({
where: {
id: userId,
},
select: {
projects: {
where: {},
select: {
id: true,
members: {
select: { id: true },
},
},
},
},
});
const membersOfProjectsUserHaveAccessTo = userData.projects.reduce((acc: string[], curr) => {
return [...acc, ...curr.members.map((member) => member?.id)];
}, []);
/**
* Only orgs he is part or owner of
*/
findOptions.where = {
id,
OR: [
{
members: {
some: {
id: userId,
},
},
},
{
createdById: userId,
},
],
};
(findOptions.select.projects as Prisma.ProjectFindManyArgs).where = {
members: {
some: {
id: userId,
},
},
};
/**
* Return only members of projects the user is part of
*/
findOptions.select.members = {
select: USER_BASIC_DETAILS,
where: {
id: {
in: membersOfProjectsUserHaveAccessTo,
},
},
};
} catch (error) {
if (error?.name === 'NotFoundError') {
this.logger.error('findOne', 'User not found', error);
}
this.logger.error('findOne', 'Something went wrong', error);
throw new InternalServerErrorException('Something went wrong');
}
break;
}
case 'org-admin':
case 'admin': {
/**
* Only orgs he is part of or owner of
*/
findOptions.where = {
id,
OR: [
{
members: {
some: {
id: userId,
},
},
},
{
createdById: userId,
},
],
};
break;
}
}
try {
const org = await this.prisma.organization.findFirst(findOptions);
if (org) {
return org;
}
this.logger.error('findOne', 'Org not found');
throw new NotFoundException('Org not found');
} catch (error) {
this.logger.error('findOne', 'Failed to fetch org', error);
throw new InternalServerErrorException();
}
}
async update(id: string, data: OrganizationRequest, user: UserPayload) {
const { userId, role } = getUserDetails(user);
const where: Prisma.OrganizationWhereUniqueInput = {
id,
};
await this.canUpdateOrg(userId, id, role.name as Roles);
const { members, createdById, ...rest } = data;
try {
const org = await this.prisma.organization.update({
where,
data: rest,
});
if (org) {
return org;
}
throw new NotFoundException();
} catch (error) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === 'P2025') {
this.logger.error('update', 'Org not found', error);
throw new NotFoundException();
}
}
this.logger.error('update', 'Failed to update org', error);
throw new InternalServerErrorException();
}
}
async updateMembers(id: string, data: UpdateMembersRequest, user: UserPayload) {
const { userId, role } = getUserDetails(user);
await this.canUpdateOrg(userId, id, role.name as Roles);
try {
let updateData: Prisma.OrganizationUpdateInput = {};
switch (data.type) {
case 'modify':
{
const itemsToRemove = data?.remove?.length > 0 ? data.remove.map((item) => ({ id: item })) : [];
const itemsToAdd = data?.add?.length > 0 ? data.add.map((item) => ({ id: item })) : [];
updateData = {
members: {
disconnect: itemsToRemove,
connect: itemsToAdd,
},
};
}
break;
case 'set':
{
const itemsToSet = data?.set.length > 0 ? data.set.map((item) => ({ id: item })) : [];
updateData = {
members: {
set: itemsToSet,
},
};
}
break;
}
const project = await this.prisma.organization.update({
where: {
id,
},
data: updateData,
select: {
id: true,
createdAt: true,
updatedAt: true,
members: {
select: USER_BASIC_DETAILS,
},
boards: true,
name: true,
projects: true,
slug: true,
tags: true,
tasks: true,
},
});
if (project) {
return project;
}
throw new NotFoundException();
} catch (error) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === 'P2025') {
this.logger.error('updateMembers', 'Org not found', error);
throw new NotFoundException();
}
}
if (error instanceof HttpException) {
throw error;
}
this.logger.error('updateMembers', 'Failed to update members', error);
throw new InternalServerErrorException();
}
}
async remove(id: string, user: UserPayload) {
const { userId, role } = getUserDetails(user);
await this.canDeleteOrg(userId, id, role.name as Roles);
try {
await this.prisma.$transaction([
this.prisma.userRoleOrg.deleteMany({
where: {
userId,
orgId: id,
},
}),
this.prisma.organization.delete({
where: {
id,
},
}),
]);
} catch (error) {
this.logger.error('Failed to delete org', error);
throw new InternalServerErrorException();
}
}
private canUpdateOrg = async (userId: string, orgId: string, role: Roles) => {
const orgData = await this.getOrgDetail(orgId);
switch (role) {
/**
* Can update the org if:
* 1. Created by the user
* 2. Is part of the org
*/
case 'admin':
case 'org-admin': {
if (orgData.createdById !== userId || orgData.members.findIndex(({ id }) => id === userId) < 0) {
this.logger.error('canUpdate', 'User not part of the org');
throw new ForbiddenException('No permission to update the org');
}
break;
}
/**
* Can update the org if:
* 1. Created by the user
*/
case 'user':
case 'project-admin': {
if (orgData.createdById !== userId) {
this.logger.error('canUpdate', 'User has not permission');
throw new ForbiddenException('No permission to update the org');
}
break;
}
}
return orgData;
};
private canDeleteOrg = async (userId: string, orgId: string, role: Roles) => {
const orgData = await this.getOrgDetail(orgId);
switch (role) {
/**
* Can delete all orgs
*/
case 'super-admin':
case 'admin': {
if (orgData.projects.length > 0) {
this.logger.error('canDelete', 'Org contains live projects');
throw new ConflictException('Cannot delete org as it contains projects.');
}
if (orgData.createdById !== userId || orgData.members.findIndex(({ id }) => id === userId) < 0) {
this.logger.error('canDelete', 'User not owner or is part of the org');
throw new ForbiddenException('No permission to delete the org');
}
break;
}
/**
* Can delete the org if:
* 1. Created by the user
*/
default:
if (orgData.createdById !== userId) {
this.logger.error('canDelete', 'User has no permission');
throw new ForbiddenException('No permission to delete the org');
}
break;
}
return orgData;
};
private async getOrgDetail(orgId) {
try {
return await this.prisma.organization.findUnique({
where: { id: orgId },
select: {
createdById: true,
projects: true,
members: {
select: { id: true },
},
},
rejectOnNotFound: true,
});
} catch (error) {
if (error?.name === 'NotFoundError') {
this.logger.error('getOrgDetail', 'Org not found', error);
throw new NotFoundException('Org not found');
}
this.logger.error('getOrgDetail', 'Something went wrong', error);
throw new InternalServerErrorException('Something went wrong');
}
}
} | the_stack |
namespace Harness.SourceMapRecorder {
interface SourceMapSpanWithDecodeErrors {
sourceMapSpan: ts.Mapping;
decodeErrors: string[] | undefined;
}
namespace SourceMapDecoder {
let sourceMapMappings: string;
let decodingIndex: number;
let mappings: ts.MappingsDecoder | undefined;
export interface DecodedMapping {
sourceMapSpan: ts.Mapping;
error?: string;
}
export function initializeSourceMapDecoding(sourceMap: ts.RawSourceMap) {
decodingIndex = 0;
sourceMapMappings = sourceMap.mappings;
mappings = ts.decodeMappings(sourceMap.mappings);
}
export function decodeNextEncodedSourceMapSpan(): DecodedMapping {
if (!mappings) return ts.Debug.fail("not initialized");
const result = mappings.next();
if (result.done) return { error: mappings.error || "No encoded entry found", sourceMapSpan: mappings.state };
return { sourceMapSpan: result.value };
}
export function hasCompletedDecoding() {
if (!mappings) return ts.Debug.fail("not initialized");
return mappings.pos === sourceMapMappings.length;
}
export function getRemainingDecodeString() {
return sourceMapMappings.substr(decodingIndex);
}
}
namespace SourceMapSpanWriter {
let sourceMapRecorder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[] | null | undefined;
let jsFile: documents.TextDocument;
let jsLineMap: readonly number[];
let tsCode: string;
let tsLineMap: number[];
let spansOnSingleLine: SourceMapSpanWithDecodeErrors[];
let prevWrittenSourcePos: number;
let nextJsLineToWrite: number;
let spanMarkerContinues: boolean;
export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMap: ts.RawSourceMap, currentJsFile: documents.TextDocument) {
sourceMapRecorder = sourceMapRecordWriter;
sourceMapSources = sourceMap.sources;
sourceMapNames = sourceMap.names;
jsFile = currentJsFile;
jsLineMap = jsFile.lineStarts;
spansOnSingleLine = [];
prevWrittenSourcePos = 0;
nextJsLineToWrite = 0;
spanMarkerContinues = false;
SourceMapDecoder.initializeSourceMapDecoding(sourceMap);
sourceMapRecorder.WriteLine("===================================================================");
sourceMapRecorder.WriteLine("JsFile: " + sourceMap.file);
sourceMapRecorder.WriteLine("mapUrl: " + ts.tryGetSourceMappingURL(ts.getLineInfo(jsFile.text, jsLineMap)));
sourceMapRecorder.WriteLine("sourceRoot: " + sourceMap.sourceRoot);
sourceMapRecorder.WriteLine("sources: " + sourceMap.sources);
if (sourceMap.sourcesContent) {
sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMap.sourcesContent));
}
sourceMapRecorder.WriteLine("===================================================================");
}
function getSourceMapSpanString(mapEntry: ts.Mapping, getAbsentNameIndex?: boolean) {
let mapString = "Emitted(" + (mapEntry.generatedLine + 1) + ", " + (mapEntry.generatedCharacter + 1) + ")";
if (ts.isSourceMapping(mapEntry)) {
mapString += " Source(" + (mapEntry.sourceLine + 1) + ", " + (mapEntry.sourceCharacter + 1) + ") + SourceIndex(" + mapEntry.sourceIndex + ")";
if (mapEntry.nameIndex! >= 0 && mapEntry.nameIndex! < sourceMapNames!.length) {
mapString += " name (" + sourceMapNames![mapEntry.nameIndex!] + ")";
}
else {
if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) {
mapString += " nameIndex (" + mapEntry.nameIndex + ")";
}
}
}
return mapString;
}
export function recordSourceMapSpan(sourceMapSpan: ts.Mapping) {
// verify the decoded span is same as the new span
const decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
let decodeErrors: string[] | undefined;
if (typeof decodeResult.error === "string" || !ts.sameMapping(decodeResult.sourceMapSpan, sourceMapSpan)) {
if (decodeResult.error) {
decodeErrors = ["!!^^ !!^^ There was decoding error in the sourcemap at this location: " + decodeResult.error];
}
else {
decodeErrors = ["!!^^ !!^^ The decoded span from sourcemap's mapping entry does not match what was encoded for this span:"];
}
decodeErrors.push("!!^^ !!^^ Decoded span from sourcemap's mappings entry: " + getSourceMapSpanString(decodeResult.sourceMapSpan, /*getAbsentNameIndex*/ true) + " Span encoded by the emitter:" + getSourceMapSpanString(sourceMapSpan, /*getAbsentNameIndex*/ true));
}
if (spansOnSingleLine.length && spansOnSingleLine[0].sourceMapSpan.generatedLine !== sourceMapSpan.generatedLine) {
// On different line from the one that we have been recording till now,
writeRecordedSpans();
spansOnSingleLine = [];
}
spansOnSingleLine.push({ sourceMapSpan, decodeErrors });
}
export function recordNewSourceFileSpan(sourceMapSpan: ts.Mapping, newSourceFileCode: string) {
let continuesLine = false;
if (spansOnSingleLine.length > 0 && spansOnSingleLine[0].sourceMapSpan.generatedCharacter === sourceMapSpan.generatedLine) {
writeRecordedSpans();
spansOnSingleLine = [];
nextJsLineToWrite--; // walk back one line to reprint the line
continuesLine = true;
}
recordSourceMapSpan(sourceMapSpan);
assert.isTrue(spansOnSingleLine.length === 1);
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("emittedFile:" + jsFile.file + (continuesLine ? ` (${sourceMapSpan.generatedLine + 1}, ${sourceMapSpan.generatedCharacter + 1})` : ""));
sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex!]);
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
tsLineMap = ts.computeLineStarts(newSourceFileCode);
tsCode = newSourceFileCode;
prevWrittenSourcePos = 0;
}
export function close() {
// Write the lines pending on the single line
writeRecordedSpans();
if (!SourceMapDecoder.hasCompletedDecoding()) {
sourceMapRecorder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded");
sourceMapRecorder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString());
}
// write remaining js lines
writeJsFileLines(jsLineMap.length);
}
function getTextOfLine(line: number, lineMap: readonly number[], code: string) {
const startPos = lineMap[line];
const endPos = lineMap[line + 1];
const text = code.substring(startPos, endPos);
return line === 0 ? Utils.removeByteOrderMark(text) : text;
}
function writeJsFileLines(endJsLine: number) {
for (; nextJsLineToWrite < endJsLine; nextJsLineToWrite++) {
sourceMapRecorder.Write(">>>" + getTextOfLine(nextJsLineToWrite, jsLineMap, jsFile.text));
}
}
function writeRecordedSpans() {
const markerIds: string[] = [];
function getMarkerId(markerIndex: number) {
let markerId = "";
if (spanMarkerContinues) {
assert.isTrue(markerIndex === 0);
markerId = "1->";
}
else {
markerId = "" + (markerIndex + 1);
if (markerId.length < 2) {
markerId = markerId + " ";
}
markerId += ">";
}
return markerId;
}
let prevEmittedCol!: number;
function iterateSpans(fn: (currentSpan: SourceMapSpanWithDecodeErrors, index: number) => void) {
prevEmittedCol = 0;
for (let i = 0; i < spansOnSingleLine.length; i++) {
fn(spansOnSingleLine[i], i);
prevEmittedCol = spansOnSingleLine[i].sourceMapSpan.generatedCharacter;
}
}
function writeSourceMapIndent(indentLength: number, indentPrefix: string) {
sourceMapRecorder.Write(indentPrefix);
for (let i = 0; i < indentLength; i++) {
sourceMapRecorder.Write(" ");
}
}
function writeSourceMapMarker(currentSpan: SourceMapSpanWithDecodeErrors, index: number, endColumn = currentSpan.sourceMapSpan.generatedCharacter, endContinues = false) {
const markerId = getMarkerId(index);
markerIds.push(markerId);
writeSourceMapIndent(prevEmittedCol, markerId);
for (let i = prevEmittedCol; i < endColumn; i++) {
sourceMapRecorder.Write("^");
}
if (endContinues) {
sourceMapRecorder.Write("->");
}
sourceMapRecorder.WriteLine("");
spanMarkerContinues = endContinues;
}
function writeSourceMapSourceText(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
const sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine!] + (currentSpan.sourceMapSpan.sourceCharacter!);
let sourceText = "";
if (prevWrittenSourcePos < sourcePos) {
// Position that goes forward, get text
sourceText = tsCode.substring(prevWrittenSourcePos, sourcePos);
}
if (currentSpan.decodeErrors) {
// If there are decode errors, write
for (const decodeError of currentSpan.decodeErrors) {
writeSourceMapIndent(prevEmittedCol, markerIds[index]);
sourceMapRecorder.WriteLine(decodeError);
}
}
const tsCodeLineMap = ts.computeLineStarts(sourceText);
for (let i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecorder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i === tsCodeLineMap.length - 1) {
sourceMapRecorder.WriteLine("");
}
}
prevWrittenSourcePos = sourcePos;
}
function writeSpanDetails(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
sourceMapRecorder.WriteLine(markerIds[index] + getSourceMapSpanString(currentSpan.sourceMapSpan));
}
if (spansOnSingleLine.length) {
const currentJsLine = spansOnSingleLine[0].sourceMapSpan.generatedLine;
// Write js line
writeJsFileLines(currentJsLine + 1);
// Emit markers
iterateSpans(writeSourceMapMarker);
const jsFileText = getTextOfLine(currentJsLine + 1, jsLineMap, jsFile.text);
if (prevEmittedCol < jsFileText.length - 1) {
// There is remaining text on this line that will be part of next source span so write marker that continues
writeSourceMapMarker(/*currentSpan*/ undefined!, spansOnSingleLine.length, /*endColumn*/ jsFileText.length - 1, /*endContinues*/ true); // TODO: GH#18217
}
// Emit Source text
iterateSpans(writeSourceMapSourceText);
// Emit column number etc
iterateSpans(writeSpanDetails);
sourceMapRecorder.WriteLine("---");
}
}
}
export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitResult[], program: ts.Program, jsFiles: readonly documents.TextDocument[], declarationFiles: readonly documents.TextDocument[]) {
const sourceMapRecorder = new Compiler.WriterAggregator();
for (let i = 0; i < sourceMapDataList.length; i++) {
const sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile | undefined;
let currentFile: documents.TextDocument;
if (ts.endsWith(sourceMapData.sourceMap.file, ts.Extension.Dts)) {
if (sourceMapDataList.length > jsFiles.length) {
currentFile = declarationFiles[Math.floor(i / 2)]; // When both kinds of source map are present, they alternate js/dts
}
else {
currentFile = declarationFiles[i];
}
}
else {
if (sourceMapDataList.length > jsFiles.length) {
currentFile = jsFiles[Math.floor(i / 2)];
}
else {
currentFile = jsFiles[i];
}
}
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData.sourceMap, currentFile);
const mapper = ts.decodeMappings(sourceMapData.sourceMap.mappings);
for (let iterResult = mapper.next(); !iterResult.done; iterResult = mapper.next()) {
const decodedSourceMapping = iterResult.value;
const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
? program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex])
: undefined;
if (currentSourceFile !== prevSourceFile) {
if (currentSourceFile) {
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
}
prevSourceFile = currentSourceFile;
}
else {
SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
}
}
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecorder.Close();
return sourceMapRecorder.lines.join("\r\n");
}
export function getSourceMapRecordWithSystem(sys: ts.System, sourceMapFile: string) {
const sourceMapRecorder = new Compiler.WriterAggregator();
let prevSourceFile: documents.TextDocument | undefined;
const files = new ts.Map<string, documents.TextDocument>();
const sourceMap = ts.tryParseRawSourceMap(sys.readFile(sourceMapFile, "utf8")!);
if (sourceMap) {
const mapDirectory = ts.getDirectoryPath(sourceMapFile);
const sourceRoot = sourceMap.sourceRoot ? ts.getNormalizedAbsolutePath(sourceMap.sourceRoot, mapDirectory) : mapDirectory;
const generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(sourceMap.file, mapDirectory);
const sourceFileAbsolutePaths = sourceMap.sources.map(source => ts.getNormalizedAbsolutePath(source, sourceRoot));
const currentFile = getFile(generatedAbsoluteFilePath);
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMap, currentFile);
const mapper = ts.decodeMappings(sourceMap.mappings);
for (let iterResult = mapper.next(); !iterResult.done; iterResult = mapper.next()) {
const decodedSourceMapping = iterResult.value;
const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
? getFile(sourceFileAbsolutePaths[decodedSourceMapping.sourceIndex])
: undefined;
if (currentSourceFile !== prevSourceFile) {
if (currentSourceFile) {
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
}
prevSourceFile = currentSourceFile;
}
else {
SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
}
}
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecorder.Close();
return sourceMapRecorder.lines.join("\r\n");
function getFile(path: string) {
const existing = files.get(path);
if (existing) return existing;
const value = new documents.TextDocument(path, sys.readFile(path, "utf8")!);
files.set(path, value);
return value;
}
}
} | the_stack |
import { Injectable } from '@nestjs/common';
import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as crypto from 'crypto';
import * as semver from 'semver';
import * as _ from 'lodash';
export interface HomebridgeConfig {
bridge: {
username: string;
pin: string;
name: string;
port: number;
advertiser?: 'ciao' | 'bonjour-hap';
bind?: string | string[];
};
mdns?: {
interface?: string | string[];
};
platforms: Record<string, any>[];
accessories: Record<string, any>[];
plugins?: string[];
disabledPlugins?: string[];
}
@Injectable()
export class ConfigService {
public name = 'homebridge-config-ui-x';
// homebridge env
public configPath = process.env.UIX_CONFIG_PATH || path.resolve(os.homedir(), '.homebridge/config.json');
public storagePath = process.env.UIX_STORAGE_PATH || path.resolve(os.homedir(), '.homebridge');
public customPluginPath = process.env.UIX_CUSTOM_PLUGIN_PATH;
public secretPath = path.resolve(this.storagePath, '.uix-secrets');
public authPath = path.resolve(this.storagePath, 'auth.json');
public accessoryLayoutPath = path.resolve(this.storagePath, 'accessories', 'uiAccessoriesLayout.json');
public configBackupPath = path.resolve(this.storagePath, 'backups/config-backups');
public instanceBackupPath = path.resolve(this.storagePath, 'backups/instance-backups');
public homebridgeInsecureMode = Boolean(process.env.UIX_INSECURE_MODE === '1');
public homebridgeNoTimestamps = Boolean(process.env.UIX_LOG_NO_TIMESTAMPS === '1');
public homebridgeVersion: string;
// server env
public minimumNodeVersion = '10.17.0';
public serviceMode = (process.env.UIX_SERVICE_MODE === '1');
public runningInDocker = Boolean(process.env.HOMEBRIDGE_CONFIG_UI === '1');
public runningInLinux = (!this.runningInDocker && os.platform() === 'linux');
public ableToConfigureSelf = (!this.runningInDocker || semver.satisfies(process.env.CONFIG_UI_VERSION, '>=3.5.5', { includePrerelease: true }));
public enableTerminalAccess = this.runningInDocker || Boolean(process.env.HOMEBRIDGE_CONFIG_UI_TERMINAL === '1');
// docker paths
public startupScript = path.resolve(this.storagePath, 'startup.sh');
public dockerEnvFile = path.resolve(this.storagePath, '.docker.env');
public dockerOfflineUpdate = this.runningInDocker && semver.satisfies(process.env.CONFIG_UI_VERSION, '>=4.6.2', { includePrerelease: true });
// package.json
public package = fs.readJsonSync(path.resolve(process.env.UIX_BASE_PATH, 'package.json'));
// custom wallpaper
public customWallpaperPath = path.resolve(this.storagePath, 'ui-wallpaper.jpg');
public customWallpaperHash: string;
// set true to force the ui to restart on next restart request
public hbServiceUiRestartRequired = false;
public homebridgeConfig: HomebridgeConfig;
public ui: {
name: string;
port: number;
host?: '::' | '0.0.0.0' | string;
auth: 'form' | 'none';
theme: string;
sudo?: boolean;
restart?: string;
lang?: string;
log?: {
method: 'file' | 'custom' | 'systemd' | 'native';
command?: string;
path?: string;
service?: string;
};
ssl?: {
key?: string;
cert?: string;
pfx?: string;
passphrase?: string;
};
accessoryControl?: {
debug?: boolean;
instanceBlacklist?: string[];
};
temp?: string;
tempUnits?: string;
loginWallpaper?: string;
noFork?: boolean;
linux?: {
shutdown?: string;
restart?: string;
};
standalone?: boolean;
debug?: boolean;
proxyHost?: string;
sessionTimeout?: number;
homebridgePackagePath?: string;
scheduledBackupPath?: string;
scheduledBackupDisable?: boolean;
disableServerMetricsMonitoring?: boolean;
};
private bridgeFreeze: this['homebridgeConfig']['bridge'];
private uiFreeze: this['ui'];
public secrets: {
secretKey: string;
};
public instanceId: string;
constructor() {
const homebridgeConfig = fs.readJSONSync(this.configPath);
this.parseConfig(homebridgeConfig);
}
/**
* Loads the config from the config.json
*/
public parseConfig(homebridgeConfig) {
this.homebridgeConfig = homebridgeConfig;
if (!this.homebridgeConfig.bridge) {
this.homebridgeConfig.bridge = {} as this['homebridgeConfig']['bridge'];
}
this.ui = Array.isArray(this.homebridgeConfig.platforms) ? this.homebridgeConfig.platforms.find(x => x.platform === 'config') : undefined as any;
if (!this.ui) {
this.ui = {
name: 'Config',
} as any;
}
process.env.UIX_PLUGIN_NAME = this.ui.name || 'homebridge-config-ui-x';
if (this.runningInDocker) {
this.setConfigForDocker();
}
if (this.serviceMode) {
this.setConfigForServiceMode();
}
if (!this.ui.port) {
this.ui.port = 8080;
}
if (!this.ui.sessionTimeout) {
this.ui.sessionTimeout = this.ui.auth === 'none' ? 1296000 : 28800;
}
if (this.ui.scheduledBackupPath) {
this.instanceBackupPath = this.ui.scheduledBackupPath;
} else {
this.instanceBackupPath = path.resolve(this.storagePath, 'backups/instance-backups');
}
this.secrets = this.getSecrets();
this.instanceId = this.getInstanceId();
this.freezeUiSettings();
this.getCustomWallpaperHash();
}
/**
* Settings that are sent to the UI
*/
public uiSettings() {
return {
env: {
ableToConfigureSelf: this.ableToConfigureSelf,
enableAccessories: this.homebridgeInsecureMode,
enableTerminalAccess: this.enableTerminalAccess,
homebridgeVersion: this.homebridgeVersion || null,
homebridgeInstanceName: this.homebridgeConfig.bridge.name,
nodeVersion: process.version,
packageName: this.package.name,
packageVersion: this.package.version,
platform: os.platform(),
runningInDocker: this.runningInDocker,
runningInLinux: this.runningInLinux,
dockerOfflineUpdate: this.dockerOfflineUpdate,
serviceMode: this.serviceMode,
temperatureUnits: this.ui.tempUnits || 'c',
lang: this.ui.lang === 'auto' ? null : this.ui.lang,
instanceId: this.instanceId,
customWallpaperHash: this.customWallpaperHash,
},
formAuth: Boolean(this.ui.auth !== 'none'),
theme: this.ui.theme || 'auto',
serverTimestamp: new Date().toISOString(),
};
}
/**
* Checks to see if the UI requires a restart due to changed ui or bridge settings
*/
public async uiRestartRequired(): Promise<boolean> {
// if the flag is set, force a restart
if (this.hbServiceUiRestartRequired) {
return true;
}
// if the ui version has changed on disk, a restart is required
const currentPackage = await fs.readJson(path.resolve(process.env.UIX_BASE_PATH, 'package.json'));
if (currentPackage.version !== this.package.version) {
return true;
}
// if the ui or bridge config has changed, a restart is required
return !(_.isEqual(this.ui, this.uiFreeze) && _.isEqual(this.homebridgeConfig.bridge, this.bridgeFreeze));
}
/**
* Freeze a copy of the initial ui config and homebridge port
*/
private freezeUiSettings() {
if (!this.uiFreeze) {
// freeze ui
this.uiFreeze = {} as this['ui'];
Object.assign(this.uiFreeze, this.ui);
}
if (!this.bridgeFreeze) {
// freeze bridge port
this.bridgeFreeze = {} as this['homebridgeConfig']['bridge'];
Object.assign(this.bridgeFreeze, this.homebridgeConfig.bridge);
}
}
/**
* Populate the required config for oznu/homebridge docker
*/
private setConfigForDocker() {
// forced config
this.ui.restart = 'killall -15 homebridge; sleep 5.1; killall -9 homebridge; kill -9 $(pidof homebridge-config-ui-x);';
this.homebridgeInsecureMode = Boolean(process.env.HOMEBRIDGE_INSECURE === '1');
this.ui.sudo = false;
this.ui.log = {
method: 'file',
path: '/homebridge/logs/homebridge.log',
};
// these options can be overridden using the config.json file
if (!this.ui.port && process.env.HOMEBRIDGE_CONFIG_UI_PORT) {
this.ui.port = parseInt(process.env.HOMEBRIDGE_CONFIG_UI_PORT, 10);
}
this.ui.theme = this.ui.theme || process.env.HOMEBRIDGE_CONFIG_UI_THEME || 'auto';
this.ui.auth = this.ui.auth || process.env.HOMEBRIDGE_CONFIG_UI_AUTH as 'form' | 'none' || 'form';
this.ui.loginWallpaper = this.ui.loginWallpaper || process.env.HOMEBRIDGE_CONFIG_UI_LOGIN_WALLPAPER || undefined;
}
/**
* Populate the required config when running in "Service Mode"
*/
private setConfigForServiceMode() {
this.homebridgeInsecureMode = Boolean(process.env.UIX_INSECURE_MODE === '1');
this.ui.restart = undefined;
this.ui.sudo = (os.platform() === 'linux' && !this.runningInDocker);
this.ui.log = {
method: 'native',
path: path.resolve(this.storagePath, 'homebridge.log'),
};
}
/**
* Gets the unique secrets for signing JWTs
*/
private getSecrets() {
if (fs.pathExistsSync(this.secretPath)) {
try {
const secrets = fs.readJsonSync(this.secretPath);
if (!secrets.secretKey) {
return this.generateSecretToken();
} else {
return secrets;
}
} catch (e) {
return this.generateSecretToken();
}
} else {
return this.generateSecretToken();
}
}
/**
* Generates the secret token for signing JWTs
*/
private generateSecretToken() {
const secrets = {
secretKey: crypto.randomBytes(32).toString('hex'),
};
fs.writeJsonSync(this.secretPath, secrets);
return secrets;
}
/**
* Generates a public instance id from a sha256 has of the secret key
*/
private getInstanceId(): string {
return crypto.createHash('sha256').update(this.secrets.secretKey).digest('hex');
}
/**
* Checks to see if custom wallpaper has been set, and generate a sha256 hash to use as the file name
*/
private async getCustomWallpaperHash(): Promise<void> {
try {
const stat = await fs.stat(this.ui.loginWallpaper || this.customWallpaperPath);
const hash = crypto.createHash('sha256');
hash.update(`${stat.birthtime}${stat.ctime}${stat.size}${stat.blocks}`);
this.customWallpaperHash = hash.digest('hex') + '.jpg';
} catch (e) {
// do nothing
}
}
/**
* Stream the custom wallpaper
*/
public streamCustomWallpaper(): fs.ReadStream {
return fs.createReadStream(this.ui.loginWallpaper || this.customWallpaperPath);
}
} | the_stack |
import React from 'react';
import Page from '../Page';
import useToolkit from '../toolkit/useToolkit';
import selectableTextConfig from './cards/selectableTextConfig';
export default function PageFAQ() {
const {
Acronym,
Admonition,
Bold,
Header,
Paragraph,
Chapter,
SourceDisplay,
RefLibrary,
RefRNSymbol,
RefHtmlElement,
RefCssProperty,
RefRenderHtmlProp,
RefRenderHTMLExport,
RefTRE,
RefHtmlAttr,
RefDoc,
RenderHtmlCard,
Section,
InlineCode,
Hyperlink,
List,
ListItem,
SvgFigure
} = useToolkit();
return (
<Page>
<Chapter title="How To">
<Section title="How to intercept press events on links?">
<Paragraph>
Use <InlineCode>renderersProps.a.onPress</InlineCode>, see{' '}
<Hyperlink url="https://stackoverflow.com/q/63114501/2779871">
Stack Overflow | How to open the browser when a link is pressed?
</Hyperlink>{' '}
and <RefRenderHTMLExport name="RenderersProps" member="a" full />.
</Paragraph>
</Section>
<Section title="I want to use a custom component to render some tags, how to do that?">
<Paragraph>
You can define custom renderers for that purpose. See{' '}
<RefDoc target="custom-renderers" />.
</Paragraph>
</Section>
<Section title="How to access the raw HTML from a custom renderer?">
<Paragraph>
Use <RefRenderHTMLExport name="domNodeToHTMLString" /> utility. See{' '}
<Hyperlink url="https://stackoverflow.com/q/63979897/2779871">
Stack Overflow | Extract raw HTML in react-native-render-html
custom renderers
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="How to render iframes?">
<Paragraph>
That's really a piece of cake. See{' '}
<Hyperlink url="https://github.com/native-html/plugins/tree/master/packages/iframe-plugin#readme">
@native-html/iframe-plugin
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="How to set the default font size and family?">
<Paragraph>
You should use <RefRenderHtmlProp name="baseStyle" /> prop.
</Paragraph>
</Section>
<Section title="How to render inline images?">
<Paragraph>
See this example from the docs:{' '}
<RefDoc
fragment="example-displaying-inline-images"
target="custom-renderers">
Example: Displaying Inline Images
</RefDoc>
.
</Paragraph>
</Section>
<Section title="Aren't there better renderers for tables?">
<Paragraph>
Sure! The default renderer is very limitted. Check-out{' '}
<Hyperlink url="https://github.com/native-html/plugins/tree/master/packages/table-plugin#readme">
@native-html/table-plugin
</Hyperlink>{' '}
and{' '}
<Hyperlink url="https://github.com/native-html/plugins/tree/master/packages/heuristic-table-plugin#readme">
@native-html/heuristic-table-plugin
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="How can I make textual content selectable?">
<Paragraph>
You can take advantage of{' '}
<RefRenderHtmlProp name="defaultTextProps" /> prop to set{' '}
<InlineCode>selectable</InlineCode> to all{' '}
<RefRNSymbol name="Text" /> instances.
</Paragraph>
<RenderHtmlCard {...selectableTextConfig} />
<Paragraph>
However, the end-user won't be able to select across multiple
blocks: this is a limitation of React Native.
</Paragraph>
</Section>
</Chapter>
<Chapter title="Troubleshooting">
<Section title="Warning: You seem to update the X prop of the Y component in short periods of time...">
<Paragraph>
There is a detailed explaination for this warning here:{' '}
<Hyperlink url="https://stackoverflow.com/q/68966120/2779871">
Stack Overflow | react-native-render-html, "You seem to update
..."
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="Custom font families don't work, what's happening?">
<Paragraph>
You must register fonts available in your app with{' '}
<RefRenderHtmlProp name="systemFonts" /> prop. This feature is
called <Bold>font selection</Bold> and prevents native crashes
caused by missing fonts! See{' '}
<RefDoc target="textual" fragment="font-selection">
Font Selection
</RefDoc>
.
</Paragraph>
<Paragraph>
Also note that <InlineCode>fontWeight</InlineCode> and{' '}
<InlineCode>fontStyle</InlineCode> typefaces modifiers, which might
be set by default for some tags such as <RefHtmlElement name="h1" />
, will cause the font to be missed on Android if you haven't
registered your font with typefaces, e.g. via{' '}
<Hyperlink url="https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml">
XML fonts
</Hyperlink>
. See{' '}
<Hyperlink url="https://stackoverflow.com/a/70247374/2779871">
this StackOverflow answer for a step-by-step guide
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="Line breaks (<br>) seem to take up too much vertical space">
<Paragraph>
This is a known bug, but hopefully we have the{' '}
<RefRenderHtmlProp name="enableExperimentalBRCollapsing" /> prop to
fix it. See{' '}
<RefDoc target="textual" fragment="caveats">
Textual | Caveats | Line Breaks
</RefDoc>
.
</Paragraph>
</Section>
<Section title="Isolated empty textual tags take up vertical space">
<Paragraph>
This is another known bug, but hopefully we have the{' '}
<RefRenderHtmlProp name="enableExperimentalGhostLinesPrevention" />{' '}
prop to fix it. See{' '}
<RefDoc target="textual" fragment="caveats">
Textual | Caveats | Empty Tags
</RefDoc>
.
</Paragraph>
</Section>
<Section title="Content after custom tags is not displayed or displayed inside instead of below?">
<Paragraph>
That would often happen in the HTML markup when your custom tags is
self-closing such as in <InlineCode>{'<customtag />'}</InlineCode>.
The HTML5 standard strictly prohibits non-void elements to be
self-closing, and the required behavior for a parser is to ignore
the <InlineCode>{'/'}</InlineCode> character in that case. Abding by
this standard, the HTML parser will end up considering{' '}
<InlineCode>{'<customtag />'}</InlineCode> as equivlent to{' '}
<InlineCode>{'<customtag >'}</InlineCode>. Therefore, any content
below it will be considered as children of{' '}
<InlineCode>{'<customtag>'}</InlineCode>. Because it is forgiving,
the parser will close this tag when it reaches the end of the
stream. To overcome this issue, <Bold>you have two options</Bold>:
</Paragraph>
<List type="decimal">
<ListItem>
Replace <InlineCode>{'<customtag />'}</InlineCode> with{' '}
<InlineCode>{'<customtag></customtag>'}</InlineCode> in your HTML
markup.
</ListItem>
<ListItem>
Set <InlineCode>recognizeSelfClosing</InlineCode> option to{' '}
<InlineCode>true</InlineCode> in{' '}
<RefRenderHtmlProp name="htmlParserOptions" /> prop.
</ListItem>
</List>
</Section>
<Section title="Sub and sup tags are not vertically shifted">
<Paragraph>
This is caused by a known limitation in React Native.{' '}
<Hyperlink url="https://github.com/meliorence/react-native-render-html/issues/76#issuecomment-660702309">
The issue is being tracked on Github.
</Hyperlink>
</Paragraph>
</Section>
<Section title="The application crashes on Android with react-native-screens">
<Paragraph>
Likely a bug between <InlineCode>react-native-webview</InlineCode>{' '}
and <InlineCode>react-native-screens</InlineCode>. See{' '}
<Hyperlink url="https://stackoverflow.com/q/63171131/2779871">
Stack Overflow | When rendering iframes, Android crashes while
navigating back to stack screen
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="Unable to resolve XXX from node_modules/YYY">
<Paragraph>
Probably an issue with your package manager. See{' '}
<Hyperlink url="https://stackoverflow.com/q/63053425/2779871">
Stack Overflow | Unable to resolve XXX from module YYY
</Hyperlink>
.
</Paragraph>
</Section>
<Section title="Long image cannot show in full screen on Android">
<Paragraph>
This is a limitation of FaceBook's fresco library and React Native{' '}
<RefRNSymbol name="Image" /> component. You need to downsize the
image.
</Paragraph>
</Section>
<Section title="Some anchors (<a>) are not accessible to screen readers">
<Paragraph>
Because of a{' '}
<Hyperlink url="https://github.com/facebook/react-native/issues/32004">
React Native bug
</Hyperlink>
, nested `Text` elements are not accessible, which means that the
screen reader will not be able to identify{' '}
<RefHtmlElement name="a" /> tags as links when grouped with other
textual elements. Below is an example:
</Paragraph>
<SourceDisplay
lang="html"
showLineNumbers={false}
content={`<p>
Unfortunately,
<a href="https://domain.com">this hyperlink is not accessible</a>
</p>`}
/>
<Paragraph>
Luke Walczak from Callstack{' '}
<Hyperlink url="https://callstack.com/blog/react-native-android-accessibility-tips/">
explains how to circumvent this issue in a great post
</Hyperlink>
. Unfortunately, this workaround cannot be genericized and we will
have to wait for a fix in React Native codebase.
</Paragraph>
</Section>
</Chapter>
</Page>
);
} | the_stack |
import * as cfnspec from '@aws-cdk/cfnspec';
import * as colors from 'colors/safe';
import { PropertyChange, PropertyMap, ResourceChange } from '../diff/types';
import { DiffableCollection } from '../diffable';
import { renderIntrinsics } from '../render-intrinsics';
import { deepRemoveUndefined, dropIfEmpty, flatMap, makeComparator } from '../util';
import { ManagedPolicyAttachment, ManagedPolicyJson } from './managed-policy';
import { parseLambdaPermission, parseStatements, Statement, StatementJson } from './statement';
export interface IamChangesProps {
propertyChanges: PropertyChange[];
resourceChanges: ResourceChange[];
}
/**
* Changes to IAM statements
*/
export class IamChanges {
public static IamPropertyScrutinies = [
cfnspec.schema.PropertyScrutinyType.InlineIdentityPolicies,
cfnspec.schema.PropertyScrutinyType.InlineResourcePolicy,
cfnspec.schema.PropertyScrutinyType.ManagedPolicies,
];
public static IamResourceScrutinies = [
cfnspec.schema.ResourceScrutinyType.ResourcePolicyResource,
cfnspec.schema.ResourceScrutinyType.IdentityPolicyResource,
cfnspec.schema.ResourceScrutinyType.LambdaPermission,
];
public readonly statements = new DiffableCollection<Statement>();
public readonly managedPolicies = new DiffableCollection<ManagedPolicyAttachment>();
constructor(props: IamChangesProps) {
for (const propertyChange of props.propertyChanges) {
this.readPropertyChange(propertyChange);
}
for (const resourceChange of props.resourceChanges) {
this.readResourceChange(resourceChange);
}
this.statements.calculateDiff();
this.managedPolicies.calculateDiff();
}
public get hasChanges() {
return this.statements.hasChanges || this.managedPolicies.hasChanges;
}
/**
* Return whether the changes include broadened permissions
*
* Permissions are broadened if positive statements are added or
* negative statements are removed, or if managed policies are added.
*/
public get permissionsBroadened(): boolean {
return this.statements.additions.some(s => !s.isNegativeStatement)
|| this.statements.removals.some(s => s.isNegativeStatement)
|| this.managedPolicies.hasAdditions;
}
/**
* Return a summary table of changes
*/
public summarizeStatements(): string[][] {
const ret: string[][] = [];
const header = ['', 'Resource', 'Effect', 'Action', 'Principal', 'Condition'];
// First generate all lines, then sort on Resource so that similar resources are together
for (const statement of this.statements.additions) {
const renderedStatement = statement.render();
ret.push([
'+',
renderedStatement.resource,
renderedStatement.effect,
renderedStatement.action,
renderedStatement.principal,
renderedStatement.condition,
].map(s => colors.green(s)));
}
for (const statement of this.statements.removals) {
const renderedStatement = statement.render();
ret.push([
colors.red('-'),
renderedStatement.resource,
renderedStatement.effect,
renderedStatement.action,
renderedStatement.principal,
renderedStatement.condition,
].map(s => colors.red(s)));
}
// Sort by 2nd column
ret.sort(makeComparator((row: string[]) => [row[1]]));
ret.splice(0, 0, header);
return ret;
}
public summarizeManagedPolicies(): string[][] {
const ret: string[][] = [];
const header = ['', 'Resource', 'Managed Policy ARN'];
for (const att of this.managedPolicies.additions) {
ret.push([
'+',
att.identityArn,
att.managedPolicyArn,
].map(s => colors.green(s)));
}
for (const att of this.managedPolicies.removals) {
ret.push([
'-',
att.identityArn,
att.managedPolicyArn,
].map(s => colors.red(s)));
}
// Sort by 2nd column
ret.sort(makeComparator((row: string[]) => [row[1]]));
ret.splice(0, 0, header);
return ret;
}
/**
* Return a machine-readable version of the changes.
* This is only used in tests.
*
* @internal
*/
public _toJson(): IamChangesJson {
return deepRemoveUndefined({
statementAdditions: dropIfEmpty(this.statements.additions.map(s => s._toJson())),
statementRemovals: dropIfEmpty(this.statements.removals.map(s => s._toJson())),
managedPolicyAdditions: dropIfEmpty(this.managedPolicies.additions.map(s => s._toJson())),
managedPolicyRemovals: dropIfEmpty(this.managedPolicies.removals.map(s => s._toJson())),
});
}
private readPropertyChange(propertyChange: PropertyChange) {
switch (propertyChange.scrutinyType) {
case cfnspec.schema.PropertyScrutinyType.InlineIdentityPolicies:
// AWS::IAM::{ Role | User | Group }.Policies
this.statements.addOld(...this.readIdentityPolicies(propertyChange.oldValue, propertyChange.resourceLogicalId));
this.statements.addNew(...this.readIdentityPolicies(propertyChange.newValue, propertyChange.resourceLogicalId));
break;
case cfnspec.schema.PropertyScrutinyType.InlineResourcePolicy:
// Any PolicyDocument on a resource (including AssumeRolePolicyDocument)
this.statements.addOld(...this.readResourceStatements(propertyChange.oldValue, propertyChange.resourceLogicalId));
this.statements.addNew(...this.readResourceStatements(propertyChange.newValue, propertyChange.resourceLogicalId));
break;
case cfnspec.schema.PropertyScrutinyType.ManagedPolicies:
// Just a list of managed policies
this.managedPolicies.addOld(...this.readManagedPolicies(propertyChange.oldValue, propertyChange.resourceLogicalId));
this.managedPolicies.addNew(...this.readManagedPolicies(propertyChange.newValue, propertyChange.resourceLogicalId));
break;
}
}
private readResourceChange(resourceChange: ResourceChange) {
switch (resourceChange.scrutinyType) {
case cfnspec.schema.ResourceScrutinyType.IdentityPolicyResource:
// AWS::IAM::Policy
this.statements.addOld(...this.readIdentityPolicyResource(resourceChange.oldProperties));
this.statements.addNew(...this.readIdentityPolicyResource(resourceChange.newProperties));
break;
case cfnspec.schema.ResourceScrutinyType.ResourcePolicyResource:
// AWS::*::{Bucket,Queue,Topic}Policy
this.statements.addOld(...this.readResourcePolicyResource(resourceChange.oldProperties));
this.statements.addNew(...this.readResourcePolicyResource(resourceChange.newProperties));
break;
case cfnspec.schema.ResourceScrutinyType.LambdaPermission:
this.statements.addOld(...this.readLambdaStatements(resourceChange.oldProperties));
this.statements.addNew(...this.readLambdaStatements(resourceChange.newProperties));
break;
}
}
/**
* Parse a list of policies on an identity
*/
private readIdentityPolicies(policies: any, logicalId: string): Statement[] {
if (policies === undefined) { return []; }
const appliesToPrincipal = 'AWS:${' + logicalId + '}';
return flatMap(policies, (policy: any) => {
// check if the Policy itself is not an intrinsic, like an Fn::If
const unparsedStatement = policy.PolicyDocument?.Statement
? policy.PolicyDocument.Statement
: policy;
return defaultPrincipal(appliesToPrincipal, parseStatements(renderIntrinsics(unparsedStatement)));
});
}
/**
* Parse an IAM::Policy resource
*/
private readIdentityPolicyResource(properties: any): Statement[] {
if (properties === undefined) { return []; }
properties = renderIntrinsics(properties);
const principals = (properties.Groups || []).concat(properties.Users || []).concat(properties.Roles || []);
return flatMap(principals, (principal: string) => {
const ref = 'AWS:' + principal;
return defaultPrincipal(ref, parseStatements(properties.PolicyDocument.Statement));
});
}
private readResourceStatements(policy: any, logicalId: string): Statement[] {
if (policy === undefined) { return []; }
const appliesToResource = '${' + logicalId + '.Arn}';
return defaultResource(appliesToResource, parseStatements(renderIntrinsics(policy.Statement)));
}
/**
* Parse an AWS::*::{Bucket,Topic,Queue}policy
*/
private readResourcePolicyResource(properties: any): Statement[] {
if (properties === undefined) { return []; }
properties = renderIntrinsics(properties);
const policyKeys = Object.keys(properties).filter(key => key.indexOf('Policy') > -1);
// Find the key that identifies the resource(s) this policy applies to
const resourceKeys = Object.keys(properties).filter(key => !policyKeys.includes(key) && !key.endsWith('Name'));
let resources = resourceKeys.length === 1 ? properties[resourceKeys[0]] : ['???'];
// For some resources, this is a singleton string, for some it's an array
if (!Array.isArray(resources)) {
resources = [resources];
}
return flatMap(resources, (resource: string) => {
return defaultResource(resource, parseStatements(properties[policyKeys[0]].Statement));
});
}
private readManagedPolicies(policyArns: any, logicalId: string): ManagedPolicyAttachment[] {
if (!policyArns) { return []; }
const rep = '${' + logicalId + '}';
return ManagedPolicyAttachment.parseManagedPolicies(rep, renderIntrinsics(policyArns));
}
private readLambdaStatements(properties?: PropertyMap): Statement[] {
if (!properties) { return []; }
return [parseLambdaPermission(renderIntrinsics(properties))];
}
}
/**
* Set an undefined or wildcarded principal on these statements
*/
function defaultPrincipal(principal: string, statements: Statement[]) {
statements.forEach(s => s.principals.replaceEmpty(principal));
statements.forEach(s => s.principals.replaceStar(principal));
return statements;
}
/**
* Set an undefined or wildcarded resource on these statements
*/
function defaultResource(resource: string, statements: Statement[]) {
statements.forEach(s => s.resources.replaceEmpty(resource));
statements.forEach(s => s.resources.replaceStar(resource));
return statements;
}
export interface IamChangesJson {
statementAdditions?: StatementJson[];
statementRemovals?: StatementJson[];
managedPolicyAdditions?: ManagedPolicyJson[];
managedPolicyRemovals?: ManagedPolicyJson[];
} | the_stack |
import { AbstractControl, AbstractControlOptions, AsyncValidatorFn, FormArray, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
import { ClassType, isFunction } from '@deepkit/core';
import { ReflectionClass, ReflectionKind, Type, ValidationErrorItem } from '@deepkit/type';
import { Subscription } from 'rxjs';
export function requiredIfValidator(predicate: () => boolean, validator: ValidatorFn): any {
return (formControl: AbstractControl) => {
if (!formControl.parent) {
return null;
}
if (predicate()) {
return validator(formControl);
}
return null;
};
}
type PropPath = string | (() => string);
function getPropPath(propPath?: PropPath, append?: string | number): string {
propPath = isFunction(propPath) ? propPath() : propPath;
if (propPath && append !== undefined) {
return propPath + '.' + append;
}
if (propPath) {
return propPath;
}
if (append !== undefined) {
return String(append);
}
return '';
}
function createControl<T>(
propPath: PropPath,
prop: Type,
parent?: FormGroup | FormArray,
conditionalValidators: TypedFormGroupConditionalValidators<any, any> = {},
limitControls: LimitControls<T> = {}
): AbstractControl {
const validator = (control: AbstractControl): ValidationErrors | null => {
const rootFormGroup = control.root as TypedFormGroup<any>;
if (!rootFormGroup.value) {
// not yet initialized
return null;
}
function errorsToAngularErrors(errors: ValidationErrorItem[]): any {
if (errors.length) {
const res: ValidationErrors = {};
for (const e of errors) {
res[e.code] = e.message;
}
return res;
}
return null;
}
const errors: ValidationErrorItem[] = [];
const val = conditionalValidators[prop.name];
if (isConditionalValidatorFn(val)) {
const res = val(rootFormGroup.value, control.parent!.value);
if (res) {
const validators: ValidatorType[] = Array.isArray(res) ? res : [res];
for (const val of validators) {
handleCustomValidator(prop, new class implements PropertyValidator {
validate<T>(value: any): PropertyValidatorError | void {
return val(value);
}
}, control.value, getPropPath(propPath), errors);
if (errors.length) {
return errorsToAngularErrors(errors);
}
}
}
}
jitValidateProperty(prop)(control.value, getPropPath(propPath), errors);
return errorsToAngularErrors(errors);
};
let control: AbstractControl;
if (prop.kind === ReflectionKind.array) {
conditionalValidators['0'] = conditionalValidators[prop.name];
control = new TypedFormArray(propPath, prop.getSubType(), limitControls, conditionalValidators);
} else {
if (prop.type === 'class') {
const t = prop.name ? conditionalValidators[prop.name] : conditionalValidators;
const conditionalValidatorsForProp = isConditionalValidatorFn(t) ? {} : t;
control = TypedFormGroup.fromEntityClass(prop.getResolvedClassType(), limitControls, undefined, conditionalValidatorsForProp, propPath);
} else {
control = new FormControl(undefined, validator);
}
}
if (parent && conditionalValidators[prop.name]) {
parent.root.valueChanges.subscribe((v) => {
// todo: rework to apply validity status sync. find our why here is a race condition.
setTimeout(() => {
control.updateValueAndValidity({ emitEvent: false });
});
});
}
if (parent) {
control.setParent(parent);
}
return control;
}
type FlattenIfArray<T> = T extends Array<any> ? T[0] : T;
type ValidatorType = ((value: any) => PropertyValidatorError | void);
type ConditionalValidatorFn<RT, PT> = (rootValue: RT, parentValue: PT) => ValidatorType | ValidatorType[] | void | undefined;
function isConditionalValidatorFn(obj: any): obj is ConditionalValidatorFn<any, any> {
return isFunction(obj);
}
type TypedFormGroupConditionalValidators<RT, T> = {
[P in keyof T & string]?: ConditionalValidatorFn<RT, T> | (FlattenIfArray<T[P]> extends object ? TypedFormGroupConditionalValidators<RT, FlattenIfArray<T[P]>> : undefined);
};
interface TypedAbstractControl<T> extends AbstractControl {
value: T;
}
type TypedControl<T> = T extends Array<any> ? TypedFormArray<FlattenIfArray<T>> : (T extends object ? TypedFormGroup<T> : TypedAbstractControl<T>);
type Controls<T> = { [P in keyof T & string]: TypedControl<T[P]> };
type LimitControls<T> = {
[P in keyof T & string]?: 1 | (FlattenIfArray<T[P]> extends object ? LimitControls<FlattenIfArray<T[P]>> : 1)
};
export interface TypedFormArray<T> {
value: T[];
}
export class TypedFormArray<T> extends FormArray {
_value: T[] = [];
constructor(
private propPath: PropPath,
private prop: Type,
private limitControls: LimitControls<T> = {},
private conditionalValidators: TypedFormGroupConditionalValidators<any, any> = {}
) {
super([], []);
Object.defineProperty(this, 'value', {
get(): any {
return this._value;
},
set(v: T[]): void {
if (this._value) {
this._value.length = 0;
Array.prototype.push.apply(this._value, v);
} else {
this._value = v;
}
}
});
}
get typedControls(): TypedControl<T>[] {
return this.controls as any;
}
protected createControl(value?: T): AbstractControl {
const prop = this.prop.clone();
let control: AbstractControl;
control = createControl(() => getPropPath(this.propPath, this.controls.indexOf(control)), prop, this, this.conditionalValidators, this.limitControls);
(control.value as any) = value;
return control;
}
addItem(item: T): void {
this.push(this.createControl(item));
}
setRefValue(v?: T[]): void {
this._value = v || [];
this.setValue(this._value);
}
removeItem(item: T): void {
const index = this.value.indexOf(item);
if (index !== -1) {
this.controls.splice(index, 1);
this.value.splice(index, 1);
}
}
removeItemAtIndex(item: T, index: number): void {
if (index !== -1 && this.controls[index]) {
this.controls.splice(index, 1);
this.value.splice(index, 1);
}
}
push(control?: AbstractControl): void {
super.push(control || this.createControl());
}
setValue(value: any[], options?: { onlySelf?: boolean; emitEvent?: boolean }): void {
// note: this.push modifies the ref `value`, so we need to (shallow) copy the
// array (not the content) and reassign the content (by not changing the
// array ref) later.
const copy = value.slice(0);
this.clear();
for (const item of copy) {
this.push(this.createControl(item));
}
// here the value is empty, but we make sure to remove any content,
// and reassign from our copied array.
Array.prototype.splice.call(value, 0, value.length, ...copy);
if (value.push === Array.prototype.push) {
(value as any).push = (...args: any[]) => {
Array.prototype.push.apply(value, args);
for (const item of args) {
this.push(this.createControl(item));
}
};
(value as any).splice = (...args: any) => {
Array.prototype.splice.apply(value, args);
this.setValue(value);
};
}
super.setValue(value, options);
}
rerender() {
this.clear();
for (const item of this._value.slice(0)) {
this.push(this.createControl(item));
}
}
printDeepErrors(path?: string): void {
for (const control of this.controls) {
if (control instanceof TypedFormGroup || control instanceof TypedFormArray) {
control.printDeepErrors(getPropPath(path, this.controls.indexOf(control)));
} else if (control.invalid) {
console.log('invalid', getPropPath(path, this.controls.indexOf(control)), control.errors, control.value, control.status, control.value, control);
}
}
}
}
export class TypedFormGroup<T extends object> extends FormGroup {
public classType?: ClassType<T>;
public typedValue?: T;
protected lastSyncSub?: Subscription;
public value: T | undefined;
get typedControls(): Controls<T> {
return this.controls as any;
}
constructor(controls: { [p: string]: AbstractControl }, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) {
super(controls, validatorOrOpts, asyncValidator);
Object.defineProperty(this, 'value', {
get(): any {
return this.typedValue;
},
set(v: T[]): void {
if (this.classType && v instanceof this.classType) {
if (!this.typedValue || this.typedValue !== v) {
// is needed since angular wont set `this.value` to `value`, but it simply iterates.
// we need however the actual reference.
this.typedValue = v;
}
if (this.lastSyncSub) {
this.lastSyncSub.unsubscribe();
}
for (const [name, control] of Object.entries(this.controls)) {
// const control = this.controls[i as keyof T & string];
if (control instanceof TypedFormArray) {
control.setRefValue((v as any)[name]);
} else {
(control as any).setValue((v as any)[name]);
}
}
// this comes after `setValue` so we don't get old values
this.lastSyncSub = this.valueChanges.subscribe(() => {
this.updateEntity(v);
this.updateValueAndValidity({ emitEvent: false });
});
this.updateValueAndValidity();
} else {
// angular tries to set via _updateValue() `this.value` again using `{}`, which we simply ignore.
// except when its resetted
if (v === undefined) {
this.typedValue = undefined;
this.updateValueAndValidity();
}
}
}
});
}
static fromEntityClass<T extends object>(
classType: ClassType<T>,
limitControls: LimitControls<T> = {},
validation?: (control: TypedFormGroup<T>) => ValidationErrors | null,
conditionalValidators: TypedFormGroupConditionalValidators<T, T> = {},
path?: PropPath
): TypedFormGroup<T> {
const entitySchema = ReflectionClass.from(classType);
const t = new TypedFormGroup<T>({}, validation as ValidatorFn);
t.classType = classType;
const validNames = Object.keys(limitControls);
for (const prop of entitySchema.getProperties()) {
if (validNames.length && !validNames.includes(prop.name)) {
continue;
}
const limitControlsForProp = limitControls[prop.name as keyof T & string] === 1 ? {} : limitControls[prop.name as keyof T & string];
t.registerControl(prop.name, createControl(() => getPropPath(path, prop.name), prop.type, t, conditionalValidators, limitControlsForProp));
}
return t;
}
updateValueAndValidity(opts?: { onlySelf?: boolean; emitEvent?: boolean }): void {
super.updateValueAndValidity(opts);
if (this.validator && !this.value && !this.disabled) {
// we have no valid, so our validator decides whether its valid or not
(this.status as any) = this.validator(this) ? 'INVALID' : 'VALID';
}
}
reset(value?: any, options?: { onlySelf?: boolean; emitEvent?: boolean }): void {
if (value && this.classType && value instanceof this.classType) {
this.syncEntity(value);
}
super.reset(value, options);
}
setValue(value: { [p: string]: any }, options?: { onlySelf?: boolean; emitEvent?: boolean }): void {
this.value = value as any;
}
getControls(): Controls<any> {
return this.controls as Controls<any>;
}
printDeepErrors(path?: string): void {
for (const [name, control] of Object.entries(this.controls)) {
if (control instanceof TypedFormGroup || control instanceof TypedFormArray) {
control.printDeepErrors(getPropPath(path, name));
} else if (control.invalid) {
console.log('invalid', getPropPath(path, name), control.errors, control.value, control.status, control.value, control);
}
}
}
/**
* Sets the current form values from the given entity and syncs changes automatically back to the entity.
*/
public syncEntity(entity: T): void {
this.value = entity;
}
/**
* Saves the current values from this form into the given entity.
*/
public updateEntity(entity: T): void {
for (const [name, c] of Object.entries(this.controls)) {
if (c.touched || c.dirty) {
if (c instanceof TypedFormGroup) {
if ((entity as any)[name]) {
c.updateEntity((entity as any)[name]);
}
} else {
(entity as any)[name] = c.value;
}
}
}
}
} | the_stack |
* @module Tiles
*/
import { assert, BeDuration, BeTimePoint, ByteStream, Id64String, JsonUtils, utf8ToString } from "@itwin/core-bentley";
import { Point2d, Point3d, Range1d, Vector3d } from "@itwin/core-geometry";
import { nextPoint3d64FromByteStream, OctEncodedNormal, QParams3d, QPoint2d } from "@itwin/core-common";
import { request, RequestOptions } from "@bentley/itwin-client";
import { ApproximateTerrainHeights } from "../../ApproximateTerrainHeights";
import { IModelApp } from "../../IModelApp";
import { IModelConnection } from "../../IModelConnection";
import { TerrainMeshPrimitive } from "../../render/primitives/mesh/TerrainMeshPrimitive";
import {
GeographicTilingScheme, MapCartoRectangle, MapTile, MapTileProjection, MapTilingScheme, QuadId, TerrainMeshProvider, Tile, TileAvailability,
} from "../internal";
/** @internal */
enum QuantizedMeshExtensionIds {
OctEncodedNormals = 1,
WaterMask = 2,
Metadata = 4,
}
/** Return the URL for a Cesium ION asset from its asset ID and request Key.
* @public
*/
export function getCesiumAssetUrl(osmAssetId: number, requestKey: string): string {
return `$CesiumIonAsset=${osmAssetId}:${requestKey}`;
}
/** @internal */
export function getCesiumOSMBuildingsUrl(): string | undefined {
const key = IModelApp.tileAdmin.cesiumIonKey;
if (undefined === key)
return undefined;
const osmBuildingAssetId = 96188;
return getCesiumAssetUrl(osmBuildingAssetId, key);
}
/** @internal */
export async function getCesiumAccessTokenAndEndpointUrl(assetId = 1, requestKey?: string): Promise<{ token?: string, url?: string }> {
if (undefined === requestKey) {
requestKey = IModelApp.tileAdmin.cesiumIonKey;
if (undefined === requestKey)
return {};
}
const requestTemplate = `https://api.cesium.com/v1/assets/${assetId}/endpoint?access_token={CesiumRequestToken}`;
const apiUrl: string = requestTemplate.replace("{CesiumRequestToken}", requestKey);
const apiRequestOptions: RequestOptions = { method: "GET", responseType: "json" };
try {
const apiResponse = await request(apiUrl, apiRequestOptions);
if (undefined === apiResponse || undefined === apiResponse.body || undefined === apiResponse.body.url) {
assert(false);
return {};
}
return { token: apiResponse.body.accessToken, url: apiResponse.body.url };
} catch (error) {
assert(false);
return {};
}
}
/** @internal */
export async function getCesiumTerrainProvider(iModel: IModelConnection, modelId: Id64String, wantSkirts: boolean, wantNormals: boolean, exaggeration: number): Promise<TerrainMeshProvider | undefined> {
let layers;
const accessTokenAndEndpointUrl = await getCesiumAccessTokenAndEndpointUrl();
if (!accessTokenAndEndpointUrl.token || !accessTokenAndEndpointUrl.url)
return undefined;
try {
const layerRequestOptions: RequestOptions = { method: "GET", responseType: "json", headers: { authorization: `Bearer ${accessTokenAndEndpointUrl.token}` } };
const layerUrl = `${accessTokenAndEndpointUrl.url}layer.json`;
const layerResponse = await request(layerUrl, layerRequestOptions);
if (undefined === layerResponse) {
assert(false);
return undefined;
}
layers = layerResponse.body;
} catch (error) {
assert(false);
return undefined;
}
if (undefined === layers.tiles || undefined === layers.version) {
assert(false);
return undefined;
}
const tilingScheme = new GeographicTilingScheme();
let tileAvailability;
if (undefined !== layers.available) {
const availableTiles = layers.available;
tileAvailability = new TileAvailability(tilingScheme, availableTiles.length);
for (let level = 0; level < layers.available.length; level++) {
const rangesAtLevel = availableTiles[level];
for (const range of rangesAtLevel) {
tileAvailability.addAvailableTileRange(level, range.startX, range.startY, range.endX, range.endY);
}
}
}
let tileUrlTemplate = accessTokenAndEndpointUrl.url + layers.tiles[0].replace("{version}", layers.version);
if (wantNormals)
tileUrlTemplate = tileUrlTemplate.replace("?", "?extensions=octvertexnormals-watermask-metadata&");
const maxDepth = JsonUtils.asInt(layers.maxzoom, 19);
// TBD -- When we have an API extract the heights for the project from the terrain tiles - for use temporary Bing elevation.
return new CesiumTerrainProvider(iModel, modelId, accessTokenAndEndpointUrl.token, tileUrlTemplate, maxDepth, wantSkirts, tilingScheme, tileAvailability, layers.metadataAvailability, exaggeration);
}
function zigZagDecode(value: number) {
return (value >> 1) ^ (-(value & 1));
}
/**
* Decodes delta and ZigZag encoded vertices. This modifies the buffers in place.
*
* @see {@link https://github.com/AnalyticalGraphicsInc/quantized-mesh|quantized-mesh-1.0 terrain format}
*/
function zigZagDeltaDecode(uBuffer: Uint16Array, vBuffer: Uint16Array, heightBuffer: Uint16Array) {
const count = uBuffer.length;
let u = 0;
let v = 0;
let height = 0;
for (let i = 0; i < count; ++i) {
u += zigZagDecode(uBuffer[i]);
v += zigZagDecode(vBuffer[i]);
uBuffer[i] = u;
vBuffer[i] = v;
height += zigZagDecode(heightBuffer[i]);
heightBuffer[i] = height;
}
}
function getIndexArray(vertexCount: number, streamBuffer: ByteStream, indexCount: number): Uint16Array | Uint32Array {
const indicesAre32Bit = vertexCount > 64 * 1024;
const indexArray = (indicesAre32Bit) ? new Uint32Array(streamBuffer.arrayBuffer, streamBuffer.curPos, indexCount) : new Uint16Array(streamBuffer.arrayBuffer, streamBuffer.curPos, indexCount);
streamBuffer.advance(indexCount * (indicesAre32Bit ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT));
return indexArray;
}
/** @internal */
class CesiumTerrainProvider extends TerrainMeshProvider {
private static _scratchQPoint2d = QPoint2d.fromScalars(0, 0);
private static _scratchPoint2d = Point2d.createZero();
private static _scratchPoint = Point3d.createZero();
private static _scratchNormal = Vector3d.createZero();
private static _scratchHeightRange = Range1d.createNull();
private static _tokenTimeoutInterval = BeDuration.fromSeconds(60 * 30); // Request a new access token every 30 minutes...
private _tokenTimeOut: BeTimePoint;
public override forceTileLoad(tile: Tile): boolean {
// Force loading of the metadata availability tiles as these are required for determining the availability of descendants.
return undefined !== this._metaDataAvailableLevel && tile.depth === 1 + this._metaDataAvailableLevel && !(tile as MapTile).everLoaded;
}
constructor(iModel: IModelConnection, modelId: Id64String, private _accessToken: string, private _tileUrlTemplate: string,
private _maxDepth: number, private readonly _wantSkirts: boolean, private _tilingScheme: MapTilingScheme, private _tileAvailability: TileAvailability | undefined, private _metaDataAvailableLevel: number | undefined, private _exaggeration: number) {
super(iModel, modelId);
this._tokenTimeOut = BeTimePoint.now().plus(CesiumTerrainProvider._tokenTimeoutInterval);
}
public override getLogo(): HTMLTableRowElement {
return IModelApp.makeLogoCard({ iconSrc: "images/cesium-ion.svg", heading: "Cesium Ion", notice: IModelApp.localization.getLocalizedString("iModelJs:BackgroundMap.CesiumWorldTerrainAttribution") });
}
public get maxDepth(): number { return this._maxDepth; }
public get tilingScheme(): MapTilingScheme { return this._tilingScheme; }
public isTileAvailable(quadId: QuadId) {
if (quadId.level > this.maxDepth)
return false;
return this._tileAvailability ? this._tileAvailability.isTileAvailable(quadId.level - 1, quadId.column, quadId.row) : true;
}
public override async getMesh(tile: MapTile, data: Uint8Array): Promise<TerrainMeshPrimitive | undefined> {
if (BeTimePoint.now().milliseconds > this._tokenTimeOut.milliseconds) {
const accessTokenAndEndpointUrl = await getCesiumAccessTokenAndEndpointUrl();
if (!accessTokenAndEndpointUrl.token) {
assert(false);
return undefined;
}
this._accessToken = accessTokenAndEndpointUrl.token;
this._tokenTimeOut = BeTimePoint.now().plus(CesiumTerrainProvider._tokenTimeoutInterval);
}
assert(data instanceof Uint8Array);
assert(tile instanceof MapTile);
const blob = data;
const streamBuffer = new ByteStream(blob.buffer);
const center = nextPoint3d64FromByteStream(streamBuffer);
const quadId = QuadId.createFromContentId(tile.contentId);
const skirtHeight = this.getLevelMaximumGeometricError(quadId.level) * 10.0;
const minHeight = this._exaggeration * streamBuffer.nextFloat32;
const maxHeight = this._exaggeration * streamBuffer.nextFloat32;
const boundCenter = nextPoint3d64FromByteStream(streamBuffer);
const boundRadius = streamBuffer.nextFloat64;
const horizonOcclusion = nextPoint3d64FromByteStream(streamBuffer);
const terrainTile = tile;
terrainTile.adjustHeights(minHeight, maxHeight);
if (undefined === center || undefined === boundCenter || undefined === boundRadius || undefined === horizonOcclusion) { }
const pointCount = streamBuffer.nextUint32;
const encodedVertexBuffer = new Uint16Array(blob.buffer, streamBuffer.curPos, pointCount * 3);
streamBuffer.advance(pointCount * 6);
const uBuffer = encodedVertexBuffer.subarray(0, pointCount);
const vBuffer = encodedVertexBuffer.subarray(pointCount, 2 * pointCount);
const heightBuffer = encodedVertexBuffer.subarray(pointCount * 2, 3 * pointCount);
zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);
let bytesPerIndex = Uint16Array.BYTES_PER_ELEMENT;
const triangleElements = 3;
if (pointCount > 64 * 1024) {
// More than 64k vertices, so indices are 32-bit.
bytesPerIndex = Uint32Array.BYTES_PER_ELEMENT;
}
// skip over any additional padding that was added for 2/4 byte alignment
if (streamBuffer.curPos % bytesPerIndex !== 0)
streamBuffer.advance(bytesPerIndex - (streamBuffer.curPos % bytesPerIndex));
const triangleCount = streamBuffer.nextUint32;
const indexCount = triangleCount * triangleElements;
const indices = getIndexArray(pointCount, streamBuffer, indexCount);
// High water mark decoding based on decompressIndices_ in webgl-loader's loader.js.
// https://code.google.com/p/webgl-loader/source/browse/trunk/samples/loader.js?r=99#55
// Copyright 2012 Google Inc., Apache 2.0 license.
let highest = 0;
const length = indices.length;
for (let i = 0; i < length; ++i) {
const code = indices[i];
indices[i] = highest - code;
if (code === 0) {
++highest;
}
}
CesiumTerrainProvider._scratchHeightRange.low = minHeight - skirtHeight;
CesiumTerrainProvider._scratchHeightRange.high = maxHeight;
const projection = terrainTile.getProjection(CesiumTerrainProvider._scratchHeightRange);
const pointQParams = QParams3d.fromRange(projection.localRange);
const uvScale = 1.0 / 32767.0;
const heightScale = uvScale * (maxHeight - minHeight);
const westCount = streamBuffer.nextUint32;
const westIndices = getIndexArray(pointCount, streamBuffer, westCount);
const southCount = streamBuffer.nextUint32;
const southIndices = getIndexArray(pointCount, streamBuffer, southCount);
const eastCount = streamBuffer.nextUint32;
const eastIndices = getIndexArray(pointCount, streamBuffer, eastCount);
const northCount = streamBuffer.nextUint32;
const northIndices = getIndexArray(pointCount, streamBuffer, northCount);
// Extensions...
let encodedNormalsBuffer;
while (streamBuffer.curPos < streamBuffer.length) {
const extensionId = streamBuffer.nextUint8;
const extensionLength = streamBuffer.nextUint32;
switch (extensionId) {
case QuantizedMeshExtensionIds.OctEncodedNormals:
assert(pointCount * 2 === extensionLength);
encodedNormalsBuffer = new Uint8Array(streamBuffer.arrayBuffer, streamBuffer.curPos, extensionLength);
streamBuffer.advance(extensionLength);
break;
case QuantizedMeshExtensionIds.Metadata:
const stringLength = streamBuffer.nextUint32;
if (stringLength > 0) {
const strData = streamBuffer.nextBytes(stringLength);
const str = utf8ToString(strData);
if (undefined !== str) {
const metaData = JSON.parse(str);
if (undefined !== metaData.available && undefined !== this._tileAvailability) {
const availableTiles = metaData.available;
for (let offset = 0; offset < availableTiles.length; ++offset) {
const availableLevel = tile.depth + offset; // Our depth is includes root (1 + cesium Depth)
const rangesAtLevel = availableTiles[offset];
for (const range of rangesAtLevel)
this._tileAvailability.addAvailableTileRange(availableLevel, range.startX, range.startY, range.endX, range.endY);
}
}
}
}
break;
default:
streamBuffer.advance(extensionLength);
break;
}
}
const mesh = TerrainMeshPrimitive.create({ pointQParams, pointCount, indexCount, wantSkirts: this._wantSkirts, westCount, eastCount, southCount, northCount, wantNormals: undefined !== encodedNormalsBuffer });
for (let i = 0; i < indexCount;)
this.addTriangle(mesh, indices[i++], indices[i++], indices[i++]);
const worldToEcef = tile.iModel.getEcefTransform().matrix;
for (let i = 0; i < pointCount; i++) {
const u = uBuffer[i];
const v = vBuffer[i];
projection.getPoint(uvScale * u, uvScale * v, minHeight + heightBuffer[i] * heightScale, CesiumTerrainProvider._scratchPoint);
CesiumTerrainProvider._scratchQPoint2d.setFromScalars(u * 2, v * 2);
if (encodedNormalsBuffer) {
const normalIndex = i * 2;
OctEncodedNormal.decodeValue(encodedNormalsBuffer[normalIndex + 1] << 8 | encodedNormalsBuffer[normalIndex], CesiumTerrainProvider._scratchNormal);
worldToEcef.multiplyTransposeVector(CesiumTerrainProvider._scratchNormal, CesiumTerrainProvider._scratchNormal);
mesh.addVertex(CesiumTerrainProvider._scratchPoint, CesiumTerrainProvider._scratchQPoint2d, OctEncodedNormal.encode(CesiumTerrainProvider._scratchNormal));
} else {
mesh.addVertex(CesiumTerrainProvider._scratchPoint, CesiumTerrainProvider._scratchQPoint2d);
}
}
if (this._wantSkirts) {
westIndices.sort((a, b) => vBuffer[a] - vBuffer[b]);
eastIndices.sort((a, b) => vBuffer[a] - vBuffer[b]);
northIndices.sort((a, b) => uBuffer[a] - uBuffer[b]);
southIndices.sort((a, b) => uBuffer[a] - uBuffer[b]);
const wantNormals = (encodedNormalsBuffer !== undefined);
this.generateSkirts(mesh, westIndices, projection, -skirtHeight, heightBuffer, minHeight, heightScale, wantNormals);
this.generateSkirts(mesh, eastIndices, projection, -skirtHeight, heightBuffer, minHeight, heightScale, wantNormals);
this.generateSkirts(mesh, southIndices, projection, -skirtHeight, heightBuffer, minHeight, heightScale, wantNormals);
this.generateSkirts(mesh, northIndices, projection, -skirtHeight, heightBuffer, minHeight, heightScale, wantNormals);
}
assert(mesh.isCompleted);
return mesh;
}
private addTriangle(mesh: TerrainMeshPrimitive, i0: number, i1: number, i2: number) {
mesh.addTriangle(i0, i1, i2);
}
private generateSkirts(mesh: TerrainMeshPrimitive, indices: Uint16Array | Uint32Array, projection: MapTileProjection, skirtOffset: number, heightBuffer: Uint16Array, minHeight: number, heightScale: number, wantNormals: boolean) {
for (let i = 0; i < indices.length; i++) {
const index = indices[i];
const paramIndex = index * 2;
const height = minHeight + heightBuffer[index] * heightScale;
CesiumTerrainProvider._scratchQPoint2d.setFromScalars(mesh.uvs[paramIndex], mesh.uvs[paramIndex + 1]);
const uv = mesh.uvQParams.unquantize(CesiumTerrainProvider._scratchQPoint2d.x, CesiumTerrainProvider._scratchQPoint2d.y, CesiumTerrainProvider._scratchPoint2d);
if (wantNormals && mesh.normals) {
mesh.addVertex(projection.getPoint(uv.x, uv.y, height + skirtOffset), CesiumTerrainProvider._scratchQPoint2d, mesh.normals[index]);
} else {
mesh.addVertex(projection.getPoint(uv.x, uv.y, height + skirtOffset), CesiumTerrainProvider._scratchQPoint2d);
}
if (i) {
this.addTriangle(mesh, index, indices[i - 1], mesh.nextPointIndex - 2);
this.addTriangle(mesh, index, mesh.nextPointIndex - 2, mesh.nextPointIndex - 1);
}
}
}
public override get requestOptions(): RequestOptions {
return { method: "GET", responseType: "arraybuffer", headers: { authorization: `Bearer ${this._accessToken}` }, accept: "application/vnd.quantized-mesh;" /* extensions=octvertexnormals, */ + "application/octet-stream;q=0.9,*/*;q=0.01" };
}
public override constructUrl(row: number, column: number, zoomLevel: number): string {
return this._tileUrlTemplate.replace("{z}", (zoomLevel - 1).toString()).replace("{x}", column.toString()).replace("{y}", row.toString());
}
public getChildHeightRange(quadId: QuadId, rectangle: MapCartoRectangle, parent: MapTile): Range1d | undefined {
return (quadId.level <= ApproximateTerrainHeights.maxLevel) ? ApproximateTerrainHeights.instance.getMinimumMaximumHeights(rectangle) : (parent).heightRange;
}
/**
* Specifies the quality of terrain created from heightmaps. A value of 1.0 will
* ensure that adjacent heightmap vertices are separated by no more than
* screen pixels and will probably go very slowly.
* A value of 0.5 will cut the estimated level zero geometric error in half, allowing twice the
* screen pixels between adjacent heightmap vertices and thus rendering more quickly.
* @type {Number}
*/
public readonly heightmapTerrainQuality = 0.25;
/**
* Determines an appropriate geometric error estimate when the geometry comes from a heightmap.
*
* @param {Ellipsoid} ellipsoid The ellipsoid to which the terrain is attached.
* @param {Number} tileImageWidth The width, in pixels, of the heightmap associated with a single tile.
* @param {Number} numberOfTilesAtLevelZero The number of tiles in the horizontal direction at tile level zero.
* @returns {Number} An estimated geometric error.
*/
public getEstimatedLevelZeroGeometricErrorForAHeightmap(ellipsoidMaximumRadius = 6378137, tileImageWidth = 65, numberOfTilesAtLevelZero = 2) {
return ellipsoidMaximumRadius * 2 * Math.PI * this.heightmapTerrainQuality / (tileImageWidth * numberOfTilesAtLevelZero);
}
public getLevelMaximumGeometricError(level: number) {
return this.getEstimatedLevelZeroGeometricErrorForAHeightmap() / (1 << level);
}
public getHeightRange(parentRange: Range1d, quadId: QuadId): Range1d {
const heightRange = quadId.level <= 6 ? ApproximateTerrainHeights.instance.getTileHeightRange(quadId) : undefined;
return undefined === heightRange ? parentRange : heightRange;
}
} | the_stack |
import { WriteStream } from "fs";
import { GraphQLArgument, GraphQLField, GraphQLFieldMap, GraphQLInterfaceType, GraphQLList, GraphQLNamedType, GraphQLNonNull, GraphQLObjectType, GraphQLType, GraphQLUnionType } from "graphql";
import { targetTypeOf, instancePrefix } from "./Utils";
import { GeneratorConfig } from "./GeneratorConfig";
import { ImportingBehavior, Writer } from "./Writer";
import { FetcherContext } from "./FetcherContext";
import { throws } from "assert";
export class FetcherWriter extends Writer {
protected readonly fetcherTypeName: string;
protected readonly defaultFetcherProps: string[];
readonly emptyFetcherName: string;
readonly defaultFetcherName: string | undefined;
readonly fieldMap: GraphQLFieldMap<any, any>;
protected fieldArgsMap: Map<string, GraphQLArgument[]>;
protected fieldCategoryMap: Map<string, string>;
protected hasArgs: boolean;
private _declaredFieldNames?: ReadonlySet<string>;
constructor(
protected modelType: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType,
protected ctx: FetcherContext,
stream: WriteStream,
config: GeneratorConfig
) {
super(stream, config);
this.fetcherTypeName = `${this.modelType.name}${config.fetcherSuffix ?? "Fetcher"}`;
if (modelType instanceof GraphQLUnionType) {
const map: { [key: string]: GraphQLField<any, any> } = {};
const itemCount = modelType.getTypes().length;
if (itemCount !== 0) {
const fieldCountMap = new Map<string, number>();
for (const type of modelType.getTypes()) {
for (const fieldName in type.getFields()) {
fieldCountMap.set(fieldName, (fieldCountMap.get(fieldName) ?? 0) + 1);
}
}
const firstTypeFieldMap = modelType.getTypes()[0].getFields();
for (const fieldName in firstTypeFieldMap) {
if (fieldCountMap.get(fieldName) === itemCount) {
map[fieldName] = firstTypeFieldMap[fieldName]!;
}
}
}
this.fieldMap = map;
} else {
this.fieldMap = modelType.getFields();
}
const fieldArgsMap = new Map<string, GraphQLArgument[]>();
const fieldCategoryMap = new Map<string, string>();
const defaultFetcherProps: string[] = [];
this.hasArgs = false;
for (const fieldName in this.fieldMap) {
const field = this.fieldMap[fieldName]!;
const targetType = targetTypeOf(field.type);
if (this.modelType.name !== "Query" && this.modelType.name !== "Mutation" && targetType === undefined && field.args.length === 0) {
if (config.defaultFetcherExcludeMap !== undefined) {
const excludeProps = config.defaultFetcherExcludeMap[modelType.name];
if (excludeProps !== undefined && excludeProps.filter(name => name === fieldName).length !== 0) {
continue;
}
}
defaultFetcherProps.push(fieldName);
}
if (field.args.length !== 0) {
fieldArgsMap.set(fieldName, field.args);
}
const fieldCoreType =
field.type instanceof GraphQLNonNull ?
field.type.ofType :
field.type;
if (this.ctx.embeddedTypes.has(fieldCoreType)) {
fieldCategoryMap.set(fieldName, "SCALAR");
} else if (this.ctx.connections.has(fieldCoreType)) {
fieldCategoryMap.set(fieldName, "CONNECTION");
} else if (fieldCoreType instanceof GraphQLList) {
const elementType =
fieldCoreType.ofType instanceof GraphQLNonNull ?
fieldCoreType.ofType.ofType :
fieldCoreType.ofType;
if (elementType instanceof GraphQLObjectType ||
elementType instanceof GraphQLInterfaceType ||
elementType instanceof GraphQLUnionType
) {
fieldCategoryMap.set(fieldName, "LIST");
}
} else if (fieldCoreType instanceof GraphQLObjectType ||
fieldCoreType instanceof GraphQLInterfaceType ||
fieldCoreType instanceof GraphQLUnionType
) {
fieldCategoryMap.set(fieldName, "REFERENCE");
} else if (this.ctx.idFieldMap.get(this.modelType) === field) {
fieldCategoryMap.set(fieldName, "ID");
} else {
fieldCategoryMap.set(fieldName, "SCALAR");
}
if (field.args.length !== 0) {
this.hasArgs = true;
}
}
this.defaultFetcherProps = defaultFetcherProps;
this.fieldArgsMap = fieldArgsMap;
this.fieldCategoryMap = fieldCategoryMap;
let prefix = instancePrefix(this.modelType.name);
this.emptyFetcherName = `${prefix}$`;
this.defaultFetcherName = defaultFetcherProps.length !== 0 ? `${prefix}$$` : undefined;
}
protected prepareImportings() {
if (this.hasArgs) {
this.importStatement("import type { AcceptableVariables, UnresolvedVariables, FieldOptions, DirectiveArgs } from 'graphql-ts-client-api';");
} else {
this.importStatement("import type { FieldOptions, DirectiveArgs } from 'graphql-ts-client-api';");
}
const importedFetcherTypeNames = new Set<string>();
importedFetcherTypeNames.add(this.superFetcherTypeName(this.modelType));
for (const fieldName in this.fieldMap) {
const field = this.fieldMap[fieldName];
const targetType = targetTypeOf(field.type);
if (targetType !== undefined) {
importedFetcherTypeNames.add(this.superFetcherTypeName(targetType));
}
}
this.importStatement(`import { ${Array.from(importedFetcherTypeNames).join(", ")}, createFetcher, createFetchableType } from 'graphql-ts-client-api';`);
if (this.modelType.name !== "Query" && this.modelType.name !== "Mutation") {
this.importStatement("import type { WithTypeName, ImplementationType } from '../CommonTypes';");
}
for (const fieldName in this.fieldMap) {
const field = this.fieldMap[fieldName];
this.importFieldTypes(field);
}
const upcastTypes = this.ctx.inheritanceInfo.upcastTypeMap.get(this.modelType);
if (upcastTypes !== undefined) {
for (const upcastType of upcastTypes) {
this.importStatement(`import { ${
this.importedNamesForSuperType(upcastType).join(", ")
} } from './${upcastType.name}${this.config.fetcherSuffix ?? "Fetcher"}';`);
}
}
}
protected importedNamesForSuperType(superType: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType): string[] {
return [ `${instancePrefix(superType.name)}$` ];
}
protected importingBehavior(type: GraphQLNamedType): ImportingBehavior {
if (type === this.modelType) {
return "SELF";
}
if (type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType) {
return "SAME_DIR";
}
return "OTHER_DIR";
}
protected writeCode() {
const t = this.text.bind(this);
t(COMMENT);
t("export interface ");
t(this.fetcherTypeName);
t("<T extends object, TVariables extends object> extends ");
t(this.superFetcherTypeName(this.modelType));
t("<'");
t(this.modelType.name);
t("', T, TVariables> ");
this.scope({type: "BLOCK", multiLines: true, suffix: "\n"}, () => {
this.writeFragmentMethods();
this.writeDirective();
this.writeTypeName();
for (const fieldName in this.fieldMap) {
this.text("\n");
const field = this.fieldMap[fieldName]!;
this.writePositiveProp(field);
this.writeNegativeProp(field);
}
});
this.writeInstances();
this.writeArgsInterface();
}
protected writeFragmentMethods() {
const t = this.text.bind(this);
if (this.modelType.name !== "Query" && this.modelType.name !== "Mutation") {
t(`\non<XName extends ImplementationType<'${this.modelType.name}'>, X extends object, XVariables extends object>`);
this.scope({type: "PARAMETERS", multiLines: !(this.modelType instanceof GraphQLUnionType)}, () => {
t(`child: ${this.superFetcherTypeName(this.modelType)}<XName, X, XVariables>`);
if (!(this.modelType instanceof GraphQLUnionType)) {
this.separator(", ");
t("fragmentName?: string // undefined: inline fragment; otherwise, otherwise, real fragment");
}
});
t(`: ${this.fetcherTypeName}`);
this.scope({type: "GENERIC", multiLines: true}, () => {
t(`XName extends '${this.modelType.name}' ?\n`);
t("T & X :\n");
t(`WithTypeName<T, ImplementationType<'${this.modelType.name}'>> & `);
this.scope({type: "BLANK", multiLines: true, prefix: "(", suffix: ")"}, () => {
t("WithTypeName<X, ImplementationType<XName>>");
this.separator(" | ");
t(`{__typename: Exclude<ImplementationType<'${this.modelType}'>, ImplementationType<XName>>}`);
});
this.separator(", ");
t("TVariables & XVariables");
});
t(";\n");
}
}
private writeDirective() {
const t = this.text.bind(this);
t(`\n\ndirective(name: string, args?: DirectiveArgs): ${this.fetcherTypeName}<T, TVariables>;\n`);
}
private writeTypeName() {
if (this.modelType.name !== "Query" && this.modelType.name !== "Mutation") {
const t = this.text.bind(this);
t("\n\n");
t("readonly __typename: ");
t(this.fetcherTypeName);
t("<T & {__typename: ImplementationType<'");
t(this.modelType.name);
t("'>}, TVariables>;\n");
}
}
private writePositiveProp(field: GraphQLField<unknown, unknown>) {
const targetType = targetTypeOf(field.type);
this.writePositivePropImpl(field, "SIMPLEST");
this.writePositivePropImpl(field, "WITH_ARGS");
this.writePositivePropImpl(field, "WITH_OTPIONS");
this.writePositivePropImpl(field, "FULL");
}
private writeNegativeProp(field: GraphQLField<unknown, unknown>) {
if (field.args.length !== 0 || targetTypeOf(field.type) !== undefined) {
return;
}
const t = this.text.bind(this);
t('\nreadonly "~');
t(field.name);
t('": ');
t(this.fetcherTypeName);
t("<Omit<T, '");
t(field.name);
t("'>, TVariables>;\n");
}
private writePositivePropImpl(field: GraphQLField<unknown, unknown>, mode: "SIMPLEST" | "WITH_ARGS" | "WITH_OTPIONS" | "FULL") {
const withArgs = mode === "WITH_ARGS" || mode === "FULL";
if (withArgs && field.args.length === 0) {
return;
}
const targetType = targetTypeOf(field.type);
const withOptions = mode === "WITH_OTPIONS" || mode === "FULL";
const renderAsField = field.args.length === 0 && targetType === undefined && !withOptions;
const namePlus = field.args.length === 0 && targetType === undefined && withOptions;
const nonNull = field.type instanceof GraphQLNonNull;
const t = this.text.bind(this);
t("\n");
if (renderAsField) {
t("readonly ");
t(field.name);
} else {
t(namePlus ? `"${field.name}+"` : field.name);
if (withArgs || targetType !== undefined || withOptions) {
this.scope({type: "GENERIC", multiLines: true}, () => {
if (withArgs) {
this.separator(", ");
t(`XArgs extends AcceptableVariables<${this.modelType.name}Args['${field.name}']>`);
}
if (targetType !== undefined) {
this.separator(", ");
t("X extends object");
this.separator(", ");
t("XVariables extends object");
}
if (withOptions) {
this.separator(", ");
t(`XAlias extends string = "${field.name}"`);
if (nonNull) {
this.separator(", ");
t(`XDirectives extends { readonly [key: string]: DirectiveArgs } = {}`);
}
this.separator(", ");
t(`XDirectiveVariables extends object = {}`);
}
});
}
this.scope({ type: "PARAMETERS", multiLines: true }, () => {
if (withArgs) {
this.separator(", ");
t("args: XArgs");
}
if (targetType !== undefined) {
this.separator(", ");
t("child: ");
t(this.superFetcherTypeName(targetType));
t("<'");
t(targetType.name);
t("', X, XVariables>");
}
if (withOptions) {
this.separator(", ");
t("optionsConfigurer: ");
this.scope({type: "PARAMETERS", multiLines: true}, () => {
t(`options: FieldOptions<"${field.name}", {}, {}>`);
});
t(` => FieldOptions<XAlias, ${nonNull ? "XDirectives" : "{readonly [key: string]: DirectiveArgs}"}, XDirectiveVariables>`);
}
});
}
t(": ");
t(this.fetcherTypeName);
this.scope({type: "GENERIC", multiLines: !renderAsField, suffix: ";\n"}, () => {
t("T & ");
if (withOptions && nonNull) {
this.scope({type: "PARAMETERS", multiLines: true}, () => {
t("XDirectives extends { readonly include: any } | { readonly skip: any } ? ");
this.scope({type: "BLANK", multiLines: true}, () => {
this.writePositivePropChangedDataType(field, withOptions, true);
this.separator(" : ");
this.writePositivePropChangedDataType(field, withOptions, false);
});
});
} else {
this.writePositivePropChangedDataType(field, withOptions, !nonNull);
}
this.separator(", ");
t("TVariables");
if (targetType !== undefined) {
t(" & XVariables");
}
if (field.args.length !== 0) {
if (withArgs) {
t(` & UnresolvedVariables<XArgs, ${this.modelType.name}Args['${field.name}']>`);
} else {
t(` & ${this.modelType.name}Args["${field.name}"]`);
}
}
if (withOptions) {
t(" & XDirectiveVariables");
}
});
}
private writePositivePropChangedDataType(field: GraphQLField<unknown, unknown>, withOptions: boolean, nullable: boolean) {
const t = this.text.bind(this);
t("{");
if (!this.config.objectEditable) {
t("readonly ");
}
if (withOptions) {
t(`[key in XAlias]`);
} else {
t(`"${field.name}"`);
}
if (nullable) {
t("?");
}
t(": ");
this.typeRef(field.type, targetTypeOf(field.type) !== undefined ? "X" : undefined);
t("}");
}
private writeInstances() {
const t = this.text.bind(this);
const itemTypes = this.modelType instanceof GraphQLUnionType ? this.modelType.getTypes() : [];
t("\nexport const ");
t(this.emptyFetcherName);
t(": ");
t(this.fetcherTypeName)
t("<{}, {}> = ")
this.scope({type: "BLANK", multiLines: true, suffix: ";\n"}, () => {
t("createFetcher")
this.scope({type: "PARAMETERS", multiLines: true}, () => {
t("createFetchableType")
this.scope({type: "PARAMETERS", multiLines: true}, () => {
t(`"${this.modelType.name}"`);
this.separator(", ");
if (this.ctx.embeddedTypes.has(this.modelType)) {
t('"EMBEDDED"');
} else if (this.ctx.connections.has(this.modelType)) {
t('"CONNECTION"');
} else if (this.ctx.edgeTypes.has(this.modelType)) {
t('"EDGE"');
} else {
t('"OBJECT"');
}
this.separator(", ");
this.scope({type: "ARRAY"}, () => {
const upcastTypes = this.ctx.inheritanceInfo.upcastTypeMap.get(this.modelType);
if (upcastTypes !== undefined) {
for (const upcastType of upcastTypes) {
this.separator(", ");
t(`${instancePrefix(upcastType.name)}$.fetchableType`);
}
}
});
this.separator(", ");
this.scope({type: "ARRAY", multiLines: true }, () => {
for (const declaredFieldName of this.declaredFieldNames) {
const field = this.fieldMap[declaredFieldName];
this.separator(", ");
const args = this.fieldArgsMap.get(declaredFieldName);
const category = this.fieldCategoryMap.get(declaredFieldName);
const targetType = targetTypeOf(field.type);
if (args === undefined &&
(category === undefined || category === "SCALAR") &&
field.type instanceof GraphQLNonNull
) {
if (targetType === undefined) {
t(`"${declaredFieldName}"`);
} else {
this.scope({type: "BLOCK", multiLines: true}, () => {
t(`category: "SCALAR"`);
this.separator(", ");
t(`name: "${declaredFieldName}"`);
this.separator(", ");
t(`targetTypeName: "${targetType.name}"`);
});
}
} else {
this.scope({type: "BLOCK", multiLines: true}, () => {
t(`category: "${category ?? 'SCALAR'}"`);
this.separator(", ");
t(`name: "${declaredFieldName}"`);
if (args !== undefined) {
this.separator(", ");
t("argGraphQLTypeMap: ");
this.scope({type: "BLOCK", multiLines: args.length > 1}, () => {
for (const arg of args) {
this.separator(", ");
t(arg.name);
t(": '");
this.gqlTypeRef(arg.type);
t("'");
}
});
}
if (targetType !== undefined) {
this.separator(", ");
const connection = this.ctx.connections.get(targetType);
if (connection !== undefined) {
t(`connectionTypeName: "${targetType.name}"`);
this.separator(", ");
t(`edgeTypeName: "${connection.edgeType.name}"`);
this.separator(", ");
t(`targetTypeName: "${connection.nodeType.name}"`);
} else {
t(`targetTypeName: "${targetType.name}"`);
}
}
if (!(field.type instanceof GraphQLNonNull)) {
this.separator(", ");
t("undefinable: true");
}
});
}
}
});
});
this.separator(", ");
if (itemTypes.length === 0) {
t("undefined");
} else {
this.scope({type: "ARRAY", multiLines: itemTypes.length >= 2}, () => {
for (const itemType of itemTypes) {
this.separator(", ");
this.str(itemType.name);
}
});
}
});
});
if (this.defaultFetcherName !== undefined) {
t("\nexport const ");
t(this.defaultFetcherName);
t(" = ");
this.enter("BLANK", true);
t(this.emptyFetcherName);
this.enter("BLANK", true);
for (const propName of this.defaultFetcherProps) {
t(".");
t(propName);
t("\n");
}
this.leave();
this.leave(";\n");
}
}
private writeArgsInterface() {
if (!this.hasArgs) {
return;
}
const t = this.text.bind(this);
t(`\nexport interface ${this.modelType.name}Args `);
this.scope({type: "BLOCK", multiLines: true, suffix: "\n"}, () => {
for (const fieldName in this.fieldMap) {
const field = this.fieldMap[fieldName];
if (field.args.length !== 0) {
this.separator(", ");
t(`\nreadonly ${field.name}: `);
this.scope({type: "BLOCK", multiLines: true}, () => {
for (const arg of field.args) {
this.separator(", ");
t("readonly ");
t(arg.name);
if (!(arg.type instanceof GraphQLNonNull)) {
t("?");
}
t(": ");
this.typeRef(arg.type)
}
});
}
}
});
}
protected get declaredFieldNames(): ReadonlySet<string> {
let set = this._declaredFieldNames;
if (set === undefined) {
this._declaredFieldNames = set = this.getDeclaredFieldNames();
}
return set;
}
private getDeclaredFieldNames(): ReadonlySet<string> {
const fields = new Set<string>();
if (this.modelType instanceof GraphQLObjectType || this.modelType instanceof GraphQLInterfaceType) {
const fieldMap = this.modelType.getFields();
for (const fieldName in fieldMap) {
fields.add(fieldMap[fieldName]!.name);
}
this.removeSuperFieldNames(fields, this.ctx.inheritanceInfo.upcastTypeMap.get(this.modelType));
}
return fields;
}
private removeSuperFieldNames(fields: Set<string>, superTypes?: Set<GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType>) {
if (superTypes !== undefined) {
for (const superType of superTypes) {
if (superType instanceof GraphQLObjectType || superType instanceof GraphQLInterfaceType) {
const superFieldMap = superType.getFields();
for (const superFieldName in superFieldMap) {
fields.delete(superFieldName);
}
}
this.removeSuperFieldNames(fields, this.ctx.inheritanceInfo.upcastTypeMap.get(superType));
}
}
}
private superFetcherTypeName(graphQLType: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType): string {
if (this.ctx.connections.has(graphQLType)) {
return "ConnectionFetcher";
}
if (this.ctx.edgeTypes.has(graphQLType)) {
return "EdgeFetcher";
}
return "ObjectFetcher";
}
}
const COMMENT = `/*
* Any instance of this interface is immutable,
* all the properties and functions can only be used to create new instances,
* they cannot modify the current instance.
*
* So any instance of this interface is reuseable.
*/
`; | the_stack |
import { getRandStr, sleep } from '@cromwell/core';
import { serverMessages } from '@cromwell/core-backend/dist/helpers/constants';
import { getLogger } from '@cromwell/core-backend/dist/helpers/logger';
import { getServerBuildPath } from '@cromwell/core-backend/dist/helpers/paths';
import { ChildProcess, fork } from 'child_process';
import fs from 'fs-extra';
import tcpPortUsed from 'tcp-port-used';
import { restartMessage } from './constants';
import { loadEnv } from './settings';
const logger = getLogger();
/**
* Proxy manager
*/
type ServerInfo = {
id?: string;
port?: number;
childInst?: ChildProcess;
}
const activeServer: ServerInfo & {
proxyPort?: number
} = {};
let isRestarting = false;
let isPendingRestart = false;
const madeServers: Record<string, ServerInfo> = {};
export const getServerPort = () => activeServer.port;
/** Used only at Proxy startup. Should not be called from any other place */
export const launchServerManager = async (proxyPort?: number, init?: boolean) => {
activeServer.proxyPort = proxyPort;
if (activeServer.port) {
logger.warn('Proxy manager: called launch, but Server was already launched!')
}
try {
const info = await makeServer(init);
updateActiveServer(info);
} catch (error) {
logger.error('Proxy manager could not launch API server', error);
}
}
const makeServer = async (init?: boolean): Promise<ServerInfo> => {
const info: ServerInfo = {};
const env = loadEnv();
if (env.envMode === 'dev') logger.info('Proxy manager: Launching new API server...');
const serverId = getRandStr(8);
info.id = serverId;
const buildPath = getServerBuildPath();
if (!buildPath || !fs.existsSync(buildPath)) {
const msg = 'Proxy manager: could not find server build at: ' + buildPath;
logger.error(msg);
throw new Error(msg);
}
const serverProc = fork(
buildPath,
[
env.scriptName,
activeServer.proxyPort ? `proxy-port=${activeServer.proxyPort}` : '',
init ? '--init' : '',
],
{ stdio: 'inherit', cwd: process.cwd() }
);
parentRegisterChild(serverProc, info);
info.childInst = serverProc;
let hasReported = false;
await new Promise(done => {
setTimeout(() => {
if (!hasReported) done(false);
}, 90000);
serverProc.on('message', (message) => {
let msg;
try {
msg = JSON.parse(String(message));
} catch (error) {
logger.error(error);
}
if (msg.message === restartMessage) {
restartServer();
}
if (msg.message === serverMessages.onStartMessage) {
if (process.send) process.send(serverMessages.onStartMessage);
info.port = msg.port
hasReported = true;
done(true);
}
if (msg.message === serverMessages.onStartErrorMessage) {
if (process.send) process.send(serverMessages.onStartErrorMessage);
hasReported = true;
done(false);
}
});
});
if (!info.port) throw new Error('Proxy manager: Failed to start API server');
try {
await tcpPortUsed.waitUntilUsed(info.port, 500, 8000);
} catch (error) {
logger.error(error);
}
madeServers[serverId] = info;
return info;
}
const closeServer = async (info: ServerInfo) => {
const env = loadEnv();
if (env.envMode === 'dev')
logger.info(`Proxy manager: killing API server at port: ${info.port}...`);
info.childInst?.kill();
}
/** Safely restarts server instance */
const restartServer = async () => {
if (isRestarting) {
isPendingRestart = true;
return;
}
const env = loadEnv();
if (env.envMode === 'dev')
logger.info('Proxy manager: restarting API server...');
isRestarting = true;
// Make new server first
let newServer: ServerInfo;
const oldServer = { ...activeServer };
try {
newServer = await makeServer();
} catch (error) {
logger.error('Proxy manager: Failed to launch new API server', error);
isRestarting = false;
if (isPendingRestart) {
isPendingRestart = false;
await restartServer();
}
return;
}
await sleep(0.5);
// Update info to redirect proxy on the new server
updateActiveServer(newServer);
// Wait in case if the old server is still processing any long-lasting requests
await sleep(4);
// Kill the old server
try {
await closeServer(oldServer);
await tcpPortUsed.waitUntilFree(oldServer.port, 500, 5000);
} catch (error) {
logger.error('Proxy manager: Failed to kill old API server at ' + oldServer.port, error);
}
isRestarting = false;
if (isPendingRestart) {
isPendingRestart = false;
await restartServer();
}
}
const updateActiveServer = (info: ServerInfo) => {
Object.keys(info).forEach(key => {
activeServer[key] = info[key];
})
}
export const serverAliveWatcher = async () => {
await sleep(60);
// Watch for the active server and if it's not alive for some reason, restart / make new
let isAlive = true;
if (!activeServer.port) {
isAlive = false;
}
try {
if (activeServer.port) {
isAlive = await tcpPortUsed.check(activeServer.port, '127.0.0.1');
}
} catch (error) { }
if (!isAlive) {
logger.error('Proxy manager watcher: API Server is not alive. Restarting...');
await restartServer();
}
// Watch for other created servers that aren't active and kill them.
// Basically they shouldn't be created in the first place, but we have
// IPC API for child servers and they can create new instances, so who knows...
for (const info of Object.values(madeServers)) {
if (info?.port && info.port !== activeServer.port && info.childInst) {
if (await checkServerAlive(info)) {
// Found other server that is alive
setTimeout(async () => {
try {
if (info?.port && info.port !== activeServer.port && await tcpPortUsed.check(info.port, '127.0.0.1')) {
// If after 50 seconds it's still alive and is not active, kill it
await closeServer(info)
info.childInst = undefined;
info.port = undefined;
}
} catch (error) {
logger.error(error);
}
}, 60000);
}
}
}
serverAliveWatcher();
}
const checkServerAlive = async (info: ServerInfo) => {
if (info?.port) {
try {
if (await tcpPortUsed.check(info.port, '127.0.0.1')) {
return true;
}
} catch (error) {
logger.error(error);
}
}
return false;
}
const onMessageCallbacks: (((msg: any) => any) | undefined)[] = [];
export const childRegister = (port: number) => {
updateActiveServer({ port });
if (process.send) process.send(JSON.stringify({
message: serverMessages.onStartMessage,
port: port,
}));
process.on('message', (m) => {
onMessageCallbacks.forEach(cb => cb?.(m));
});
}
type IPCMessageType = 'make-new' | 'apply-new' | 'restart-me' | 'kill-me' | 'success' | 'failed';
type IPCMessage = {
id: string;
message: IPCMessageType;
payload?: any;
port?: number;
}
export const childSendMessage = async (message: IPCMessageType, payload?: any): Promise<IPCMessage> => {
const messageId = getRandStr(8);
let responseResolver;
const responsePromise = new Promise<IPCMessage>(res => responseResolver = res);
const cb = (message) => {
message = JSON.parse(message);
if (message.id === messageId) {
responseResolver(message)
}
}
onMessageCallbacks.push(cb);
if (process.send) process.send(JSON.stringify({
id: messageId,
port: activeServer.port,
message,
payload,
} as IPCMessage));
const resp = await responsePromise;
delete onMessageCallbacks[onMessageCallbacks.indexOf(cb)];
return resp;
}
const parentRegisterChild = (child: ChildProcess, childInfo: ServerInfo) => {
child.on('message', async (msg: any) => {
try {
const message: IPCMessage = JSON.parse(msg);
if (message.message === 'make-new') {
try {
const info = await makeServer();
if (!info.port) throw new Error('!info.port')
if (!(await checkServerAlive(info))) throw new Error('new server is not alive')
if (await checkServerAlive(childInfo)) {
child.send(JSON.stringify({
id: message.id,
message: 'success',
payload: info.id,
} as IPCMessage));
}
return;
} catch (error) {
if (await checkServerAlive(childInfo)) {
child.send(JSON.stringify({
id: message.id,
message: 'failed',
} as IPCMessage));
}
logger.error(error);
return;
}
}
if (message.message === 'apply-new' && message.payload) {
const port = madeServers[message.payload]?.port;
if (port) {
const isAlive = await checkServerAlive({ port });
if (!isAlive) {
if (await checkServerAlive(childInfo)) {
child.send(JSON.stringify({
id: message.id,
message: 'failed',
} as IPCMessage));
}
return;
} else {
updateActiveServer(madeServers[message.payload]);
await sleep(1);
if (await checkServerAlive(childInfo)) {
child.send(JSON.stringify({
id: message.id,
message: 'success',
} as IPCMessage));
}
return;
}
}
}
if (message.message === 'kill-me') {
await closeServer({
childInst: child
});
return;
}
if (message.message === 'restart-me') {
await restartServer();
return;
}
if (message.id) {
if (await checkServerAlive(childInfo)) {
child.send(JSON.stringify({
id: message.id,
message: 'failed',
} as IPCMessage));
}
}
} catch (error) {
logger.error(error);
}
});
}
export const closeAllServers = () => {
Object.values(madeServers).forEach(closeServer);
} | the_stack |
import { Grid } from '../../../src/grid/base/grid';
import { Column } from '../../../src/grid/models';
import { createElement, remove, EmitType } from '@syncfusion/ej2-base';
import { data, employeeData } from '../base/datasource.spec';
import { Freeze } from '../../../src/grid/actions/freeze';
import { Aggregate } from '../../../src/grid/actions/aggregate';
import { Edit } from '../../../src/grid/actions/edit';
import { createGrid, destroy } from '../base/specutil.spec';
import { profile, inMB, getMemoryProfile } from '../base/common.spec';
import { getScrollBarWidth } from '../../../src/grid/base/util';
Grid.Inject(Freeze, Aggregate, Edit);
describe('Freeze render module', () => {
describe('Freeze Row and Column', () => {
let gridObj: any;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: data,
frozenColumns: 2,
frozenRows: 2,
height: 400,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('Frozen Header testing', () => {
expect(gridObj.getHeaderContent().querySelector('.e-frozenheader').querySelector('tbody').childElementCount).toBe(2);
expect(gridObj.getHeaderContent().querySelector('.e-frozenheader')
.querySelector('tbody').children[0].childElementCount).toBe(2);
expect(gridObj.getHeaderContent().querySelector('.e-frozenheader').querySelector('tr').children[0].childElementCount).toBe(2);
});
it('Movable Header testing', () => {
expect(gridObj.getHeaderContent().querySelector('.e-movableheader').querySelector('tbody').childElementCount).toBe(2);
});
it('Frozen Content testing', () => {
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').children[0].childElementCount).toBe(2);
});
it('Movable Content testing', () => {
expect(gridObj.getContent().querySelector('.e-movablecontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
});
it('check scroll left header/content sync', () => {
let ele: HTMLElement = gridObj.getContent().querySelector('.e-movablecontent') as HTMLElement;
(<HTMLElement>ele).scrollLeft = 10;
raise(gridObj, 'scroll', ele);
(<HTMLElement>ele).scrollTop = 10;
raise(gridObj, 'scroll', ele);
(<HTMLElement>ele).scrollTop = 10;
raise(gridObj, 'scroll', ele);
(<HTMLElement>gridObj.getContent().querySelector('.e-frozencontent')).scrollTop = 20;
raise(gridObj, 'wheel', <HTMLElement>gridObj.getContent().querySelector('.e-frozencontent'));
gridObj.isDestroyed = true;
(<HTMLElement>ele).scrollTop = 10;
raise(gridObj, 'scroll', ele);
(<HTMLElement>gridObj.getContent().querySelector('.e-frozencontent')).scrollTop = 20;
raise(gridObj, 'wheel', <HTMLElement>gridObj.getContent().querySelector('.e-frozencontent'));
raise(gridObj, 'touchstart', <HTMLElement>gridObj.getContent().querySelector('.e-frozencontent'));
(<HTMLElement>gridObj.getContent().querySelector('.e-frozencontent')).scrollTop = 30;
raise(gridObj, 'touchmove', <HTMLElement>gridObj.getContent().querySelector('.e-frozencontent'));
raise(gridObj, 'touchstart', <HTMLElement>gridObj.getHeaderContent().querySelector('.e-movableheader'));
(<HTMLElement>gridObj.getHeaderContent().querySelector('.e-movableheader')).scrollLeft = 30;
raise(gridObj, 'touchmove', <HTMLElement>gridObj.getHeaderContent().querySelector('.e-movableheader'));
let args = { target: gridObj.getContent().querySelector('.e-frozencontent'), touches: [{ pageY: 200 }] };
gridObj.scrollModule.getPointXY(args);
let arg = { target: gridObj.getContent().querySelector('.e-frozencontent') };
gridObj.scrollModule.getPointXY(arg);
remove(gridObj.getContent().querySelector('tbody'));
remove(gridObj.getContent().querySelector('tbody'));
(<HTMLElement>ele).scrollTop = 10;
raise(gridObj, 'scroll', ele);
(<HTMLElement>gridObj.getContent().querySelector('.e-frozencontent')).scrollTop = 20;
raise(gridObj, 'wheel', <HTMLElement>gridObj.getContent().querySelector('.e-frozencontent'));
});
let raise: Function = (gridObj: Grid, type: string, ele: HTMLElement) => {
let evt: Event = document.createEvent('HTMLEvents');
evt.initEvent(type, true, true);
ele.dispatchEvent(evt);
};
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
let destroy: EmitType<Object> = (grid: Grid) => {
if (grid) {
grid.destroy();
document.getElementById('Grid').remove();
}
};
describe('Freeze Row', () => {
let gridObj: Grid;
let dBound: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
frozenRows: 2,
height: 400,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('Frozen Header testing', () => {
expect(gridObj.getHeaderContent().querySelector('tbody').childElementCount).toBe(2);
});
it('Movable Content testing', () => {
expect(gridObj.getContent().querySelector('tbody').childElementCount).toBeGreaterThan(1);
});
it('on property change', () => {
dBound = (args?: Object): void => {
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').children[0].childElementCount).toBe(2);
expect(gridObj.getContent().querySelector('.e-movablecontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
expect(gridObj.getHeaderContent().querySelector('.e-frozenheader')
.querySelector('tbody').children[0].childElementCount).toBe(2);
expect(gridObj.getHeaderContent().querySelector('.e-movableheader').querySelector('tbody').childElementCount).toBe(2);
};
gridObj.frozenColumns = 2;
gridObj.dataBound = dBound;
gridObj.dataBind();
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('Freeze Column', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
frozenColumns: 2,
height: 400,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('Frozen Content testing', () => {
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').children[0].childElementCount).toBe(2);
});
it('Movable Content testing', () => {
gridObj.isDestroyed = true;
(gridObj as any).freezeModule.addEventListener();
gridObj.isDestroyed = false;
expect(gridObj.getContent().querySelector('.e-movablecontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
});
it('Add aggregates', () => {
gridObj.aggregates = [{
columns: [{
type: 'Sum',
field: 'EmployeeID',
footerTemplate: 'Sum: ${Sum}'
}]
},
{
columns: [{
type: 'Max',
field: 'EmployeeID',
footerTemplate: 'Max: ${Max}'
}]
}];
});
it('Ensure aggregate row visiblity', () => {
let isHide: boolean = gridObj.element.querySelector('.e-frozenfootercontent').querySelector('.e-summaryrow').classList.contains('e-hide');
expect(isHide).toBe(false);
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('Without Freeze', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
frozenColumns: 0,
frozenRows: 0,
height: 400,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('header content rendering', () => {
// Test case for header content rendering
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Freeze Column', () => {
let gridObj: Grid;
let dBound: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
height: 400,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID', isFrozen: true },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
aggregates: [{
columns: [{
type: 'Count',
field: 'ShipCity',
footerTemplate: 'Count: ${count}'
}]
}],
}, done);
});
it('Frozen Content testing', () => {
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
expect(gridObj.getContent().querySelector('.e-frozencontent').querySelector('tbody').children[0].childElementCount).toBe(1);
});
it('Movable Content testing', () => {
expect(gridObj.getContent().querySelector('.e-movablecontent').querySelector('tbody').childElementCount).toBeGreaterThan(1);
});
it('Aggregate checking', () => {
expect(gridObj.element.querySelector('.e-summarycontent').childNodes.length).toBe(2);
});
it('clip board testing', () => {
gridObj.selectRow(2);
gridObj.copy();
expect((<any>gridObj.clipboardModule).copyContent).toBe('HANAR 10250 4 Brazil Rio de Janeiro');
});
it('copy with header', () => {
gridObj.copy(true);
expect((<any>gridObj.clipboardModule).copyContent).toBe('CustomerID OrderID EmployeeID ShipCountry ShipCity\nHANAR 10250 4 Brazil Rio de Janeiro');
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
it('Ensure the grid table while dynamically disable isFrozen in the Grid column', (done: Function) => {
(gridObj.columns[1] as Column).isFrozen = false;
let dataBound = (args: Object) => {
expect(gridObj.getContent().querySelector('.e-frozencontent')).toBeNull();
done();
};
gridObj.dataBound = dataBound;
gridObj.refreshColumns();
});
it('Ensure the grid table while dynamically enable isFrozen in the Grid column', (done: Function) => {
(gridObj.columns[1] as Column).isFrozen = true;
let dataBound = (args: Object) => {
expect(gridObj.getContent().querySelector('.e-frozencontent')).not.toBeUndefined();
expect(gridObj.getContent().querySelector('.e-frozencontent')).not.toBeNull();
done();
};
gridObj.dataBound = dataBound;
gridObj.refreshColumns();
});
it('Ensure the movable content colgroup count while dynamically enable isFrozen in the Grid column', (done: Function) => {
(gridObj.columns[2] as Column).isFrozen = true;
let dataBound = (args: Object) => {
let mTblColgr: Element = gridObj.contentModule.getMovableContent().querySelector('colgroup');
let mHdrColgr: Element = gridObj.getHeaderContent().querySelector('.e-movableheader').querySelector('colgroup');
expect(mTblColgr.children.length).toBe(mHdrColgr.children.length);
done();
};
gridObj.dataBound = dataBound;
gridObj.refreshColumns();
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('Ensure deleteRow and deleteRecord with batch editing', () => {
let gridObj: Grid;
let dBound: () => void;
let selectedRowIndex: number;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
height: 400,
frozenColumns: 2,
frozenRows: 2,
editSettings: { allowAdding: true, allowEditing: true, allowDeleting: true, mode: 'Batch', showConfirmDialog: false },
columns: [
{ headerText: 'OrderID', field: 'OrderID', isPrimaryKey: true },
{ headerText: 'CustomerID', field: 'CustomerID', isFrozen: true },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('Before delete', () => {
gridObj.selectRow(4);
});
it('Ensure deleteRow method', (done: Function) => {
selectedRowIndex = parseInt(gridObj.getSelectedRows()[0].getAttribute('aria-rowindex'), 10);
let batchDelete = (args: Object) => {
expect(gridObj.getMovableRows()[3].classList.contains('e-hiddenrow')).toBeTruthy();
expect(gridObj.getFrozenDataRows().length).toBe(gridObj.currentViewData.length - 1);
expect(gridObj.getMovableDataRows().length).toBe(gridObj.currentViewData.length - 1);
//selectedRowIndex = parseInt(gridObj.getSelectedRows()[0].getAttribute('aria-rowindex'), 10);
//expect(selectedRowIndex).toBe(3);
gridObj.editModule.batchCancel();
gridObj.batchDelete = null;
done();
};
gridObj.batchDelete = batchDelete;
gridObj.deleteRow(gridObj.getMovableRows()[3] as HTMLTableRowElement);
});
it('Before delete', () => {
gridObj.selectRow(4);
});
it('Ensure deleteRecord method', (done: Function) => {
selectedRowIndex = parseInt(gridObj.getSelectedRows()[0].getAttribute('aria-rowindex'), 10);
let batchDelete = (args: Object) => {
expect(gridObj.getMovableRows()[3].classList.contains('e-hiddenrow')).toBeTruthy();
expect(gridObj.getFrozenDataRows().length).toBe(gridObj.currentViewData.length - 1);
expect(gridObj.getMovableDataRows().length).toBe(gridObj.currentViewData.length - 1);
//selectedRowIndex = parseInt(gridObj.getSelectedRows()[0].getAttribute('aria-rowindex'), 10);
//expect(selectedRowIndex).toBe(3);
gridObj.editModule.batchCancel();
gridObj.batchDelete = null;
done();
};
gridObj.batchDelete = batchDelete;
gridObj.deleteRecord('OrderID', gridObj.currentViewData[3]);
});
it('Ensure getFrozenRowByIndex', () => {
let frozenRow: Element = gridObj.getFrozenRowByIndex(2);
let rowindex: number = parseInt(frozenRow.getAttribute('aria-rowindex'), 10);
expect(rowindex).toBe(2);
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('Ensure movable header scrollLeft after the refrechColumns', () => {
let gridObj: Grid;
let dBound: () => void;
let selectedRowIndex: number;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
height: 400,
width: 200,
columns: [
{ headerText: 'OrderID', field: 'OrderID', isPrimaryKey: true, isFrozen: true, width: 120 },
{ headerText: 'CustomerID', field: 'CustomerID', width: 120 },
{ headerText: 'EmployeeID', field: 'EmployeeID', width: 120 },
{ headerText: 'ShipCountry', field: 'ShipCountry', width: 120 },
{ headerText: 'ShipCity', field: 'ShipCity', width: 120 },
]
}, done);
});
it('set isFrozen', function (done) {
(gridObj.columns[1] as Column).isFrozen = true;
var dataB = function (args: any) {
gridObj.contentModule.getMovableContent().scrollLeft = 300;
done();
};
gridObj.dataBound = dataB;
gridObj.refreshColumns();
});
it('Ensure scrollLeft', function (done) {
(gridObj.columns[2] as any).isFrozen = true;
var dataB = function (args: any) {
var hdrScrollLeft = gridObj.headerModule.getMovableHeader().scrollLeft;
var cntScrollLeft = gridObj.contentModule.getMovableContent().scrollLeft;
expect(hdrScrollLeft).toBe(cntScrollLeft);
done();
};
gridObj.dataBound = dataB;
gridObj.refreshColumns();
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe(' EJ2-36046=> movable header misalignment with textwrap', () => {
let gridObj: Grid;
let dBound: () => void;
let selectedRowIndex: number;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: employeeData,
allowTextWrap: true,
frozenColumns: 2,
gridLines: "Both",
columns: [
{
field: "FirstName", headerText: 'First Name', textAlign: 'Center',
width: 150
},
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
{ field: 'Title', headerText: 'Title', width: 70 },
{
field: 'HireDate', headerText: 'Hire Date', textAlign: 'Right',
width: 135, format: { skeleton: 'yMd', type: 'date' }
},
{ field: 'ReportsTo', headerText: 'Reports To', width: 120, textAlign: 'Right' }
],
width: 'auto',
height: 359
}, done);
});
it('Ensure header padding', function (done) {
expect((gridObj.getHeaderContent() as any).style.paddingRight).not.toBe("");
done();
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('EJ2-39341 - Row height is not set properly in the grid when having frozen column', () => {
let gridObj: Grid;
let data1: Object[] = [
{
OrderID: 10248, CustomerID: 'VINET', EmployeeID: 5, OrderDate: new Date(8364186e5),
ShipName: 'Vins et alcools Chevalier', Freight: 1.2, Verified: !0
},
{
OrderID: 10249, CustomerID: '', EmployeeID: 6, OrderDate: new Date(836505e6),
ShipName: 'Toms Spezialitäten', Freight: 2.4, Verified: !1
},
{
OrderID: 10250, CustomerID: '', EmployeeID: 2, OrderDate: new Date(8367642e5),
ShipName: 'Hanari Carnes', Freight: null, Verified: !0
},
{
OrderID: 10251, CustomerID: 'HANAR', EmployeeID: 7, OrderDate: new Date(8367642e5),
ShipName: 'Hanari Carnes', Freight: '', Verified: !0
}
];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data1,
frozenColumns: 2,
frozenRows: 2,
editSettings: { allowAdding: true, allowEditing: true, allowDeleting: true, mode: 'Batch' },
rowHeight: 20,
columns: [
{ field: 'CustomerID', headerText: 'Customer ID', width: 130, minWidth: 10 },
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right', minWidth: 10 },
{ field: 'Freight', width: 125, minWidth: 10 },
{ field: 'ShipName', headerText: 'Ship Name', width: 300, minWidth: 10 },
]
}, done);
});
it('Ensure Rows Height', () => {
let fHead: HTMLElement = gridObj.element.querySelector('.e-frozenheader').querySelector('table').rows[2];
let mHead: HTMLElement = gridObj.element.querySelector('.e-movableheader').querySelector('table').rows[2];
let fContent: HTMLElement = gridObj.element.querySelector('.e-frozencontent').querySelector('table').rows[0];
let mContent: HTMLElement = gridObj.element.querySelector('.e-movablecontent').querySelector('table').rows[0];
expect(fHead.offsetHeight).toBe(gridObj.rowHeight);
expect(mHead.offsetHeight).toBe(gridObj.rowHeight);
expect(fContent.offsetHeight).toBe(gridObj.rowHeight);
expect(mContent.offsetHeight).toBe(gridObj.rowHeight);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-59576 - Grid is not rendering properly with row height and frozen columns properties', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
rowHeight: 30,
allowResizing: true,
height: 300,
frozenColumns: 1,
columns: [
{ field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120, minWidth: 10, },
{ headerText: 'Order Details',
columns: [
{ field: 'OrderDate', headerText: 'Order Date', textAlign: 'Right', width: 135, format: 'yMd', minWidth: 10, },
{ field: 'Freight', headerText: 'Freight($)', textAlign: 'Right', width: 120, format: 'C2', minWidth: 10, },
],
},
{ headerText: 'Ship Details',
columns: [
{ field: 'OrderDate', headerText: 'Shipped Date', textAlign: 'Right', width: 145, format: 'yMd', minWidth: 10, },
{ field: 'ShipCountry', headerText: 'Ship Country', width: 140, minWidth: 10, },
],
},
],
}, done);
});
it('Ensure Rows Height', () => {
let fHead: HTMLElement = gridObj.element.querySelector('.e-frozenheader').querySelector('table').rows[0];
let mHead: HTMLElement = gridObj.element.querySelector('.e-movableheader').querySelector('table').rows[0];
let fContent: HTMLElement = gridObj.element.querySelector('.e-frozencontent').querySelector('table').rows[0];
let mContent: HTMLElement = gridObj.element.querySelector('.e-movablecontent').querySelector('table').rows[0];
expect(fHead.offsetHeight).toBe(gridObj.rowHeight * 2);
expect(mHead.offsetHeight).toBe(gridObj.rowHeight);
expect(fContent.offsetHeight).toBe(gridObj.rowHeight);
expect(mContent.offsetHeight).toBe(gridObj.rowHeight);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-45062 => Alignment issue when we have visible false column with empty data set', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: [],
frozenColumns: 2,
columns: [
{
field: "FirstName", headerText: 'First Name', textAlign: 'Center',
width: 150, visible: false
},
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
{ field: 'Title', headerText: 'Title', width: 70 },
{
field: 'HireDate', headerText: 'Hire Date', textAlign: 'Right',
width: 135, format: { skeleton: 'yMd', type: 'date' }
},
{ field: 'ReportsTo', headerText: 'Reports To', width: 120, textAlign: 'Right' }
],
height: 359
}, done);
});
it('Ensure empty row cell colSpan', () => {
expect(gridObj.getFrozenLeftContentTbody().querySelector('td').colSpan).toBe(1);
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('EJ2-45062 => column level freeze left empty row missaligment issue', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: [],
columns: [
{
field: "FirstName", headerText: 'First Name', textAlign: 'Center',
width: 150, visible: false, freeze: 'Left'
},
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
{ field: 'Title', headerText: 'Title', width: 70, freeze: 'Right' },
{
field: 'HireDate', headerText: 'Hire Date', textAlign: 'Right',
width: 135, format: { skeleton: 'yMd', type: 'date' }
},
{ field: 'ReportsTo', headerText: 'Reports To', width: 120, textAlign: 'Right', freeze: 'Left' }
],
height: 359
}, done);
});
it('Ensure empty row cell colSpan', () => {
expect(gridObj.getFrozenLeftContentTbody().querySelector('td').colSpan).toBe(1);
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('EJ2-45062 => column level freeze right empty row missaligment issue', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: [],
columns: [
{
field: "FirstName", headerText: 'First Name', textAlign: 'Center',
width: 150, visible: false, freeze: 'Right'
},
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
{ field: 'Title', headerText: 'Title', width: 70, freeze: 'Right' },
{
field: 'HireDate', headerText: 'Hire Date', textAlign: 'Right',
width: 135, format: { skeleton: 'yMd', type: 'date' }
},
{ field: 'ReportsTo', headerText: 'Reports To', width: 120, textAlign: 'Right' }
],
height: 359
}, done);
});
it('Ensure empty row cell colSpan', () => {
expect(gridObj.getFrozenRightContentTbody().querySelector('td').colSpan).toBe(1);
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
});
});
describe('EJ2-45329 => Horizontal scroll bar is not displayed while using Frozen columns', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: employeeData,
frozenColumns: 2,
height: '100%',
columns: [
{
field: "FirstName", headerText: 'First Name', textAlign: 'Center',
width: 150, visible: false
},
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 },
{ field: 'Title', headerText: 'Title', width: 70 },
{
field: 'HireDate', headerText: 'Hire Date', textAlign: 'Right',
width: 135, format: { skeleton: 'yMd', type: 'date' }
},
{ field: 'ReportsTo', headerText: 'Reports To', width: 120, textAlign: 'Right' }
],
}, done);
});
it('Ensure e-content element height', () => {
expect((gridObj.getContent().firstElementChild as HTMLElement).style.height).toBe('calc(100% - ' + getScrollBarWidth() + 'px)');
});
afterAll(() => {
gridObj['freezeModule'].destroy();
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-48927 - SetCellValue does not work when column.isFrozen Property is set to true', function () {
let gridObj: Grid;
let localData: Object[] = [{
OrderID: 10248, CustomerID: 'VINET', EmployeeID: 5, OrderDate: new Date(8364186e5),
ShipName: 'Vins et alcools Chevalier', ShipCity: 'Reims', ShipAddress: '59 rue de l Abbaye',
ShipRegion: 'CJ', ShipPostalCode: '51100', ShipCountry: 'France', Freight: 32.38, Verified: !0
},
{
OrderID: 10249, CustomerID: 'TOMSP', EmployeeID: 6, OrderDate: new Date(836505e6),
ShipName: 'Toms Spezialitäten', ShipCity: 'Münster', ShipAddress: 'Luisenstr. 48',
ShipRegion: 'CJ', ShipPostalCode: '44087', ShipCountry: 'Germany', Freight: 11.61, Verified: !1
},
{
OrderID: 10250, CustomerID: 'HANAR', EmployeeID: 4, OrderDate: new Date(8367642e5),
ShipName: 'Hanari Carnes', ShipCity: 'Rio de Janeiro', ShipAddress: 'Rua do Paço, 67',
ShipRegion: 'RJ', ShipPostalCode: '05454-876', ShipCountry: 'Brazil', Freight: 65.83, Verified: !0
}];
beforeAll(function (done) {
gridObj = createGrid({
dataSource: localData,
columns: [
{ headerText: 'OrderID', field: 'OrderID', type: 'number', isPrimaryKey: true, isFrozen : true },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'Freight', field: 'Freight', format: "C2" },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
]
}, done);
});
it('update particular cell', () => {
gridObj.setCellValue(10249, 'CustomerID', 'new value');
let selRow: any = gridObj.contentModule.getRows()[1];
expect((<any>selRow).data.CustomerID).toEqual('new value');
gridObj.setCellValue(10249, 'Freight', 1);
expect((<any>selRow).data.Freight).toEqual(1);
gridObj.setCellValue(10249, 'ShipCountry', 'new country');
expect((<any>selRow).data.ShipCountry).toEqual('new country');
});
afterAll(function () {
destroy(gridObj);
});
});
}); | the_stack |
import { browser, by } from 'protractor';
import { AddFile } from '../component/add-file';
import { Editor } from '../component/editor';
import { EditorFile } from '../component/editor-file';
import { ErrorAlert } from '../component/error-alert';
import { Import } from '../component/import';
import { OperationsHelper } from '../utils/operations-helper';
import { Replace } from '../component/replace';
import { waitForFileToExist, retrieveZipContentList } from '../utils/fileUtils';
import { Constants } from '../constants';
import * as fs from 'fs';
import * as JSZip from 'jszip';
import * as chai from 'chai';
let expect = chai.expect;
describe('Editor Define', (() => {
const addFileActionLabel = Constants.addFileActionLabel;
const exportActionLabel = Constants.exportActionLabel;
const deployButtonLabel = Constants.deployButtonLabel;
let baseTiles: Array<string> = null;
let npmTiles: Array<string> = null;
let sampleOptions;
// Navigate to Editor base page and move past welcome splash
beforeAll(() => {
// Important angular configuration and intial step passage to reach editor
browser.waitForAngularEnabled(false);
OperationsHelper.navigatePastWelcome();
});
afterAll(() => {
browser.waitForAngularEnabled(true);
browser.executeScript('window.sessionStorage.clear();');
browser.executeScript('window.localStorage.clear();');
});
describe('On initialise', (() => {
it('should initialise the side navigation with basic sample network', (() => {
// Check Loaded Files (Basic Sample Files)
let expectedFiles = ['About\nREADME.md', 'Model File\nmodels/sample.cto', 'Script File\nlib/sample.js', 'Access Control\npermissions.acl'];
Editor.retrieveNavigatorFileNames()
.then((filelist: any) => {
expect(filelist).to.be.an('array').lengthOf(4);
filelist.forEach((file) => {
expect(file).to.be.oneOf(expectedFiles);
});
});
// Check Actions (AddFile/Export) Present and clickable
Editor.retrieveNavigatorActions()
.then((actionlist: any) => {
expect(actionlist).to.be.an('array').lengthOf(2);
expect(actionlist[0]).to.deep.equal({text: addFileActionLabel, enabled: true});
expect(actionlist[1]).to.deep.equal({text: exportActionLabel, enabled: true});
});
// Check Buttons (Deploy Changes)
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
}));
describe('Export BND button', (() => {
it('should export BNA named as the package name', (() => {
Editor.waitForProjectFilesToLoad();
Editor.retrieveDeployedPackageName()
.then((packageName) => {
let filename = './e2e/downloads/' + packageName + '.bna';
if (fs.existsSync(filename)) {
// Make sure the browser doesn't have to rename the download.
fs.unlinkSync(filename);
}
return filename;
})
.then((filename) => {
Editor.clickExportBND();
return waitForFileToExist(filename)
.then(() => { return retrieveZipContentList(filename); });
})
.then((contents) => {
// -should have known contents
let expectedContents = [ 'package.json',
'README.md',
'permissions.acl',
'models/',
'models/sample.cto',
'lib/',
'lib/sample.js' ];
expect(contents).to.be.an('array').lengthOf(7);
expect(contents).to.deep.equal(expectedContents);
});
}));
}));
describe('Import BND button', (() => {
// Press the 'Import' button
beforeEach(() => {
Editor.clickImportBND();
Import.waitToLoadBaseOptions();
Import.waitToLoadNpmOptions();
});
it('should enable to close/cancel import slide out', (() => {
Import.cancelImport();
// -expected files in navigator (unchanged)
let expectedFiles = ['About\nREADME.md', 'Model File\nmodels/sample.cto', 'Script File\nlib/sample.js', 'Access Control\npermissions.acl'];
Editor.retrieveNavigatorFileNames()
.then((filelist: any) => {
expect(filelist).to.be.an('array').lengthOf(4);
filelist.forEach((file) => {
expect(file).to.be.oneOf(expectedFiles);
});
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable to cancel import import at replacement warning', (() => {
// Select default item
Import.confirmImport();
// Cancel on replace warning
Replace.cancelReplace();
// -expected files in navigator (unchanged)
let expectedFiles = ['About\nREADME.md', 'Model File\nmodels/sample.cto', 'Script File\nlib/sample.js', 'Access Control\npermissions.acl'];
Editor.retrieveNavigatorFileNames()
.then((filelist: any) => {
expect(filelist).to.be.an('array').lengthOf(4);
filelist.forEach((file) => {
expect(file).to.be.oneOf(expectedFiles);
});
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable empty BNA import via tile selection', (() => {
// Select Empty BNA
Import.selectBaseImportOption('empty-business-network');
// Replace confirm should show, confirm it
Replace.confirmReplace();
// Check that the import has succeeded
// -import modal disappears
Import.waitToDisappear();
// -success message
OperationsHelper.processExpectedSuccess();
// -expected files in navigator (Just a readme)
Editor.retrieveNavigatorFileNames()
.then((filelist: any) => {
expect(filelist).to.be.an('array').lengthOf(1);
expect(filelist).to.deep.equal(['About\nREADME.md']);
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable populated BNA import via file selection', (() => {
// Select Basic Sample Network BNA
Import.selectBaseImportOption('basic-sample-network');
// Replace confirm should show, confirm it
Replace.confirmReplace();
// Check that the import has succeeded
// -import modal disappears
Import.waitToDisappear();
// -success message
OperationsHelper.processExpectedSuccess();
// -expected files in navigator
Editor.retrieveNavigatorFileNames()
.then((filelist: any) => {
let expectedFiles = ['About\nREADME.md', 'Model File\nmodels/sample.cto', 'Script File\nlib/sample.js', 'Access Control\npermissions.acl'];
expect(filelist).to.be.an('array').lengthOf(4);
filelist.forEach((file) => {
expect(file).to.be.oneOf(expectedFiles);
});
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable import of npm hosted animaltracking-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('animaltracking-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted bond-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('bond-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted carauction-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('carauction-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted digitalproperty-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('digitalproperty-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted marbles-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('marbles-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted perishable-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('perishable-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted pii-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('pii-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted trade-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('trade-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
it('should enable import of npm hosted vehicle-lifecycle-network', (() => {
// Select & Confirm
Import.selectNpmImportOption('vehicle-lifecycle-network');
Replace.confirmReplace();
// Expect success
Import.waitToDisappear();
OperationsHelper.processExpectedSuccess();
}));
}));
describe('Add File button', (() => {
// Press the 'AddFile' button
beforeEach(() => {
Editor.clickAddFile()
.then(() => {
AddFile.waitToAppear();
});
});
afterEach(() => {
// Reset network to basic sample network
OperationsHelper.importBusinessNetworkArchiveFromTile('basic-sample-network', true);
});
it('should bring up an AddFile modal that can be closed by cancel button', (() => {
AddFile.clickCancelAdd();
AddFile.waitToDisappear();
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should bring up an AddFile modal that can be closed by X button', (() => {
AddFile.clickExitAdd();
AddFile.waitToDisappear();
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable the cancelling of script file addition part way through without completing the file addition', (() => {
AddFile.selectAddScriptViaRadioOption();
// Add option becomes enabled, but we want to cancel instead
AddFile.clickCancelAdd();
// Check we do not have a template script file added
Editor.retrieveNavigatorFileNames()
.then( (list: any) => {
expect(list).to.not.include('Script File\nlib/script.js');
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable the cancelling of model file addition part way through without completing the file addition', (() => {
AddFile.selectAddModelViaRadioOption();
// Add option becomes enabled, but we want to cancel instead
AddFile.clickCancelAdd();
// Check we do not have a template model file added
Editor.retrieveNavigatorFileNames()
.then( (list: any) => {
expect(list).to.not.include('Model File\nlmodels/org.acme.model.cto');
});
// -update not enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
}));
it('should enable the addition of a script file via radio button selection', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectAddScriptViaRadioOption();
return AddFile.clickConfirmAdd()
.then(() => {
return names;
});
})
.then((startFiles) => {
// Check extracted against new template file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
expect(filenames).to.include('Script File\nlib/script.js');
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Script File\nlib/script.js');
});
});
}));
it('should enable the addition of a script file via file input event', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectFromFile('./e2e/data/files/importScript.js');
// Add option becomes enabled
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// Check extracted against new template file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Script File\nlib/importScript.js');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Script File\nlib/importScript.js');
});
});
}));
it('should enable the addition of a model file via radio button selection', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
// Select radio option
AddFile.selectAddModelViaRadioOption();
// Add option becomes enabled
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Model File\nmodels/org.acme.model.cto');
});
// Check extracted against new template file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Model File\nmodels/org.acme.model.cto');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of a model file via file input event', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectFromFile('./e2e/data/files/importModel.cto');
// Add option becomes enabled
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Model File\nmodels/importModel.cto');
});
// Check extracted against new file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Model File\nmodels/importModel.cto');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of an ACL file via file input event', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectFromFile('./e2e/data/files/importACL.acl');
AddFile.clickConfirmAdd();
Replace.confirmReplace();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Access Control\npermissions.acl');
});
// Check code mirror for new contents (we only have one permissions file)
EditorFile.retrieveEditorCodeMirrorText()
.then((text) => {
expect(text).to.contain('description: "Newly imported ACL file"');
});
// Check file list unchanged
Editor.retrieveNavigatorFileNames()
.then((filenames) => {
// No new file (names)
expect(filenames).to.be.an('array').lengthOf(startFiles.length);
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of an ACL file via radio button selection', (() => {
AddFile.clickCancelAdd();
OperationsHelper.importBusinessNetworkArchiveFromTile('empty-business-network', true);
Editor.clickAddFile();
AddFile.waitToAppear();
Editor.retrieveNavigatorFileNames()
.then((names) => {
// Select radio option
AddFile.selectAddAclViaRadioOption();
// Add option becomes enabled
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Access Control\npermissions.acl');
});
// Check extracted against new template file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Access Control\npermissions.acl');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of a Readme file via file input event', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectFromFile('./e2e/data/files/importReadMe.md');
AddFile.clickConfirmAdd();
// Replace confirm modal should show
Replace.confirmReplace();
return names;
})
.then((startFiles) => {
// Check for new contents (we only have one readme file)
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('About\nREADME.md');
});
EditorFile.retrieveEditorText()
.then((text) => {
expect(text).to.contain('This is the NEW readme.');
});
// Check file list unchanged
Editor.retrieveNavigatorFileNames()
.then((filenames) => {
// No new file (names)
expect(filenames).to.be.an('array').lengthOf(startFiles.length);
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of a Query file via radio button selection', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
// Select radio option
AddFile.selectAddQueryViaRadioOption();
// Add option becomes enabled
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Query File\nqueries.qry');
});
// Check extracted against new template file that we should have in the list
Editor.retrieveNavigatorFileNames()
.then((filenames: any) => {
// We should have added one file
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Query File\nqueries.qry');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should enable the addition of a Query file via file input event', (() => {
Editor.retrieveNavigatorFileNames()
.then((names) => {
AddFile.selectFromFile('./e2e/data/files/importQuery.qry');
AddFile.clickConfirmAdd();
return names;
})
.then((startFiles) => {
// -active file
Editor.retrieveNavigatorActiveFiles()
.then((list: any) => {
expect(list).to.be.an('array').lengthOf(1);
expect(list).to.include('Query File\nqueries.qry');
});
EditorFile.retrieveEditorCodeMirrorText()
.then((text) => {
expect(text).to.contain('query Q1');
});
// Check file list unchanged
Editor.retrieveNavigatorFileNames()
.then((filenames) => {
// One new file (names)
expect(filenames).to.be.an('array').lengthOf(startFiles.length + 1);
expect(filenames).to.include('Query File\nqueries.qry');
// Previous files should still exist
startFiles.forEach((file) => {
expect(file).to.be.oneOf(filenames);
});
});
// -update enabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: true});
});
// update new item
Editor.clickDeployBND();
// -success message
OperationsHelper.processExpectedSuccess();
// -update disabled
Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: deployButtonLabel, enabled: false});
});
});
}));
it('should prevent the addition of a query file and/or acl file if one exists already', (() => {
// Add a query file
AddFile.selectFromFile('./e2e/data/files/importQuery.qry');
AddFile.clickConfirmAdd();
// Click add file
Editor.clickAddFile();
AddFile.waitToAppear();
// Inspect radio button status
AddFile.retrieveAddFileRadioButtons()
.then((radioList: any) => {
expect(radioList).to.be.an('array').lengthOf(4);
expect(radioList).to.contain({name: 'file-type-cto', enabled: true});
expect(radioList).to.contain({name: 'file-type-js', enabled: true});
expect(radioList).to.contain({name: 'file-type-qry', enabled: false});
expect(radioList).to.contain({name: 'file-type-acl', enabled: false});
});
AddFile.clickCancelAdd();
}));
it('should prevent the addition of a file with an invalid file extension', (() => {
AddFile.selectFromFile('./e2e/data/files/importBanned.wombat');
ErrorAlert.clickCloseError();
ErrorAlert.waitToDisappear();
AddFile.clickCancelAdd();
}));
}));
})); | the_stack |
import _ = require('lodash');
import net = require('net');
import tls = require('tls');
import http = require('http');
import http2 = require('http2');
import * as streams from 'stream';
import httpolyglot = require('@httptoolkit/httpolyglot');
import now = require("performance-now");
import { TlsRequest } from '../types';
import { destroyable, DestroyableServer } from '../util/destroyable-server';
import { getCA, CAOptions } from '../util/tls';
import { delay } from '../util/util';
// Hardcore monkey-patching: force TLSSocket to link servername & remoteAddress to
// sockets as soon as they're available, without waiting for the handshake to fully
// complete, so we can easily access them if the handshake fails.
const originalSocketInit = (<any>tls.TLSSocket.prototype)._init;
(<any>tls.TLSSocket.prototype)._init = function () {
originalSocketInit.apply(this, arguments);
const tlsSocket: tls.TLSSocket = this;
const { _handle } = tlsSocket;
if (!_handle) return;
const loadSNI = _handle.oncertcb;
_handle.oncertcb = function (info: any) {
tlsSocket.servername = info.servername;
tlsSocket.initialRemoteAddress = tlsSocket.remoteAddress || // Normal case
tlsSocket._parent?.remoteAddress || // For early failing sockets
tlsSocket._handle?._parentWrap?.stream?.remoteAddress; // For HTTP/2 CONNECT
tlsSocket.initialRemotePort = tlsSocket.remotePort ||
tlsSocket._parent?.remotePort ||
tlsSocket._handle?._parentWrap?.stream?.remotePort;
return loadSNI?.apply(this, arguments as any);
};
};
export type ComboServerOptions = {
debug: boolean,
https: CAOptions | undefined,
http2: true | false | 'fallback'
};
// Takes an established TLS socket, calls the error listener if it's silently closed
function ifTlsDropped(socket: tls.TLSSocket, errorCallback: () => void) {
new Promise((resolve, reject) => {
// If you send data, you trust the TLS connection
socket.once('data', resolve);
// If you silently close it very quicky, you probably don't trust us
socket.once('error', reject);
socket.once('close', reject);
socket.once('end', reject);
// Some clients open later-unused TLS connections for connection pools, preconnect, etc.
// Even if these are shut later on, that doesn't mean they're are rejected connections.
// To differentiate the two cases, we consider connections OK after waiting 10x longer
// than the initial TLS handshake for an unhappy disconnection.
const timing = socket.__timingInfo;
const tlsSetupDuration = timing
? timing.tlsConnectedTimestamp! - (timing.tunnelSetupTimestamp! || timing.initialSocketTimestamp)
: 0;
const maxTlsRejectionTime = !Object.is(tlsSetupDuration, NaN)
? Math.max(tlsSetupDuration * 10, 100) // Ensure a sensible minimum
: 2000;
delay(maxTlsRejectionTime).then(resolve);
})
.then(() => {
// Mark the socket as having completed TLS setup - this ensures that future
// errors fire as client errors, not TLS setup errors.
socket.tlsSetupCompleted = true;
})
.catch(() => {
// If TLS setup was confirmed in any way, we know we don't have a TLS error.
if (socket.tlsSetupCompleted) return;
// To get here, the socket must have connected & done the TLS handshake, but then
// closed/ended without ever sending any data. We can fairly confidently assume
// in that case that it's rejected our certificate.
errorCallback();
});
}
function getCauseFromError(error: Error & { code?: string }) {
const cause = (
/alert certificate/.test(error.message) ||
/alert bad certificate/.test(error.message) ||
error.code === 'ERR_SSL_SSLV3_ALERT_BAD_CERTIFICATE' ||
/alert unknown ca/.test(error.message)
)
// The client explicitly told us it doesn't like the certificate
? 'cert-rejected'
: /no shared cipher/.test(error.message)
// The client refused to negotiate a cipher. Probably means it didn't like the
// cert so refused to continue, but it could genuinely not have a shared cipher.
? 'no-shared-cipher'
: (/ECONNRESET/.test(error.message) || error.code === 'ECONNRESET')
// The client sent no TLS alert, it just hard RST'd the connection
? 'reset'
: 'unknown'; // Something \else.
if (cause === 'unknown') console.log('Unknown TLS error:', error);
return cause;
}
function buildTimingInfo(): Required<net.Socket>['__timingInfo'] {
return { initialSocket: Date.now(), initialSocketTimestamp: now() };
}
function buildTlsError(
socket: tls.TLSSocket,
cause: TlsRequest['failureCause']
): TlsRequest {
const timingInfo = socket.__timingInfo ||
socket._parent?.__timingInfo ||
buildTimingInfo();
return {
failureCause: cause,
hostname: socket.servername,
// These only work because of oncertcb monkeypatch above
remoteIpAddress: socket.remoteAddress || // Normal case
socket._parent?.remoteAddress || // Pre-certCB error, e.g. timeout
socket.initialRemoteAddress!, // Recorded by certCB monkeypatch
remotePort: socket.remotePort ||
socket._parent?.remotePort ||
socket.initialRemotePort!,
tags: [],
timingEvents: {
startTime: timingInfo.initialSocket,
connectTimestamp: timingInfo.initialSocketTimestamp,
tunnelTimestamp: timingInfo.tunnelSetupTimestamp,
handshakeTimestamp: timingInfo.tlsConnectedTimestamp,
failureTimestamp: now()
}
};
}
// The low-level server that handles all the sockets & TLS. The server will correctly call the
// given handler for both HTTP & HTTPS direct connections, or connections when used as an
// either HTTP or HTTPS proxy, all on the same port.
export async function createComboServer(
options: ComboServerOptions,
requestListener: (req: http.IncomingMessage, res: http.ServerResponse) => void,
tlsClientErrorListener: (socket: tls.TLSSocket, req: TlsRequest) => void
): Promise<DestroyableServer> {
let server: net.Server;
if (!options.https) {
server = httpolyglot.createServer(requestListener);
} else {
const ca = await getCA(options.https!);
const defaultCert = ca.generateCertificate('localhost');
server = httpolyglot.createServer({
key: defaultCert.key,
cert: defaultCert.cert,
ca: [defaultCert.ca],
ALPNProtocols: options.http2 === true
? ['h2', 'http/1.1']
: options.http2 === 'fallback'
? ['http/1.1', 'h2']
// false
: ['http/1.1'],
SNICallback: (domain: string, cb: Function) => {
if (options.debug) console.log(`Generating certificate for ${domain}`);
try {
const generatedCert = ca.generateCertificate(domain);
cb(null, tls.createSecureContext({
key: generatedCert.key,
cert: generatedCert.cert,
ca: generatedCert.ca
}));
} catch (e) {
console.error('Cert generation error', e);
cb(e);
}
}
}, requestListener);
}
server.on('connection', (socket: net.Socket | http2.ServerHttp2Stream) => {
socket.__timingInfo = socket.__timingInfo || buildTimingInfo();
// All sockets are initially marked as using unencrypted upstream connections.
// If TLS is used, this is upgraded to 'true' by secureConnection below.
socket.lastHopEncrypted = false;
// For actual sockets, set NODELAY to avoid any buffering whilst streaming. This is
// off by default in Node HTTP, but likely to be enabled soon & is default in curl.
if ('setNoDelay' in socket) socket.setNoDelay(true);
});
server.on('secureConnection', (socket: tls.TLSSocket) => {
const parentSocket = getParentSocket(socket);
if (parentSocket) {
// Sometimes wrapper TLS sockets created by the HTTP/2 server don't include the
// underlying socket details, so it's better to make sure we copy them up.
copyAddressDetails(parentSocket, socket);
copyTimingDetails(parentSocket, socket);
} else if (!socket.__timingInfo) {
socket.__timingInfo = buildTimingInfo();
}
socket.__timingInfo!.tlsConnectedTimestamp = now();
socket.lastHopEncrypted = true;
ifTlsDropped(socket, () => {
tlsClientErrorListener(socket, buildTlsError(socket, 'closed'));
});
});
// Mark HTTP/2 sockets as set up once we receive a first settings frame. This always
// happens immediately after the connection preface, as long as the connection is OK.
server!.on('session', (session) => {
session.once('remoteSettings', () => {
session.socket.tlsSetupCompleted = true;
});
});
server.on('tlsClientError', (error: Error, socket: tls.TLSSocket) => {
tlsClientErrorListener(socket, buildTlsError(socket, getCauseFromError(error)));
});
// If the server receives a HTTP/HTTPS CONNECT request, Pretend to tunnel, then just re-handle:
server.addListener('connect', function (
req: http.IncomingMessage | http2.Http2ServerRequest,
resOrSocket: net.Socket | http2.Http2ServerResponse
) {
if (resOrSocket instanceof net.Socket) {
handleH1Connect(req as http.IncomingMessage, resOrSocket);
} else {
handleH2Connect(req as http2.Http2ServerRequest, resOrSocket);
}
});
function handleH1Connect(req: http.IncomingMessage, socket: net.Socket) {
// Clients may disconnect at this point (for all sorts of reasons), but here
// nothing else is listening, so we need to catch errors on the socket:
socket.once('error', (e) => console.log('Error on client socket', e));
const connectUrl = req.url || req.headers['host'];
if (!connectUrl) {
// If we can't work out where to go, send an error.
socket.write('HTTP/' + req.httpVersion + ' 400 Bad Request\r\n\r\n', 'utf-8');
return;
}
if (options.debug) console.log(`Proxying HTTP/1 CONNECT to ${connectUrl}`);
socket.write('HTTP/' + req.httpVersion + ' 200 OK\r\n\r\n', 'utf-8', () => {
socket.__timingInfo!.tunnelSetupTimestamp = now();
server.emit('connection', socket);
});
}
function handleH2Connect(req: http2.Http2ServerRequest, res: http2.Http2ServerResponse) {
const connectUrl = req.headers[':authority'];
if (!connectUrl) {
// If we can't work out where to go, send an error.
res.writeHead(400, {});
res.end();
return;
}
if (options.debug) console.log(`Proxying HTTP/2 CONNECT to ${connectUrl}`);
// Send a 200 OK response, and start the tunnel:
res.writeHead(200, {});
copyAddressDetails(res.socket, res.stream);
copyTimingDetails(res.socket, res.stream);
// When layering HTTP/2 on JS streams, we have to make sure the JS stream won't autoclose
// when the other side does, because the upper HTTP/2 layers want to handle shutdown, so
// they end up trying to write a GOAWAY at the same time as the lower stream shuts down,
// and we get assertion errors in Node v16.7+.
if (res.socket.constructor.name.includes('JSStreamSocket')) {
res.socket.allowHalfOpen = true;
}
server.emit('connection', res.stream);
}
return destroyable(server);
}
function getParentSocket(socket: net.Socket) {
return socket._parent || // TLS wrapper
socket.stream || // SocketWrapper
(socket as any)._handle?._parentWrap?.stream; // HTTP/2 CONNECT'd TLS wrapper
}
type SocketIsh<MinProps extends keyof net.Socket> =
streams.Duplex & Partial<Pick<net.Socket, MinProps>>;
// Update the target socket(-ish) with the address details from the source socket,
// iff the target has no details of its own.
function copyAddressDetails(
source: SocketIsh<'localAddress' | 'localPort' | 'remoteAddress' | 'remotePort'>,
target: SocketIsh<'localAddress' | 'localPort' | 'remoteAddress' | 'remotePort'>
) {
const fields = ['localAddress', 'localPort', 'remoteAddress', 'remotePort'] as const;
Object.defineProperties(target, _.zipObject(fields,
_.range(fields.length).map(() => ({ writable: true }))
));
fields.forEach((fieldName) => {
if (target[fieldName] === undefined) {
(target as any)[fieldName] = source[fieldName];
}
});
}
function copyTimingDetails<T extends SocketIsh<'__timingInfo'>>(
source: SocketIsh<'__timingInfo'>,
target: T
): asserts target is T & { __timingInfo: Required<net.Socket>['__timingInfo'] } {
if (!target.__timingInfo) {
// Clone timing info, don't copy it - child sockets get their own independent timing stats
target.__timingInfo = Object.assign({}, source.__timingInfo);
}
} | the_stack |
import { PathExt, nbformat } from "@jupyterlab/coreutils";
import {
ILayoutRestorer,
JupyterFrontEndPlugin,
JupyterFrontEnd
} from '@jupyterlab/application';
import {
//ICommandPalette,
WidgetTracker,
Clipboard,
Dialog,
showDialog,
showErrorMessage
} from '@jupyterlab/apputils';
import {
ABCWidgetFactory,
DocumentRegistry,
Context,
IDocumentWidget,
DocumentWidget
} from "@jupyterlab/docregistry";
import { Widget } from "@phosphor/widgets";
import {
IMainMenu
} from '@jupyterlab/mainmenu';
import { IDocumentManager, DocumentManager } from "@jupyterlab/docmanager";
import { IRenderMimeRegistry } from "@jupyterlab/rendermime";
import {
INotebookTracker,
NotebookPanel,
NotebookTracker,
NotebookActions
} from "@jupyterlab/notebook";
import { CodeCell } from "@jupyterlab/cells";
import { ReadonlyJSONObject, JSONExt } from "@phosphor/coreutils";
import { VoyagerTutorialWidget } from "./tutorial";
import { VoyagerPanel, VoyagerPanel_DF, isValidFileName } from "./voyagerpanel";
import "../style/index.css";
import "datavoyager/build/style.css";
/**
* The mimetype used for Jupyter cell data.
*/
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
/**
* The class icon for a datavoyager widget.
*/
const VOYAGER_ICON = "jp-VoyagerIcon";
/**
* The class name added to a datavoyager widget.
*/
const Voyager_CLASS = 'jp-Voyager';
/**
* The source file for the Voyager tutorial.
*/
const SOURCE = require("../tutorial/tutorial.md");
/**
* A counter for VoyagerPanel_DF widgets, to give them distinct IDs.
*/
var temp_widget_counter = 0;
/**
* Definitions for all the commands to be used.
*/
export namespace CommandIDs {
export const JL_Graph_Voyager = "graph_voyager:open";
export const JL_Table_Voyager = "table_voyager:open";
export const JL_Voyager_Save = "voyager_graph:save";
export const JL_Voyager_Save1 = "voyager_graph:save1";
export const JL_Voyager_Export = "voyager_graph:Export";
export const JL_Voyager_Export_To_Notebook =
"voyager_graph:Export_to_notebook";
export const JL_Voyager_Tutorial = "voyager_tutorial:open";
export const JL_Voyager_Undo = "voyager_graph:undo";
export const JL_Voyager_Redo = "voyager_graph:redo";
export const JL_Voyager_HideBar = "voyager_graph:hidebar";
}
/**
* The widget factory class to open a file with the VoyagerPanel.
*/
class VoyagerWidgetFactory extends ABCWidgetFactory<
IDocumentWidget<VoyagerPanel>
> {
docManager: DocumentManager;
app: JupyterFrontEnd;
/**
* Construct a new Voyager widget factory.
*/
constructor(
app: JupyterFrontEnd,
docManager: DocumentManager,
options: DocumentRegistry.IWidgetFactoryOptions
) {
super(options);
this.docManager = docManager;
this.app = app;
}
/**
* Create a new widget given a context.
*/
protected createNewWidget(
context: DocumentRegistry.IContext<DocumentRegistry.IModel>
): IDocumentWidget<VoyagerPanel> {
let context_array = context.path.split(".");
const file_type = context_array[context_array.length-1];
const content = new VoyagerPanel(
{ context, fileType: file_type },
this.app,
this.docManager
);
const widget = new DocumentWidget({ context, content });
return widget;
}
}
/**
* The widget factory class to open a vl.json file with notebook.
*/
class VoyagerNotebookWidgetFactory extends ABCWidgetFactory<
NotebookPanel,
DocumentRegistry.IModel
> {
app: JupyterFrontEnd;
KernalName?: string;
/**
* Construct a new notebook widget factory.
*/
constructor(
app: JupyterFrontEnd,
options: DocumentRegistry.IWidgetFactoryOptions,
kernelName?: string
) {
super(options);
this.app = app;
this.KernalName = kernelName;
}
/**
* Create a new notebook widget with pre-written python codes.
*/
protected createNewWidget(context: DocumentRegistry.Context): any {
let PATH = PathExt.dirname(context.path);
return this.app.commands
.execute("docmanager:new-untitled", {
path: PATH,
type: "notebook"
})
.then(model => {
return this.app.commands
.execute("docmanager:open", {
path: model.path,
factory: "Notebook",
kernel: { name: this.KernalName ? this.KernalName : "Python 3" }
})
.then(widget => {
let md = (widget as NotebookPanel).model.toJSON() as nbformat.INotebookContent;
md.cells = [
{
cell_type: "code",
execution_count: null,
metadata: {},
outputs: [],
source: [
"import altair as alt\n",
"import pandas as pd\n",
"import json\n",
`with open('${PathExt.basename(
context.path
)}') as json_data:\n`,
" data_src = json.load(json_data)\n",
"data = data_src['data']\n",
"alt.Chart.from_dict(data_src)\n"
]
}
];
(widget as NotebookPanel).model.fromJSON(md);
widget.context.save();
NotebookActions.runAll(widget.notebook, widget.context.session);
});
});
}
}
/**
* Define the supported file types.
*/
const fileTypes = ["csv", "json", "tsv"];
const fileTypes_vega = ["vega-lite2", "vega3"];
function activate(
app: JupyterFrontEnd,
restorer: ILayoutRestorer,
tracker_Notebook: NotebookTracker,
docManager: DocumentManager,
mainMenu: IMainMenu,
rendermime: IRenderMimeRegistry
): void {
// Declare a widget variable for tutorial
let T_widget: VoyagerTutorialWidget;
const { commands} = app;
// Get the current cellar widget and activate unless the args specify otherwise.
function getCurrent(args: ReadonlyJSONObject): NotebookPanel | null {
const widget = tracker_Notebook.currentWidget;
const activate = args['activate'] !== false;
if (activate && widget) {
app.shell.activateById(widget.id);
}
return widget;
}
/**
* Create a new local file
* @param cwd: current file path
* @param data: the data to be written in the new file
* @param open: whether to open this new file
*/
function createNew(cwd: string, data: any, open: boolean) {
let input_block = document.createElement("div");
let input_prompt = document.createElement("div");
input_prompt.textContent = '';
let input = document.createElement("input");
input_block.appendChild(input_prompt);
input_block.appendChild(input);
let bd = new Widget({node:input_block});
showDialog({
title: "Export as Vega-Lite File (.vl.json)",
body: bd,
buttons: [Dialog.cancelButton(), Dialog.okButton({ label: "OK"})]
}).then(result=>{
let msg = input.value;
if (result.button.accept) {
if (!isValidFileName(msg)) {
showErrorMessage(
"Name Error",
Error(
`"${result.value}" is not a valid name for a file. ` +
`Names must have nonzero length, ` +
`and cannot include "/", "\\", or ":"`
)
);
} else {
let basePath = cwd;
let newPath = PathExt.join(basePath, msg.indexOf('.vl.json')!==-1?msg:msg+'.vl.json');
return commands.execute('docmanager:new-untitled', {
path: cwd, ext: '.vl.json', type: 'file'
}).then(model => {
return docManager.rename(model.path, newPath).then(model=>{
return commands.execute('docmanager:open', {
path: model.path, factory: "Editor"
}).then(widget=>{
let context = docManager.contextForWidget(widget);
if(context!=undefined){
context.save().then(()=>{
if(context!=undefined){
context.model.fromJSON(data);
context.save().then(()=>{
if (open) {
commands.execute('docmanager:open', {
path: model.path,
factory: `Voyager`
});
}
})
}
})
}})
})
});
}}
})
};
/**
* create and add the command to open a notebook graph in Voyager
*/
commands.addCommand(CommandIDs.JL_Graph_Voyager, {
label: 'Open Graph in Voyager',
caption: 'Open the datasource in Voyager',
execute: args => {
const cur = getCurrent(args);
if(cur){
var filename = cur.id+'_Voyager';
let cell = cur.content.activeCell;
if (cell && cell.model.type === "code") {
let codeCell = cur.content.activeCell as CodeCell;
let outputs = codeCell.model.outputs;
let i = 0;
// Find the first altair image output of this cell,
// If multiple output images in one cell, currently there's no method to locate the selected one,
// so only select the first one by default)
while (i < outputs.length) {
if (!!outputs.get(i).data["application/vnd.vegalite.v2+json"]) {
if (
!!(outputs.get(i).data[
"application/vnd.vegalite.v2+json"
] as any).vconcat
) {
var JSONobject = (outputs.get(i).data[
"application/vnd.vegalite.v2+json"
] as any).vconcat["0"];
} else {
var JSONobject = outputs.get(i).data[
"application/vnd.vegalite.v2+json"
] as any;
}
let context = docManager.contextForWidget(cur) as Context<
DocumentRegistry.IModel
>;
var wdg = new VoyagerPanel_DF(
JSONobject,
filename,
context,
false,
app,
docManager
);
wdg.data_src = JSONobject;
wdg.id = filename+(temp_widget_counter++);
wdg.title.closable = true;
wdg.title.iconClass = VOYAGER_ICON;
const tracker = new WidgetTracker<VoyagerPanel_DF>({ namespace: 'VoyagerPanel_DataFrame' });
tracker.add(wdg);
app.shell.add(wdg, 'main');
app.shell.activateById(wdg.id);
break;
}
i++;
}
}
}
}
});
/**
* create and add the command to open a notebook table in Voyager
*/
commands.addCommand(CommandIDs.JL_Table_Voyager, {
label: 'Open table in Voyager',
caption: 'Open the datasource in Voyager',
execute: args => {
const cur = getCurrent(args);
if (cur) {
var filename = cur.id + "_Voyager";
let cell = cur.content.activeCell;
if (cell && cell.model.type === "code") {
let codeCell = cur.content.activeCell as CodeCell;
let outputs = codeCell.model.outputs;
let i = 0;
/** find the first dataframe output of this cell,
* (if multiple dataframes in one cell, currently there's no method to locate,
* so only select the first one by default)
*/
while (i < outputs.length) {
if (!!outputs.get(i).data["application/vnd.dataresource+json"]) {
var JSONobject = (outputs.get(i).data[
"application/vnd.dataresource+json"
] as any).data;
let context = docManager.contextForWidget(cur) as Context<
DocumentRegistry.IModel
>;
var wdg = new VoyagerPanel_DF(
{ values: JSONobject },
filename,
context,
true,
app,
docManager
);
wdg.data_src = { values: JSONobject };
wdg.id = filename + temp_widget_counter++;
wdg.title.closable = true;
wdg.title.iconClass = VOYAGER_ICON;
const tracker = new WidgetTracker<VoyagerPanel_DF>({ namespace: 'VoyagerPanel_DataFrame' });
tracker.add(wdg);
app.shell.add(wdg, 'main');
app.shell.activateById(wdg.id);
break;
}
i++;
}
}
}
}
});
/**
* create and add the command to save the Voyager content
*/
commands.addCommand(CommandIDs.JL_Voyager_Save, {
label: ' ',
caption: 'Save the chart datasource as vl.json file',
execute: args => {
let widget = app.shell.currentWidget;
if (widget) {
var datavoyager = (widget as VoyagerPanel).voyager_cur;
var dataSrc = (widget as VoyagerPanel).data_src;
let spec = datavoyager.getSpec(false);
let context = docManager.contextForWidget(widget) as Context<DocumentRegistry.IModel>;
context.model.fromJSON({
"data":dataSrc,
"mark": spec.mark,
"encoding": spec.encoding,
"height":spec.height,
"width":spec.width,
"description":spec.description,
"name":spec.name,
"selection":spec.selection,
"title":spec.title,
"transform":spec.transform
});
context.save();
}
},
isEnabled: () =>{
return false;
}
});
/**
* create and add the command to save the Voyager content
*/
commands.addCommand(CommandIDs.JL_Voyager_Save1, {
label: 'Save Voyager Chart',
caption: 'Save the chart datasource as vl.json file',
execute: args => {
let widget = app.shell.currentWidget;
if(widget){
var datavoyager = (widget as VoyagerPanel).voyager_cur;
var dataSrc = (widget as VoyagerPanel).data_src;
let spec = datavoyager.getSpec(false);
let context = docManager.contextForWidget(widget) as Context<DocumentRegistry.IModel>;
context.model.fromJSON({
"data":dataSrc,
"mark": spec.mark,
"encoding": spec.encoding,
"height":spec.height,
"width":spec.width,
"description":spec.description,
"name":spec.name,
"selection":spec.selection,
"title":spec.title,
"transform":spec.transform
});
context.save();
}
},
isEnabled: () =>{
let widget = app.shell.currentWidget;
if (
widget &&
widget.hasClass(Voyager_CLASS) &&
(widget as VoyagerPanel).context.path.indexOf('vl.json') !== -1
) {
return true;
} else {
return false;
}
}
});
/**
* create and add the command to export the Voyager content
*/
commands.addCommand(CommandIDs.JL_Voyager_Export, {
label: 'Export Voyager as Vega-Lite File',
caption: 'Export the chart datasource as vl.json file',
execute: args => {
let widget = app.shell.currentWidget as DocumentWidget;
if (widget) {
const voyager_panel = widget.content as VoyagerPanel | VoyagerPanel_DF
var datavoyager = voyager_panel.voyager_cur;
var dataSrc = voyager_panel.data_src;
let context = docManager.contextForWidget(widget) as Context<
DocumentRegistry.IModel
>;
let path = PathExt.dirname(context.path);
let spec = datavoyager.getSpec(false);
if (spec !== undefined) {
createNew(
path,
{
data: dataSrc,
mark: spec.mark,
encoding: spec.encoding,
height: spec.height,
width: spec.width,
description: spec.description,
name: spec.name,
selection: spec.selection,
title: spec.title,
transform: spec.transform
},
false
);
} else {
createNew(
path,
{
data: dataSrc
},
false
);
}
}
},
isEnabled: () => {
let widget = app.shell.currentWidget as DocumentWidget;
if(widget&&widget.content.hasClass(Voyager_CLASS)&&(widget.content as VoyagerPanel|VoyagerPanel_DF).context.path.indexOf('vl.json')===-1){
return true;
}
else{
return false;
}
}
});
/**
* create and add the command to export the Voyager content to notebook(copy it to clipboard)
*/
commands.addCommand(CommandIDs.JL_Voyager_Export_To_Notebook, {
label: 'Copy Altair Graph to clipboard',
caption: 'Copy the Altair graph python code to clipboard',
execute: args => {
let widget = app.shell.currentWidget;
if (widget) {
var datavoyager = (widget as VoyagerPanel | VoyagerPanel_DF)
.voyager_cur;
var dataSrc = (widget as VoyagerPanel | VoyagerPanel_DF).data_src;
let spec = datavoyager.getSpec(false);
let src = JSON.stringify({
data: dataSrc,
mark: spec.mark,
encoding: spec.encoding,
height: spec.height,
width: spec.width,
description: spec.description,
name: spec.name,
selection: spec.selection,
title: spec.title,
transform: spec.transform
});
let clipboard = Clipboard.getInstance();
clipboard.clear();
let data = [
{
cell_type: "code",
execution_count: null,
metadata: {},
outputs: [],
source: [
"import altair as alt\n",
"import pandas as pd\n",
"import json\n",
`data_src = json.loads('''${src}''')\n`,
"alt.Chart.from_dict(data_src)\n"
]
}
];
clipboard.setData(JUPYTER_CELL_MIME, data);
}
},
isEnabled: () =>{
let widget = app.shell.currentWidget;
if(widget&&widget.hasClass(Voyager_CLASS)&&((widget as VoyagerPanel|VoyagerPanel_DF).voyager_cur.getSpec(false)!==undefined)){
return true;
}
else{
return false;
}
}
});
/**
* create and add the command to show or hide the toolbar inside Voyager UI
*/
commands.addCommand(CommandIDs.JL_Voyager_HideBar, {
label: "Show/Hide Toolbar",
caption: "show or hide toolbar in voyager",
execute: args => {
let widget = app.shell.currentWidget;
if (widget) {
if ((widget as VoyagerPanel | VoyagerPanel_DF).toolbar.isHidden) {
(widget as VoyagerPanel | VoyagerPanel_DF).toolbar.show();
} else {
(widget as VoyagerPanel | VoyagerPanel_DF).toolbar.hide();
}
}
},
isEnabled: () => {
let widget = app.shell.currentWidget;
if (widget && widget.hasClass(Voyager_CLASS)) {
return true;
} else {
return false;
}
}
});
/**
* create and add the command to undo the last operation in Voyager
*/
commands.addCommand(CommandIDs.JL_Voyager_Undo, {
label: "Undo",
caption: "Update state to reflect the previous state",
execute: args => {
let widget = app.shell.currentWidget;
if (widget) {
(widget as VoyagerPanel | VoyagerPanel_DF).voyager_cur.undo();
}
}
});
/**
* create and add the command to redo the previously canceled operation in Voyager
*/
commands.addCommand(CommandIDs.JL_Voyager_Redo, {
label: "Redo",
caption: "Update state to reflect the future state",
execute: args => {
let widget = app.shell.currentWidget;
if (widget) {
(widget as VoyagerPanel | VoyagerPanel_DF).voyager_cur.redo();
}
}
});
// Track and restore the tutorial widget state
let tracker0 = new WidgetTracker<VoyagerTutorialWidget>({
namespace: "voyager_tutorial"
});
const command: string = CommandIDs.JL_Voyager_Tutorial;
restorer.restore(tracker0, {
command,
args: () => JSONExt.emptyObject,
name: () => 'voyager_tutorial'
});
/**
* create and add the command to display the tutorial page
*/
commands.addCommand(CommandIDs.JL_Voyager_Tutorial, {
label: 'Voyager FAQ',
caption: 'Open tutorial page for JupyterLab_voyager',
execute: args => {
if (!T_widget) {
// Create a new widget if one does not exist
let content = rendermime.createRenderer("text/markdown");
const model = rendermime.createModel({
data: { "text/markdown": SOURCE }
});
content.renderModel(model);
content.addClass('jp-VoyagerTutorial-content');
T_widget = new VoyagerTutorialWidget(content);
T_widget.update();
}
if (!tracker0.has(T_widget)) {
// Track the state of the widget for later restoration
tracker0.add(T_widget);
}
if (!T_widget.isAttached) {
// Attach the widget to the main area if it's not there
app.shell.add(T_widget, 'main');
} else {
// Refresh the comic in the widget
T_widget.update();
}
// Activate the widget
app.shell.activateById(T_widget.id);
},
});
//Add the tutorial command into top menu 'Help' button
mainMenu.helpMenu.addGroup([{ command: CommandIDs.JL_Voyager_Tutorial }], 0);
//Add the 'Save' and 'Export' command into top menu 'File' button
mainMenu.fileMenu.addGroup(
[
{ command: CommandIDs.JL_Voyager_Save },
{ command: CommandIDs.JL_Voyager_Export }
],
10
);
//add phosphor context menu for voyager_dataframe, for the "save", "export", "show/hide toolbar", "undo", "redo" functions
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_Undo,
selector: ".voyager",
rank: 0
});
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_Redo,
selector: ".voyager",
rank: 1
});
app.contextMenu.addItem({
type: "separator",
selector: ".voyager",
rank: 2
});
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_HideBar,
selector: ".voyager",
rank: 3
});
app.contextMenu.addItem({
type: "separator",
selector: ".voyager",
rank: 4
});
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_Save1,
selector: ".voyager",
rank: 5
});
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_Export,
selector: ".voyager",
rank: 6
});
app.contextMenu.addItem({
command: CommandIDs.JL_Voyager_Export_To_Notebook,
selector: ".voyager",
rank: 7
});
//add context menu for altair image ouput
app.contextMenu.addItem({
command: CommandIDs.JL_Graph_Voyager,
selector: '.p-Widget.jp-RenderedVegaCommon3.jp-RenderedVegaLite2.jp-OutputArea-output.vega-embed'
});
app.contextMenu.addItem({
command: CommandIDs.JL_Graph_Voyager,
selector: '.p-Widget.jp-RenderedVegaCommon.jp-RenderedVegaLite.vega-embed.jp-OutputArea-output'
});
app.contextMenu.addItem({
command: CommandIDs.JL_Graph_Voyager,
selector: '.p-Widget.jp-RenderedImage.jp-OutputArea-output'
});
//add context menu for table ouput
app.contextMenu.addItem({
command: CommandIDs.JL_Table_Voyager,
selector: ".dataframe"
});
//add tsv file type to docRegistry to support "Open With ..." context menu;
app.docRegistry.addFileType({
name: 'tsv',
extensions: ['.tsv']
});
// Track and restore the Voyager widget state
const factoryName1 = `Voyager`;
const tracker1 = new WidgetTracker<IDocumentWidget<VoyagerPanel>>({
namespace: factoryName1
});
const factory1 = new VoyagerWidgetFactory(app, docManager, {
name: factoryName1,
fileTypes: ["csv", "json", "tsv", "vega-lite2", "vega3"],
readOnly: true
});
// Handle state restoration.
restorer.restore(tracker1, {
command: "docmanager:open",
args: widget => ({ path: widget.context.path, factory: factoryName1 }),
name: widget => widget.context.path
});
app.docRegistry.addWidgetFactory(factory1);
factory1.widgetCreated.connect((sender, widget) => {
// Track the widget.
widget.id = widget.id;
widget.title.icon = VOYAGER_ICON;
widget.context.pathChanged.connect(() => {
tracker1.save(widget);
});
tracker1.add(widget);
});
fileTypes.map(ft => {
let ftObj = app.docRegistry.getFileType(ft);
if (ftObj == undefined) {
console.log("app docreg getfile type: undefined");
} else {
console.log("app docreg getfile type: " + ftObj.name);
}
});
// Track and restore the notebook widget state (for opening vegalite file in notebook)
const factoryName2 = `Vegalite in New Notebook`;
const tracker2 = new WidgetTracker<NotebookPanel>({
namespace: factoryName2
});
const factory2 = new VoyagerNotebookWidgetFactory(app, {
name: factoryName2,
fileTypes: ["vega-lite2", "vega3"],
readOnly: true
});
// Handle state restoration.
restorer.restore(tracker2, {
command: "docmanager:open",
args: widget => ({ path: widget.context.path, factory: factoryName2 }),
name: widget => widget.context.path
});
app.docRegistry.addWidgetFactory(factory2);
factory2.widgetCreated.connect((sender, widget) => {
// Track the widget.
tracker2.add(widget);
widget.context.pathChanged.connect(() => {
tracker2.save(widget);
});
widget.title.iconClass = VOYAGER_ICON;
});
fileTypes_vega.map(ft => {
let ftObj = app.docRegistry.getFileType(ft);
if (ftObj == undefined) {
console.log('app docreg getfile type: undefined');
} else {
console.log('app docreg getfile type: ' + ftObj.name);
}
})
}
//const plugin: JupyterFrontEndPlugin<WidgetTracker<VoyagerPanel>> = {
const plugin: JupyterFrontEndPlugin<void> = {
activate: activate,
id: "jupyterlab_voyager:plugin",
autoStart: true,
requires: [
ILayoutRestorer,
INotebookTracker,
IDocumentManager,
IMainMenu,
IRenderMimeRegistry
]
};
export default plugin; | the_stack |
import {MessageData} from './ThreadData';
import {assert} from './utils';
const RE_FLAG_PATTERN = /^\/(.*)\/([gimuys]*)$/;
enum ConditionType {
AND, OR, NOT, SUBJECT, FROM, TO, CC, BCC, LIST, SENDER, RECEIVER, BODY,
}
/**
* S expression represents condition in rule.
*
* Syntax:
* CONDITION_EXP := (OPERATOR CONDITION_LIST) | (MATCHER STRING)
* OPERATOR := and | or | not
* MATCHER := subject | from | to | cc | bcc | list | sender | receiver | content
* CONDITION_LIST := CONDITION_EXP | CONDITION_EXP CONDITION_LIST
*/
export default class Condition {
private static parseSubConditions(rest_str: string, condition_str: string): Condition[] {
const result = [];
let start = 0, level = 0, length = rest_str.length;
for (let end = 0; end < length; end++) {
switch (rest_str[end]) {
case '(':
level++;
break;
case ')':
level--;
assert(level >= 0, `Condition ${condition_str} has non-balanced parentheses`);
if (level === 0) {
if (start < end) {
const sub_str = rest_str.substring(start, end + 1).trim();
if (sub_str.length > 0) {
result.push(new Condition(sub_str));
}
}
start = end + 1;
}
break;
}
}
assert(level === 0, `Condition ${condition_str} has non-balanced parentheses overall.`);
return result;
}
private static escapeRegExp(pattern: string): string {
return pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
private static parseRegExp(pattern: string, condition_str: string, matching_address: boolean): RegExp {
assert(pattern.length > 0, `Condition ${condition_str} should have value but not found`);
const match = pattern.match(RE_FLAG_PATTERN);
if (match !== null) {
// normal regexp
const [/* ignored */, p, flags] = match;
return new RegExp(p, flags);
} else if (pattern.startsWith('"') && pattern.endsWith('"')) {
// exact matching
return new RegExp(`(^|<)${Condition.escapeRegExp(pattern.substring(1, pattern.length - 1))}($|>)`, 'i');
} else if (matching_address) {
// ignoring label in address
return new RegExp(`(^|<)${Condition.escapeRegExp(pattern).replace('@', '(\\+[^@]+)?@')}($|>)`, 'i');
} else {
// containing matching
return new RegExp(Condition.escapeRegExp(pattern));
}
}
private readonly type: ConditionType;
private readonly regexp: RegExp;
private readonly sub_conditions: Condition[];
constructor(condition_str: string) {
condition_str = condition_str.trim();
assert(condition_str.startsWith('(') && condition_str.endsWith(')'),
`Condition ${condition_str} should be surrounded by ().`);
const first_space = condition_str.indexOf(" ");
const type_str = condition_str.substring(1, first_space).trim().toUpperCase();
const rest_str = condition_str.substring(first_space + 1, condition_str.length - 1).trim();
this.type = ConditionType[type_str as keyof typeof ConditionType];
switch (this.type) {
case ConditionType.AND:
case ConditionType.OR: {
this.sub_conditions = Condition.parseSubConditions(rest_str, condition_str);
break;
}
case ConditionType.NOT: {
this.sub_conditions = Condition.parseSubConditions(rest_str, condition_str);
if (this.sub_conditions.length !== 1) {
throw `Conditions of type ${type_str} must have exactly one sub-condition, but found ${this.sub_conditions.length}: ${rest_str}`;
}
break;
}
case ConditionType.FROM:
case ConditionType.TO:
case ConditionType.CC:
case ConditionType.BCC:
case ConditionType.LIST:
case ConditionType.SENDER:
case ConditionType.RECEIVER: {
this.regexp = Condition.parseRegExp(rest_str, condition_str, true);
break;
}
case ConditionType.SUBJECT:
case ConditionType.BODY: {
this.regexp = Condition.parseRegExp(rest_str, condition_str, false);
break;
}
default:
throw `Unexpected condition type ${type_str} from ${condition_str}.`;
}
}
match(message_data: MessageData): boolean {
switch (this.type) {
case ConditionType.AND: {
for (const sub_condition of this.sub_conditions) {
if (!sub_condition.match(message_data)) {
return false;
}
}
return true;
}
case ConditionType.OR: {
for (const sub_condition of this.sub_conditions) {
if (sub_condition.match(message_data)) {
return true;
}
}
return false;
}
case ConditionType.NOT: {
return !this.sub_conditions[0].match(message_data);
}
case ConditionType.FROM: {
return this.matchAddress(message_data.from);
}
case ConditionType.TO: {
return this.matchAddress(...message_data.to);
}
case ConditionType.CC: {
return this.matchAddress(...message_data.cc);
}
case ConditionType.BCC: {
return this.matchAddress(...message_data.bcc);
}
case ConditionType.LIST: {
return this.matchAddress(message_data.list);
}
case ConditionType.SENDER: {
return this.matchAddress(message_data.from);
}
case ConditionType.RECEIVER: {
return this.matchAddress(...message_data.receivers);
}
case ConditionType.SUBJECT: {
return this.regexp.test(message_data.subject);
}
case ConditionType.BODY: {
return this.regexp.test(message_data.body);
}
}
}
private matchAddress(...addresses: string[]) {
return addresses.some(address => this.regexp.test(address));
}
toString(): string {
const type_str = ConditionType[this.type];
const regexp_str = this.regexp ? this.regexp.source : "";
const sub_str = this.sub_conditions ? "\n" + this.sub_conditions.map(c => c.toString()).join("\n") : "";
return `(${type_str} ${regexp_str} ${sub_str})`;
}
public static testAll() {
function t(condition_str: string, target_str: string, is_address: boolean, should_matching: boolean) {
const regexp = Condition.parseRegExp(condition_str, "", is_address);
assert(regexp.test(target_str) === should_matching,
`Expect ${condition_str}(${regexp.source}) to match ${target_str}, but failed`);
}
// matching address ignoring labels
t('some-mailing-list@gmail.com', 'some-mailing-list@gmail.com', true, true);
t('some-mailing-list@gmail.com', 'prefix-some-mailing-list@gmail.com', true, false);
t('some-mailing-list@gmail.com', 'some-mailing-list-suffix@gmail.com', true, false);
t('some-mailing-list@gmail.com', 'some-mailing-list+tag1@gmail.com', true, true);
// matching address with name
t('abc@gmail.com', '<abc@gmail.com>', true, true);
t('abc@gmail.com', '<abc+dd@gmail.com>', true, true);
t('abc@gmail.com', 'dd <abc+dd@gmail.com>', true, true);
// if label is specified, then it's required
t('some-mailing-list+tag1@gmail.com', 'some-mailing-list@gmail.com', true, false);
t('some-mailing-list+tag1@gmail.com', 'some-mailing-list+tag1@gmail.com', true, true);
t('some-mailing-list+tag1@gmail.com', 'some-mailing-list+tag2@gmail.com', true, false);
// exact matching
t('"some-mailing-list@gmail.com"', 'some-mailing-list@gmail.com', true, true);
t('"some-mailing-list@gmail.com"', 'prefix-some-mailing-list@gmail.com', true, false);
t('"some-mailing-list@gmail.com"', 'some-mailing-list-suffix@gmail.com', true, false);
t('"some-mailing-list@gmail.com"', 'some-mailing-list+tag1@gmail.com', true, false);
// exact matching with tag
t('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list@gmail.com', true, false);
t('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list+tag1@gmail.com', true, true);
t('"some-mailing-list+tag1@gmail.com"', 'some-mailing-list+tag2@gmail.com', true, false);
// matches are case-insensitive
t('abc+Def@gmail.com', 'abc+def@gmail.com', true, true);
t('"abc+Def@gmail.com"', 'abc+def@gmail.com', true, true);
// regexp matching
t('/some-.*@gmail.com/', 'some-mailing-list@gmail.com', true, true);
t('/some-.*@gmail.com/', 'some-mailing-list+tag@gmail.com', true, true);
t('/some-.*@gmail.com/', 'some2-mailing-list@gmail.com', true, false);
t('/feedback access request/i', 'Feedback access request', false, true);
t('/abc.def/si', 'Abc\nDef', false, true);
const base_message = {
getFrom: () => '',
getTo: () => '',
getCc: () => '',
getBcc: () => '',
getReplyTo: () => '',
getSubject: () => '',
getPlainBody: () => '',
getRawContent: () => '',
} as GoogleAppsScript.Gmail.GmailMessage;
function c(condition_str: string, message: Partial<GoogleAppsScript.Gmail.GmailMessage>, expected: boolean) {
const condition = new Condition(condition_str);
const message_data = new MessageData(Object.assign({}, base_message, message));
assert(condition.match(message_data) === expected,
`Expected ${condition_str} matches email ${message}, but failed`);
}
c(`(and
(from abc@gmail.com)
(or
(receiver ijl@gmail.com)
(receiver xyz@gmail.com)))`,
{
getFrom: () => 'dd <abc+dd@gmail.com>',
getTo: () => 'something+-random@gmail.com',
getCc: () => 'xyz+tag@gmail.com',
},
true);
c(`(or
(receiver abc@gmail.com)
(receiver abc@corp.com))`,
{
getFrom: () => 'DDD EEE <def@corp.com>',
getTo: () => 'AAA BBB <abc@corp.com>, DDD EEE <def@corp.com>',
},
true);
c(`(not (receiver abc@gmail.com))`,
{
getTo: () => 'AAA BBB <abc@gmail.com>',
},
false);
c(`(not (receiver abc@gmail.com))`,
{
getTo: () => 'AAA BBB <def@gmail.com>',
},
true);
c(`(receiver abc+Def@bar.com)`,
{
getTo: () => 'abc+Def@bar.com',
},
true);
c(`(receiver "abc+Def@bar.com")`,
{
getTo: () => 'abc+Def@bar.com',
},
true);
}
} | the_stack |
import { Validators as NativeValidators, AbstractControl } from '@angular/forms';
import { ValidatorFn, ValidationErrors, AsyncValidatorFn } from './types';
import { FormControl } from './form-control';
// Next flag used because of this https://github.com/ng-packagr/ng-packagr/issues/696#issuecomment-373487183
// @dynamic
/**
* Provides a set of built-in validators that can be used by form controls.
*
* A validator is a function that processes a `FormControl` or collection of
* controls and returns an error map or null. A null map means that validation has passed.
*
* See also [Form Validation](https://angular.io/guide/form-validation).
*/
export class Validators extends NativeValidators {
/**
* Validator that requires the control's value to be greater than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* ### Validate against a minimum of 3
*
* ```ts
* const control = new FormControl(2, Validators.min(3));
*
* console.log(control.errors); // {min: {min: 3, actual: 2}}
* ```
*
* @returns A validator function that returns an error map with the
* `min` property if the validation check fails, otherwise `null`.
*
*/
static min(min: number) {
return super.min(min) as ValidatorFn<{ min: { min: number; actual: number } }>;
}
/**
* Validator that requires the control's value to be less than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* ### Validate against a maximum of 15
*
* ```ts
* const control = new FormControl(16, Validators.max(15));
*
* console.log(control.errors); // {max: {max: 15, actual: 16}}
* ```
*
* @returns A validator function that returns an error map with the
* `max` property if the validation check fails, otherwise `null`.
*
*/
static max(max: number) {
return super.max(max) as ValidatorFn<{ max: { max: number; actual: number } }>;
}
/**
* Validator that requires the control have a non-empty value.
*
* ### Validate that the field is non-empty
*
* ```ts
* const control = new FormControl('', Validators.required);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map with the `required` property
* if the validation check fails, otherwise `null`.
*
*/
static required(control: AbstractControl) {
return super.required(control) as ValidationErrors<{ required: true }> | null;
}
/**
* Validator that requires the control's value be true. This validator is commonly
* used for required checkboxes.
*
* ### Validate that the field value is true
*
* ```typescript
* const control = new FormControl('', Validators.requiredTrue);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map that contains the `required` property
* set to `true` if the validation check fails, otherwise `null`.
*/
static requiredTrue(control: AbstractControl) {
return super.requiredTrue(control) as ValidationErrors<{ required: true }> | null;
}
/**
* Validator that requires the control's value pass an email validation test.
*
* ### Validate that the field matches a valid email pattern
*
* ```typescript
* const control = new FormControl('bad@', Validators.email);
*
* console.log(control.errors); // {email: true}
* ```
*
* @returns An error map with the `email` property
* if the validation check fails, otherwise `null`.
*
*/
static email(control: AbstractControl) {
return super.email(control) as ValidationErrors<{ email: true }> | null;
}
/**
* Validator that requires the length of the control's value to be greater than or equal
* to the provided minimum length. This validator is also provided by default if you use the
* the HTML5 `minlength` attribute.
*
* ### Validate that the field has a minimum of 3 characters
*
* ```typescript
* const control = new FormControl('ng', Validators.minLength(3));
*
* console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}
* ```
*
* ```html
* <input minlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `minlength` if the validation check fails, otherwise `null`.
*/
static minLength(minLength: number) {
return super.minLength(minLength) as ValidatorFn<{
minlength: { requiredLength: number; actualLength: number };
}>;
}
/**
* Validator that requires the length of the control's value to be less than or equal
* to the provided maximum length. This validator is also provided by default if you use the
* the HTML5 `maxlength` attribute.
*
* ### Validate that the field has maximum of 5 characters
*
* ```typescript
* const control = new FormControl('Angular', Validators.maxLength(5));
*
* console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}
* ```
*
* ```html
* <input maxlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `maxlength` property if the validation check fails, otherwise `null`.
*/
static maxLength(maxLength: number) {
return super.maxLength(maxLength) as ValidatorFn<{
maxlength: { requiredLength: number; actualLength: number };
}>;
}
/**
* Validator that requires the control's value to match a regex pattern. This validator is also
* provided by default if you use the HTML5 `pattern` attribute.
*
* Note that if a Regexp is provided, the Regexp is used as is to test the values. On the other
* hand, if a string is passed, the `^` character is prepended and the `$` character is
* appended to the provided string (if not already present), and the resulting regular
* expression is used to test the values.
*
* ### Validate that the field only contains letters or spaces
*
* ```typescript
* const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));
*
* console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}
* ```
*
* ```html
* <input pattern="[a-zA-Z ]*">
* ```
*
* @returns A validator function that returns an error map with the
* `pattern` property if the validation check fails, otherwise `null`.
*/
static pattern(pattern: string | RegExp) {
return super.pattern(pattern) as ValidatorFn<{
pattern: { requiredPattern: string; actualValue: string };
}>;
}
/**
* Validator that performs no operation.
*/
static nullValidator(control: AbstractControl): null {
return null;
}
/**
* Compose multiple validators into a single function that returns the union
* of the individual error maps for the provided control.
*
* @returns A validator function that returns an error map with the
* merged error maps of the validators if the validation check fails, otherwise `null`.
*/
static compose(validators: null): null;
static compose<T extends object = any>(validators: (ValidatorFn | null | undefined)[]): ValidatorFn<T> | null;
static compose<T extends object = any>(validators: (ValidatorFn | null | undefined)[] | null): ValidatorFn<T> | null {
return super.compose(validators) as ValidatorFn<T> | null;
}
/**
* Compose multiple async validators into a single function that returns the union
* of the individual error objects for the provided control.
*
* @returns A validator function that returns an error map with the
* merged error objects of the async validators if the validation check fails, otherwise `null`.
*/
static composeAsync<T extends object = any>(validators: (AsyncValidatorFn<T> | null)[]) {
return super.composeAsync(validators) as AsyncValidatorFn<T> | null;
}
/**
* At least one file should be.
*
* **Note**: use this validator when `formControl.value` is an instance of `FormData` only.
*/
static fileRequired(formControl: FormControl<FormData>): ValidationErrors<{ fileRequired: true }> | null {
if (!(formControl.value instanceof FormData)) {
return { fileRequired: true };
}
const files: File[] = [];
formControl.value.forEach((file: File) => files.push(file));
for (const file of files) {
if (file instanceof File) {
return null;
}
}
return { fileRequired: true };
}
/**
* Minimal number of files.
*
* **Note**: use this validator when `formControl.value` is an instance of `FormData` only.
*/
static filesMinLength(
minLength: number
): ValidatorFn<{
filesMinLength: { requiredLength: number; actualLength: number };
}> {
return (formControl: FormControl<FormData>) => {
const value = formControl.value;
if (minLength < 1) {
return null;
}
if (!value || !(value instanceof FormData)) {
return { filesMinLength: { requiredLength: minLength, actualLength: 0 } };
}
const files: File[] = [];
value.forEach((file: File) => files.push(file));
const len = files.length;
if (len < minLength) {
return { filesMinLength: { requiredLength: minLength, actualLength: len } };
}
return null;
};
}
/**
* Maximal number of files.
*
* **Note**: use this validator when `formControl.value` is an instance of `FormData` only.
*/
static filesMaxLength(
maxLength: number
): ValidatorFn<{
filesMaxLength: { requiredLength: number; actualLength: number };
}> {
return (formControl: FormControl<FormData>) => {
if (!(formControl.value instanceof FormData)) {
return null;
}
const files: File[] = [];
formControl.value.forEach((file: File) => files.push(file));
const len = files.length;
if (len > maxLength) {
return { filesMaxLength: { requiredLength: maxLength, actualLength: len } };
}
return null;
};
}
/**
* Maximal size of a file.
*
* **Note**: use this validator when `formControl.value` is an instance of `FormData` only.
*/
static fileMaxSize(
maxSize: number
): ValidatorFn<{
fileMaxSize: { requiredSize: number; actualSize: number; file: File };
}> {
return (formControl: FormControl<FormData>) => {
if (!(formControl.value instanceof FormData)) {
return null;
}
const files: File[] = [];
formControl.value.forEach((file: File) => files.push(file));
for (const file of files) {
if (file instanceof File && file.size > maxSize) {
return { fileMaxSize: { requiredSize: maxSize, actualSize: file.size, file } };
}
}
return null;
};
}
} | the_stack |
import {aclColumnList} from 'app/client/aclui/ACLColumnList';
import {aclFormulaEditor} from 'app/client/aclui/ACLFormulaEditor';
import {aclSelect} from 'app/client/aclui/ACLSelect';
import {ACLUsersPopup} from 'app/client/aclui/ACLUsers';
import {PermissionKey, permissionsWidget} from 'app/client/aclui/PermissionsWidget';
import {GristDoc} from 'app/client/components/GristDoc';
import {reportError, UserError} from 'app/client/models/errors';
import {TableData} from 'app/client/models/TableData';
import {shadowScroll} from 'app/client/ui/shadowScroll';
import {bigBasicButton, bigPrimaryButton} from 'app/client/ui2018/buttons';
import {squareCheckbox} from 'app/client/ui2018/checkbox';
import {colors, testId} from 'app/client/ui2018/cssVars';
import {textInput} from 'app/client/ui2018/editableLabel';
import {cssIconButton, icon} from 'app/client/ui2018/icons';
import {menu, menuItemAsync} from 'app/client/ui2018/menus';
import {
emptyPermissionSet,
MixedPermissionValue,
parsePermissions,
PartialPermissionSet,
permissionSetToText,
summarizePermissions,
summarizePermissionSet
} from 'app/common/ACLPermissions';
import {ACLRuleCollection, SPECIAL_RULES_TABLE_ID} from 'app/common/ACLRuleCollection';
import {BulkColValues, RowRecord, UserAction} from 'app/common/DocActions';
import {
FormulaProperties,
getFormulaProperties,
RulePart,
RuleSet,
UserAttributeRule
} from 'app/common/GranularAccessClause';
import {isHiddenCol} from 'app/common/gristTypes';
import {isObject} from 'app/common/gutil';
import * as roles from 'app/common/roles';
import {SchemaTypes} from 'app/common/schema';
import {ANONYMOUS_USER_EMAIL, EVERYONE_EMAIL, getRealAccess} from 'app/common/UserAPI';
import {
BaseObservable,
Computed,
Disposable,
dom,
DomElementArg,
IDisposableOwner,
MutableObsArray,
obsArray,
Observable,
styled
} from 'grainjs';
import isEqual = require('lodash/isEqual');
// tslint:disable:max-classes-per-file no-console
// Types for the rows in the ACL tables we use.
type ResourceRec = SchemaTypes["_grist_ACLResources"] & {id?: number};
type RuleRec = Partial<SchemaTypes["_grist_ACLRules"]> & {id?: number, resourceRec?: ResourceRec};
type UseCB = <T>(obs: BaseObservable<T>) => T;
// Status of rules, which determines whether the "Save" button is enabled. The order of the values
// matters, as we take the max of all the parts to determine the ultimate status.
enum RuleStatus {
Unchanged,
ChangedValid,
Invalid,
CheckPending,
}
// UserAttribute autocomplete choices. RuleIndex is used to filter for only those user
// attributes made available by the previous rules.
interface IAttrOption {
ruleIndex: number;
value: string;
}
/**
* Top-most container managing state and dom-building for the ACL rule UI.
*/
export class AccessRules extends Disposable {
// Whether anything has changed, i.e. whether to show a "Save" button.
private _ruleStatus: Computed<RuleStatus>;
// Parsed rules obtained from DocData during last call to update(). Used for _ruleStatus.
private _ruleCollection = new ACLRuleCollection();
// Array of all per-table rules.
private _tableRules = this.autoDispose(obsArray<TableRules>());
// The default rule set for the document (for "*:*").
private _docDefaultRuleSet = Observable.create<DefaultObsRuleSet|null>(this, null);
// Special document-level rules, for resources of the form ("*SPECIAL:<RuleType>").
private _specialRules = Observable.create<SpecialRules|null>(this, null);
// Array of all UserAttribute rules.
private _userAttrRules = this.autoDispose(obsArray<ObsUserAttributeRule>());
// Array of all user-attribute choices created by UserAttribute rules. Used for lookup items in
// rules, and for ACLFormula completions.
private _userAttrChoices: Computed<IAttrOption[]>;
// Whether the save button should be enabled.
private _savingEnabled: Computed<boolean>;
// Error or warning message to show next to Save/Reset buttons if non-empty.
private _errorMessage = Observable.create(this, '');
// Map of tableId to the list of columns for all tables in the document.
private _aclResources: {[tableId: string]: string[]} = {};
private _aclUsersPopup = ACLUsersPopup.create(this);
private _publicEditAccess = Observable.create(this, false);
constructor(private _gristDoc: GristDoc) {
super();
this._ruleStatus = Computed.create(this, (use) => {
const defRuleSet = use(this._docDefaultRuleSet);
const tableRules = use(this._tableRules);
const specialRules = use(this._specialRules);
const userAttr = use(this._userAttrRules);
return Math.max(
defRuleSet ? use(defRuleSet.ruleStatus) : RuleStatus.Unchanged,
// If any tables/userAttrs were changed or added, they will be considered changed. If
// there were only removals, then length will be reduced.
getChangedStatus(tableRules.length < this._ruleCollection.getAllTableIds().length),
getChangedStatus(userAttr.length < this._ruleCollection.getUserAttributeRules().size),
...tableRules.map(t => use(t.ruleStatus)),
...userAttr.map(u => use(u.ruleStatus)),
specialRules ? use(specialRules.ruleStatus) : RuleStatus.Unchanged,
);
});
this._savingEnabled = Computed.create(this, this._ruleStatus, (use, s) =>
(s === RuleStatus.ChangedValid) && !use(this._publicEditAccess));
this._userAttrChoices = Computed.create(this, this._userAttrRules, (use, rules) => {
const result: IAttrOption[] = [
{ruleIndex: -1, value: 'user.Access'},
{ruleIndex: -1, value: 'user.Email'},
{ruleIndex: -1, value: 'user.UserID'},
{ruleIndex: -1, value: 'user.Name'},
{ruleIndex: -1, value: 'user.LinkKey.'},
{ruleIndex: -1, value: 'user.Origin'},
];
for (const [i, rule] of rules.entries()) {
const tableId = use(rule.tableId);
const name = use(rule.name);
for (const colId of this.getValidColIds(tableId) || []) {
result.push({ruleIndex: i, value: `user.${name}.${colId}`});
}
}
return result;
});
// The UI in this module isn't really dynamic (that would be tricky while allowing unsaved
// changes). Instead, react deliberately if rules change. Note that table/column renames would
// trigger changes to rules, so we don't need to listen for those separately.
for (const tableId of ['_grist_ACLResources', '_grist_ACLRules']) {
const tableData = this._gristDoc.docData.getTable(tableId)!;
this.autoDispose(tableData.tableActionEmitter.addListener(this._onChange, this));
}
this.autoDispose(this._gristDoc.docPageModel.currentDoc.addListener(this._updateDocAccessData, this));
this.update().catch((e) => this._errorMessage.set(e.message));
}
public get allTableIds() { return Object.keys(this._aclResources).sort(); }
public get userAttrRules() { return this._userAttrRules; }
public get userAttrChoices() { return this._userAttrChoices; }
/**
* Replace internal state from the rules in DocData.
*/
public async update() {
if (this.isDisposed()) { return; }
this._errorMessage.set('');
const rules = this._ruleCollection;
[ , , this._aclResources] = await Promise.all([
rules.update(this._gristDoc.docData, {log: console}),
this._updateDocAccessData(),
this._gristDoc.docComm.getAclResources(),
]);
if (this.isDisposed()) { return; }
this._tableRules.set(
rules.getAllTableIds()
.filter(tableId => (tableId !== SPECIAL_RULES_TABLE_ID))
.map(tableId => TableRules.create(this._tableRules,
tableId, this, rules.getAllColumnRuleSets(tableId), rules.getTableDefaultRuleSet(tableId)))
);
SpecialRules.create(this._specialRules, SPECIAL_RULES_TABLE_ID, this,
rules.getAllColumnRuleSets(SPECIAL_RULES_TABLE_ID),
rules.getTableDefaultRuleSet(SPECIAL_RULES_TABLE_ID));
DefaultObsRuleSet.create(this._docDefaultRuleSet, this, null, undefined, rules.getDocDefaultRuleSet());
this._userAttrRules.set(
Array.from(rules.getUserAttributeRules().values(), userAttr =>
ObsUserAttributeRule.create(this._userAttrRules, this, userAttr))
);
}
/**
* Collect the internal state into records and sync them to the document.
*/
public async save(): Promise<void> {
if (!this._savingEnabled.get()) { return; }
// Note that if anything has changed, we apply changes relative to the current state of the
// ACL tables (they may have changed by other users). So our changes will win.
const docData = this._gristDoc.docData;
const resourcesTable = docData.getTable('_grist_ACLResources')!;
const rulesTable = docData.getTable('_grist_ACLRules')!;
// Add/remove resources to have just the ones we need.
const newResources: RowRecord[] = flatten(
[{tableId: '*', colIds: '*'}],
this._specialRules.get()?.getResources() || [],
...this._tableRules.get().map(t => t.getResources()))
.map(r => ({id: -1, ...r}));
// Prepare userActions and a mapping of serializedResource to rowIds.
const resourceSync = syncRecords(resourcesTable, newResources, serializeResource);
// For syncing rules, we'll go by rowId that we store with each RulePart and with the RuleSet.
const newRules: RowRecord[] = [];
for (const rule of this.getRules()) {
// We use id of 0 internally to mark built-in rules. Skip those.
if (rule.id === 0) {
continue;
}
// Look up the rowId for the resource.
const resourceKey = serializeResource(rule.resourceRec as RowRecord);
const resourceRowId = resourceSync.rowIdMap.get(resourceKey);
if (!resourceRowId) {
throw new Error(`Resource missing in resource map: ${resourceKey}`);
}
newRules.push({
id: rule.id || -1,
resource: resourceRowId,
aclFormula: rule.aclFormula!,
permissionsText: rule.permissionsText!,
rulePos: rule.rulePos || null,
});
}
// UserAttribute rules are listed in the same rulesTable.
const defaultResourceRowId = resourceSync.rowIdMap.get(serializeResource({id: -1, tableId: '*', colIds: '*'}));
if (!defaultResourceRowId) {
throw new Error('Default resource missing in resource map');
}
for (const userAttr of this._userAttrRules.get()) {
const rule = userAttr.getRule();
newRules.push({
id: rule.id || -1,
resource: defaultResourceRowId,
rulePos: rule.rulePos || null,
userAttributes: rule.userAttributes,
});
}
// We need to fill in rulePos values. We'll add them in the order the rules are listed (since
// this.getRules() returns them in a suitable order), keeping rulePos unchanged when possible.
let lastGoodRulePos = 0;
let lastGoodIndex = -1;
for (let i = 0; i < newRules.length; i++) {
const pos = newRules[i].rulePos as number;
if (pos && pos > lastGoodRulePos) {
const step = (pos - lastGoodRulePos) / (i - lastGoodIndex);
for (let k = lastGoodIndex + 1; k < i; k++) {
newRules[k].rulePos = lastGoodRulePos + step * (k - lastGoodIndex);
}
lastGoodRulePos = pos;
lastGoodIndex = i;
}
}
// Fill in the rulePos values for the remaining rules.
for (let k = lastGoodIndex + 1; k < newRules.length; k++) {
newRules[k].rulePos = ++lastGoodRulePos;
}
// Prepare the UserActions for syncing the Rules table.
const rulesSync = syncRecords(rulesTable, newRules);
// Finally collect and apply all the actions together.
try {
await docData.sendActions([...resourceSync.userActions, ...rulesSync.userActions]);
} catch (e) {
// Report the error, but go on to update the rules. The user may lose their entries, but
// will see what's in the document. To preserve entries and show what's wrong, we try to
// catch errors earlier.
reportError(e);
}
// Re-populate the state from DocData once the records are synced.
await this.update();
}
public buildDom() {
return cssOuter(
cssAddTableRow(
bigBasicButton({disabled: true}, dom.hide(this._savingEnabled),
dom.text((use) => {
const s = use(this._ruleStatus);
return s === RuleStatus.CheckPending ? 'Checking...' :
s === RuleStatus.Unchanged ? 'Saved' : 'Invalid';
}),
testId('rules-non-save')
),
bigPrimaryButton('Save', dom.show(this._savingEnabled),
dom.on('click', () => this.save()),
testId('rules-save'),
),
bigBasicButton('Reset', dom.show(use => use(this._ruleStatus) !== RuleStatus.Unchanged),
dom.on('click', () => this.update()),
testId('rules-revert'),
),
bigBasicButton('Add Table Rules', cssDropdownIcon('Dropdown'), {style: 'margin-left: auto'},
menu(() =>
this.allTableIds.map((tableId) =>
// Add the table on a timeout, to avoid disabling the clicked menu item
// synchronously, which prevents the menu from closing on click.
menuItemAsync(() => this._addTableRules(tableId),
tableId,
dom.cls('disabled', (use) => use(this._tableRules).some(t => t.tableId === tableId)),
)
),
),
),
bigBasicButton('Add User Attributes', dom.on('click', () => this._addUserAttributes())),
bigBasicButton('Users', cssDropdownIcon('Dropdown'), elem => this._aclUsersPopup.attachPopup(elem),
dom.style('visibility', use => use(this._aclUsersPopup.isInitialized) ? '' : 'hidden')),
),
cssConditionError({style: 'margin-left: 16px'},
dom.maybe(this._publicEditAccess, () => dom('div',
'Public "Editor" access is incompatible with Access Rules. ' +
'To set rules, remove it or reduce to "Viewer".'
)),
dom.text(this._errorMessage),
testId('access-rules-error')
),
shadowScroll(
dom.maybe(use => use(this._userAttrRules).length, () =>
cssSection(
cssSectionHeading('User Attributes'),
cssTableRounded(
cssTableHeaderRow(
cssCell1(cssCell.cls('-rborder'), cssCell.cls('-center'), cssColHeaderCell('Name')),
cssCell4(
cssColumnGroup(
cssCell1(cssColHeaderCell('Attribute to Look Up')),
cssCell1(cssColHeaderCell('Lookup Table')),
cssCell1(cssColHeaderCell('Lookup Column')),
cssCellIcon(),
),
),
),
dom.forEach(this._userAttrRules, (userAttr) => userAttr.buildUserAttrDom()),
),
),
),
dom.forEach(this._tableRules, (tableRules) => tableRules.buildDom()),
cssSection(
cssSectionHeading('Default Rules', testId('rule-table-header')),
cssTableRounded(
cssTableHeaderRow(
cssCell1(cssCell.cls('-rborder'), cssCell.cls('-center'), cssColHeaderCell('Columns')),
cssCell4(
cssColumnGroup(
cssCellIcon(),
cssCell2(cssColHeaderCell('Condition')),
cssCell1(cssColHeaderCell('Permissions')),
cssCellIcon(),
)
)
),
dom.maybe(this._docDefaultRuleSet, ruleSet => ruleSet.buildRuleSetDom()),
),
testId('rule-table'),
),
dom.maybe(this._specialRules, tableRules => tableRules.buildDom()),
),
);
}
/**
* Get a list of all rule records, for saving.
*/
public getRules(): RuleRec[] {
return flatten(
...this._tableRules.get().map(t => t.getRules()),
this._specialRules.get()?.getRules() || [],
this._docDefaultRuleSet.get()?.getRules('*') || []
);
}
public removeTableRules(tableRules: TableRules) {
removeItem(this._tableRules, tableRules);
}
public removeUserAttributes(userAttr: ObsUserAttributeRule) {
removeItem(this._userAttrRules, userAttr);
}
public async checkAclFormula(text: string): Promise<FormulaProperties> {
if (text) {
return this._gristDoc.docComm.checkAclFormula(text);
}
return {};
}
// Check if the given tableId, and optionally a list of colIds, are present in this document.
// Returns '' if valid, or an error string if not. Exempt colIds will not trigger an error.
public checkTableColumns(tableId: string, colIds?: string[], exemptColIds?: string[]): string {
if (!tableId || tableId === SPECIAL_RULES_TABLE_ID) { return ''; }
const tableColIds = this._aclResources[tableId];
if (!tableColIds) { return `Invalid table: ${tableId}`; }
if (colIds) {
const validColIds = new Set([...tableColIds, ...exemptColIds || []]);
const invalidColIds = colIds.filter(c => !validColIds.has(c));
if (invalidColIds.length === 0) { return ''; }
return `Invalid columns in table ${tableId}: ${invalidColIds.join(', ')}`;
}
return '';
}
// Returns a list of valid colIds for the given table, or undefined if the table isn't valid.
public getValidColIds(tableId: string): string[]|undefined {
return this._aclResources[tableId]?.filter(id => !isHiddenCol(id)).sort();
}
private _addTableRules(tableId: string) {
if (this._tableRules.get().some(t => t.tableId === tableId)) {
throw new Error(`Trying to add TableRules for existing table ${tableId}`);
}
const defRuleSet: RuleSet = {tableId, colIds: '*', body: []};
this._tableRules.push(TableRules.create(this._tableRules, tableId, this, undefined, defRuleSet));
}
private _addUserAttributes() {
this._userAttrRules.push(ObsUserAttributeRule.create(this._userAttrRules, this, undefined, {focus: true}));
}
private _onChange() {
if (this._ruleStatus.get() === RuleStatus.Unchanged) {
// If no changes, it's safe to just reload the rules from docData.
this.update().catch((e) => this._errorMessage.set(e.message));
} else {
this._errorMessage.set(
'Access rules have changed. Click Reset to revert your changes and refresh the rules.'
);
}
}
private async _updateDocAccessData() {
const pageModel = this._gristDoc.docPageModel;
const doc = pageModel.currentDoc.get();
const permissionData = doc && await this._gristDoc.docComm.getUsersForViewAs();
if (this.isDisposed()) { return; }
this._aclUsersPopup.init(pageModel, permissionData);
// We do not allow Public Editor access in combination with Granular ACL rules. When
// _publicEditAccess is on, we show a warning and prevent saving rules.
if (permissionData) {
const publicEditAccess = permissionData.users.some(user => (
(user.email === EVERYONE_EMAIL || user.email === ANONYMOUS_USER_EMAIL) &&
roles.canEdit(getRealAccess(user, permissionData))
));
this._publicEditAccess.set(publicEditAccess);
}
}
}
// Represents all rules for a table.
class TableRules extends Disposable {
// Whether any table rules changed, and if they are valid.
public ruleStatus: Computed<RuleStatus>;
// The column-specific rule sets.
protected _columnRuleSets = this.autoDispose(obsArray<ColumnObsRuleSet>());
// Whether there are any column-specific rule sets.
private _haveColumnRules = Computed.create(this, this._columnRuleSets, (use, cols) => cols.length > 0);
// The default rule set (for columns '*'), if one is set.
private _defaultRuleSet = Observable.create<DefaultObsRuleSet|null>(this, null);
constructor(public readonly tableId: string, public _accessRules: AccessRules,
private _colRuleSets?: RuleSet[], private _defRuleSet?: RuleSet) {
super();
this._columnRuleSets.set(this._colRuleSets?.map(rs =>
this._createColumnObsRuleSet(this._columnRuleSets, this._accessRules, this, rs,
rs.colIds === '*' ? [] : rs.colIds)) || []);
if (!this._colRuleSets) {
// Must be a newly-created TableRules object. Just create a default RuleSet (for tableId:*)
DefaultObsRuleSet.create(this._defaultRuleSet, this._accessRules, this, this._haveColumnRules);
} else if (this._defRuleSet) {
DefaultObsRuleSet.create(this._defaultRuleSet, this._accessRules, this, this._haveColumnRules,
this._defRuleSet);
}
this.ruleStatus = Computed.create(this, (use) => {
const columnRuleSets = use(this._columnRuleSets);
const d = use(this._defaultRuleSet);
return Math.max(
getChangedStatus(
!this._colRuleSets || // This TableRules object must be newly-added
Boolean(d) !== Boolean(this._defRuleSet) || // Default rule set got added or removed
columnRuleSets.length < this._colRuleSets.length // There was a removal
),
d ? use(d.ruleStatus) : RuleStatus.Unchanged, // Default rule set got changed.
...columnRuleSets.map(rs => use(rs.ruleStatus))); // Column rule set was added or changed.
});
}
public buildDom() {
return cssSection(
cssSectionHeading(
dom('span', 'Rules for table ', cssTableName(this.tableId)),
cssIconButton(icon('Dots'), {style: 'margin-left: auto'},
menu(() => [
menuItemAsync(() => this._addColumnRuleSet(), 'Add Column Rule'),
menuItemAsync(() => this._addDefaultRuleSet(), 'Add Default Rule',
dom.cls('disabled', use => Boolean(use(this._defaultRuleSet)))),
menuItemAsync(() => this._accessRules.removeTableRules(this), 'Delete Table Rules'),
]),
testId('rule-table-menu-btn'),
),
testId('rule-table-header'),
),
cssTableRounded(
cssTableHeaderRow(
cssCell1(cssCell.cls('-rborder'), cssCell.cls('-center'), cssColHeaderCell('Columns')),
cssCell4(
cssColumnGroup(
cssCellIcon(),
cssCell2(cssColHeaderCell('Condition')),
cssCell1(cssColHeaderCell('Permissions')),
cssCellIcon(),
)
),
),
this.buildColumnRuleSets(),
),
this.buildErrors(),
testId('rule-table'),
);
}
public buildColumnRuleSets() {
return [
dom.forEach(this._columnRuleSets, ruleSet => ruleSet.buildRuleSetDom()),
dom.maybe(this._defaultRuleSet, ruleSet => ruleSet.buildRuleSetDom()),
];
}
public buildErrors() {
return dom.forEach(this._columnRuleSets, c => cssConditionError(dom.text(c.formulaError)));
}
/**
* Return the resources (tableId:colIds entities), for saving, checking along the way that they
* are valid.
*/
public getResources(): ResourceRec[] {
// Check that the colIds are valid.
const seen = {
allow: new Set<string>(), // columns mentioned in rules that only have 'allow's.
deny: new Set<string>(), // columns mentioned in rules that only have 'deny's.
mixed: new Set<string>() // columns mentioned in any rules.
};
for (const ruleSet of this._columnRuleSets.get()) {
const sign = ruleSet.summarizePermissions();
const counterSign = sign === 'mixed' ? 'mixed' : (sign === 'allow' ? 'deny' : 'allow');
const colIds = ruleSet.getColIdList();
if (colIds.length === 0) {
throw new UserError(`No columns listed in a column rule for table ${this.tableId}`);
}
for (const colId of colIds) {
if (seen[counterSign].has(colId)) {
// There may be an order dependency between rules. We've done a little analysis, to
// allow the useful pattern of forbidding all access to columns, and then adding back
// access to different sets for different teams/conditions (or allowing all access
// by default, and then forbidding different sets). But if there's a mix of
// allows and denies, then we throw up our hands.
// TODO: could analyze more deeply. An easy step would be to analyze per permission bit.
// Could also allow order dependency and provide a way to control the order.
// TODO: could be worth also flagging multiple rulesets with the same columns as
// undesirable.
throw new UserError(`Column ${colId} appears in multiple rules for table ${this.tableId}` +
` that might be order-dependent. Try splitting rules up differently?`);
}
if (sign === 'mixed') {
seen.allow.add(colId);
seen.deny.add(colId);
seen.mixed.add(colId);
} else {
seen[sign].add(colId);
seen.mixed.add(colId);
}
}
}
return [
...this._columnRuleSets.get().map(rs => ({tableId: this.tableId, colIds: rs.getColIds()})),
{tableId: this.tableId, colIds: '*'},
];
}
/**
* Get rules for this table, for saving.
*/
public getRules(): RuleRec[] {
return flatten(
...this._columnRuleSets.get().map(rs => rs.getRules(this.tableId)),
this._defaultRuleSet.get()?.getRules(this.tableId) || [],
);
}
public removeRuleSet(ruleSet: ObsRuleSet) {
if (ruleSet === this._defaultRuleSet.get()) {
this._defaultRuleSet.set(null);
} else {
removeItem(this._columnRuleSets, ruleSet);
}
if (!this._defaultRuleSet.get() && this._columnRuleSets.get().length === 0) {
this._accessRules.removeTableRules(this);
}
}
protected _createColumnObsRuleSet(
owner: IDisposableOwner, accessRules: AccessRules, tableRules: TableRules,
ruleSet: RuleSet|undefined, initialColIds: string[],
): ColumnObsRuleSet {
return ColumnObsRuleSet.create(owner, accessRules, tableRules, ruleSet, initialColIds);
}
private _addColumnRuleSet() {
this._columnRuleSets.push(ColumnObsRuleSet.create(this._columnRuleSets, this._accessRules, this, undefined, []));
}
private _addDefaultRuleSet() {
if (!this._defaultRuleSet.get()) {
DefaultObsRuleSet.create(this._defaultRuleSet, this._accessRules, this, this._haveColumnRules);
}
}
}
class SpecialRules extends TableRules {
public buildDom() {
return cssSection(
cssSectionHeading('Special Rules', testId('rule-table-header')),
this.buildColumnRuleSets(),
this.buildErrors(),
testId('rule-table'),
);
}
public getResources(): ResourceRec[] {
return this._columnRuleSets.get()
.filter(rs => !rs.hasOnlyBuiltInRules())
.map(rs => ({tableId: this.tableId, colIds: rs.getColIds()}));
}
protected _createColumnObsRuleSet(
owner: IDisposableOwner, accessRules: AccessRules, tableRules: TableRules,
ruleSet: RuleSet|undefined, initialColIds: string[],
): ColumnObsRuleSet {
return SpecialObsRuleSet.create(owner, accessRules, tableRules, ruleSet, initialColIds);
}
}
// Represents one RuleSet, for a combination of columns in one table, or the default RuleSet for
// all remaining columns in a table.
abstract class ObsRuleSet extends Disposable {
// Whether rules changed, and if they are valid. Never unchanged if this._ruleSet is undefined.
public ruleStatus: Computed<RuleStatus>;
// List of individual rule parts for this entity. The default permissions may be included as the
// last rule part, with an empty aclFormula.
protected readonly _body = this.autoDispose(obsArray<ObsRulePart>());
// ruleSet is omitted for a new ObsRuleSet added by the user.
constructor(public accessRules: AccessRules, protected _tableRules: TableRules|null, private _ruleSet?: RuleSet) {
super();
if (this._ruleSet) {
this._body.set(this._ruleSet.body.map(part => ObsRulePart.create(this._body, this, part)));
} else {
// If creating a new RuleSet, start with just a default permission part.
this._body.set([ObsRulePart.create(this._body, this, undefined)]);
}
this.ruleStatus = Computed.create(this, this._body, (use, body) => {
// If anything was changed or added, some part.ruleStatus will be other than Unchanged. If
// there were only removals, then body.length will have changed.
return Math.max(
getChangedStatus(body.length < (this._ruleSet?.body?.length || 0)),
...body.map(part => use(part.ruleStatus)));
});
}
public getRules(tableId: string): RuleRec[] {
// Return every part in the body, tacking on resourceRec to each rule.
return this._body.get().map(part => ({
...part.getRulePart(),
resourceRec: {tableId, colIds: this.getColIds()}
}))
// Skip entirely empty rule parts: they are invalid and dropping them is the best fix.
.filter(part => part.aclFormula || part.permissionsText);
}
public getColIds(): string {
return '*';
}
/**
* Check if RuleSet may only add permissions, only remove permissions, or may do either.
* A rule that neither adds nor removes permissions is treated as mixed for simplicity,
* though this would be suboptimal if this were a useful case to support.
*/
public summarizePermissions(): MixedPermissionValue {
return summarizePermissions(this._body.get().map(p => p.summarizePermissions()));
}
public abstract buildResourceDom(): DomElementArg;
public buildRuleSetDom() {
return cssTableRow(
cssCell1(cssCell.cls('-rborder'),
this.buildResourceDom(),
testId('rule-resource')
),
cssCell4(cssRuleBody.cls(''),
dom.forEach(this._body, part => part.buildRulePartDom()),
dom.maybe(use => !this.hasDefaultCondition(use), () =>
cssColumnGroup(
{style: 'min-height: 28px'},
cssCellIcon(
cssIconButton(icon('Plus'),
dom.on('click', () => this.addRulePart(null)),
testId('rule-add'),
)
),
testId('rule-extra-add'),
)
),
),
testId('rule-set'),
);
}
public removeRulePart(rulePart: ObsRulePart) {
removeItem(this._body, rulePart);
if (this._body.get().length === 0) {
this._tableRules?.removeRuleSet(this);
}
}
public addRulePart(beforeRule: ObsRulePart|null) {
const body = this._body.get();
const i = beforeRule ? body.indexOf(beforeRule) : body.length;
this._body.splice(i, 0, ObsRulePart.create(this._body, this, undefined));
}
/**
* Returns the first built-in rule. It's the only one of the built-in rules to get a "+" next to
* it, since we don't allow inserting new rules in-between built-in rules.
*/
public getFirstBuiltIn(): ObsRulePart|undefined {
return this._body.get().find(p => p.isBuiltIn());
}
/**
* When an empty-condition RulePart is the only part of a RuleSet, we can say it applies to
* "Everyone".
*/
public isSoleCondition(use: UseCB, part: ObsRulePart): boolean {
const body = use(this._body);
return body.length === 1 && body[0] === part;
}
/**
* When an empty-condition RulePart is last in a RuleSet, we say it applies to "Everyone Else".
*/
public isLastCondition(use: UseCB, part: ObsRulePart): boolean {
const body = use(this._body);
return body[body.length - 1] === part;
}
public hasDefaultCondition(use: UseCB): boolean {
const body = use(this._body);
return body.length > 0 && body[body.length - 1].hasEmptyCondition(use);
}
/**
* Which permission bits to allow the user to set.
*/
public getAvailableBits(): PermissionKey[] {
if (this._tableRules) {
return ['read', 'update', 'create', 'delete'];
} else {
// For the doc-wide rule set, expose the schemaEdit bit too.
return ['read', 'update', 'create', 'delete', 'schemaEdit'];
}
}
/**
* Get valid colIds for the table that this RuleSet is for.
*/
public getValidColIds(): string[] {
const tableId = this._tableRules?.tableId;
return (tableId && this.accessRules.getValidColIds(tableId)) || [];
}
/**
* Check if this rule set is limited to a set of columns.
*/
public hasColumns() {
return false;
}
public hasOnlyBuiltInRules() {
return this._body.get().every(rule => rule.isBuiltIn());
}
}
class ColumnObsRuleSet extends ObsRuleSet {
// Error message for this rule set, or '' if valid.
public formulaError: Computed<string>;
private _colIds = Observable.create<string[]>(this, this._initialColIds);
constructor(accessRules: AccessRules, tableRules: TableRules, ruleSet: RuleSet|undefined,
private _initialColIds: string[]) {
super(accessRules, tableRules, ruleSet);
this.formulaError = Computed.create(this, (use) => {
// Exempt existing colIds from checks, by including as a third argument.
return accessRules.checkTableColumns(tableRules.tableId, use(this._colIds), this._initialColIds);
});
const baseRuleStatus = this.ruleStatus;
this.ruleStatus = Computed.create(this, (use) => {
if (use(this.formulaError)) { return RuleStatus.Invalid; }
return Math.max(
getChangedStatus(!isEqual(use(this._colIds), this._initialColIds)),
use(baseRuleStatus));
});
}
public buildResourceDom(): DomElementArg {
return aclColumnList(this._colIds, this.getValidColIds());
}
public getColIdList(): string[] {
return this._colIds.get();
}
public getColIds(): string {
return this._colIds.get().join(",");
}
public getAvailableBits(): PermissionKey[] {
// Create/Delete bits can't be set on a column-specific rule.
return ['read', 'update'];
}
public hasColumns() {
return true;
}
}
class DefaultObsRuleSet extends ObsRuleSet {
constructor(accessRules: AccessRules, tableRules: TableRules|null,
private _haveColumnRules?: Observable<boolean>, ruleSet?: RuleSet) {
super(accessRules, tableRules, ruleSet);
}
public buildResourceDom() {
return [
cssCenterContent.cls(''),
cssDefaultLabel(
dom.text(use => this._haveColumnRules && use(this._haveColumnRules) ? 'All Other' : 'All'),
)
];
}
}
function getSpecialRuleDescription(type: string): string {
switch (type) {
case 'AccessRules':
return 'Allow everyone to view Access Rules.';
case 'FullCopies':
return 'Allow everyone to copy the entire document, or view it in full in fiddle mode.\n' +
'Useful for examples and templates, but not for sensitive data.';
default: return type;
}
}
function getSpecialRuleName(type: string): string {
switch (type) {
case 'AccessRules': return 'Permission to view Access Rules';
case 'FullCopies': return 'Permission to access the document in full when needed';
default: return type;
}
}
class SpecialObsRuleSet extends ColumnObsRuleSet {
public buildRuleSetDom() {
const isNonStandard: Observable<boolean> = Computed.create(null, this._body, (use, body) =>
!body.every(rule => rule.isBuiltIn() || rule.matches(use, 'True', '+R')));
const allowEveryone: Observable<boolean> = Computed.create(null, this._body,
(use, body) => !use(isNonStandard) && !body.every(rule => rule.isBuiltIn()))
.onWrite(val => this._allowEveryone(val));
const isExpanded = Observable.create<boolean>(null, isNonStandard.get());
return dom('div',
dom.autoDispose(isExpanded),
dom.autoDispose(allowEveryone),
cssRuleDescription(
{style: 'white-space: pre-line;'}, // preserve line breaks in long descriptions
cssIconButton(icon('Expand'),
dom.style('transform', (use) => use(isExpanded) ? 'rotate(90deg)' : ''),
dom.on('click', () => isExpanded.set(!isExpanded.get())),
testId('rule-special-expand'),
),
squareCheckbox(allowEveryone,
dom.prop('disabled', isNonStandard),
testId('rule-special-checkbox'),
),
getSpecialRuleDescription(this.getColIds()),
),
dom.maybe(isExpanded, () =>
cssTableRounded(
{style: 'margin-left: 56px'},
cssTableHeaderRow(
cssCellIcon(),
cssCell4(cssColHeaderCell(getSpecialRuleName(this.getColIds()))),
cssCell1(cssColHeaderCell('Permissions')),
cssCellIcon(),
),
cssTableRow(
cssRuleBody.cls(''),
dom.forEach(this._body, part => part.buildRulePartDom(true)),
),
testId('rule-set'),
)
),
testId('rule-special'),
testId(`rule-special-${this.getColIds()}`), // Make accessible in tests as, e.g. rule-special-FullCopies
);
}
public getAvailableBits(): PermissionKey[] {
return ['read'];
}
private _allowEveryone(value: boolean) {
const builtInRules = this._body.get().filter(r => r.isBuiltIn());
if (value === true) {
const rulePart: RulePart = {
aclFormula: 'True',
permissionsText: '+R',
permissions: parsePermissions('+R'),
};
this._body.set([ObsRulePart.create(this._body, this, rulePart, true), ...builtInRules]);
} else if (value === false) {
this._body.set(builtInRules);
}
}
}
class ObsUserAttributeRule extends Disposable {
public ruleStatus: Computed<RuleStatus>;
// If the rule failed validation, the error message to show. Blank if valid.
public formulaError: Computed<string>;
private _name = Observable.create<string>(this, this._userAttr?.name || '');
private _tableId = Observable.create<string>(this, this._userAttr?.tableId || '');
private _lookupColId = Observable.create<string>(this, this._userAttr?.lookupColId || '');
private _charId = Observable.create<string>(this, 'user.' + (this._userAttr?.charId || ''));
private _validColIds = Computed.create(this, this._tableId, (use, tableId) =>
this._accessRules.getValidColIds(tableId) || []);
private _userAttrChoices: Computed<IAttrOption[]>;
private _userAttrError = Observable.create(this, '');
constructor(private _accessRules: AccessRules, private _userAttr?: UserAttributeRule,
private _options: {focus?: boolean} = {}) {
super();
this.formulaError = Computed.create(
this, this._tableId, this._lookupColId, this._userAttrError,
(use, tableId, colId, userAttrError) => {
if (userAttrError.length) {
return userAttrError;
}
// Don't check for errors if it's an existing rule and hasn't changed.
if (use(this._tableId) === this._userAttr?.tableId &&
use(this._lookupColId) === this._userAttr?.lookupColId) {
return '';
}
return _accessRules.checkTableColumns(tableId, colId ? [colId] : undefined);
});
this.ruleStatus = Computed.create(this, use => {
if (use(this.formulaError)) { return RuleStatus.Invalid; }
return getChangedStatus(
use(this._name) !== this._userAttr?.name ||
use(this._tableId) !== this._userAttr?.tableId ||
use(this._lookupColId) !== this._userAttr?.lookupColId ||
use(this._charId) !== 'user.' + this._userAttr?.charId
);
});
// Reset lookupColId when tableId changes, since a colId from a different table would usually be wrong
this.autoDispose(this._tableId.addListener(() => this._lookupColId.set('')));
this._userAttrChoices = Computed.create(this, _accessRules.userAttrRules, (use, rules) => {
// Filter for only those choices created by previous rules.
const index = rules.indexOf(this);
return use(this._accessRules.userAttrChoices).filter(c => (c.ruleIndex < index));
});
}
public get name() { return this._name; }
public get tableId() { return this._tableId; }
public buildUserAttrDom() {
return cssTableRow(
cssCell1(cssCell.cls('-rborder'),
cssCellContent(
cssInput(this._name, async (val) => this._name.set(val),
{placeholder: 'Attribute name'},
(this._options.focus ? (elem) => { setTimeout(() => elem.focus(), 0); } : null),
testId('rule-userattr-name'),
),
),
),
cssCell4(cssRuleBody.cls(''),
cssColumnGroup(
cssCell1(
aclFormulaEditor({
initialValue: this._charId.get(),
readOnly: false,
setValue: (text) => this._setUserAttr(text),
placeholder: '',
getSuggestions: () => this._userAttrChoices.get().map(choice => choice.value),
customiseEditor: (editor => {
editor.on('focus', () => {
if (editor.getValue() == 'user.') {
// TODO this weirdly only works on the first click
(editor as any).completer?.showPopup(editor);
}
});
})
}),
testId('rule-userattr-attr'),
),
cssCell1(
aclSelect(this._tableId, this._accessRules.allTableIds,
{defaultLabel: '[Select Table]'}),
testId('rule-userattr-table'),
),
cssCell1(
aclSelect(this._lookupColId, this._validColIds,
{defaultLabel: '[Select Column]'}),
testId('rule-userattr-col'),
),
cssCellIcon(
cssIconButton(icon('Remove'),
dom.on('click', () => this._accessRules.removeUserAttributes(this)))
),
dom.maybe(this.formulaError, (msg) => cssConditionError(msg, testId('rule-error'))),
),
),
testId('rule-userattr'),
);
}
public getRule() {
const fullCharId = this._charId.get().trim();
const strippedCharId = fullCharId.startsWith('user.') ?
fullCharId.substring('user.'.length) : fullCharId;
const spec = {
name: this._name.get(),
tableId: this._tableId.get(),
lookupColId: this._lookupColId.get(),
charId: strippedCharId,
};
for (const [prop, value] of Object.entries(spec)) {
if (!value) {
throw new UserError(`Invalid user attribute rule: ${prop} must be set`);
}
}
if (this._getUserAttrError(fullCharId)) {
throw new UserError(`Invalid user attribute to look up`);
}
return {
id: this._userAttr?.origRecord?.id,
rulePos: this._userAttr?.origRecord?.rulePos as number|undefined,
userAttributes: JSON.stringify(spec),
};
}
private _setUserAttr(text: string) {
if (text === this._charId.get()) {
return;
}
this._charId.set(text);
this._userAttrError.set(this._getUserAttrError(text) || '');
}
private _getUserAttrError(text: string): string | null {
text = text.trim();
if (text.startsWith('user.LinkKey')) {
if (/user\.LinkKey\.\w+$/.test(text)) {
return null;
}
return 'Use a simple attribute of user.LinkKey, e.g. user.LinkKey.something';
}
const isChoice = this._userAttrChoices.get().map(choice => choice.value).includes(text);
if (!isChoice) {
return 'Not a valid user attribute';
}
return null;
}
}
// Represents one line of a RuleSet, a combination of an aclFormula and permissions to apply to
// requests that match it.
class ObsRulePart extends Disposable {
// Whether the rule part, and if it's valid or being checked.
public ruleStatus: Computed<RuleStatus>;
// Formula to show in the formula editor.
private _aclFormula = Observable.create<string>(this, this._rulePart?.aclFormula || "");
// Rule-specific completions for editing the formula, e.g. "user.Email" or "rec.City".
private _completions = Computed.create<string[]>(this, (use) => [
...use(this._ruleSet.accessRules.userAttrChoices).map(opt => opt.value),
...this._ruleSet.getValidColIds().map(colId => `rec.${colId}`),
...this._ruleSet.getValidColIds().map(colId => `newRec.${colId}`),
]);
// The permission bits.
private _permissions = Observable.create<PartialPermissionSet>(
this, this._rulePart?.permissions || emptyPermissionSet());
// Whether the rule is being checked after a change. Saving will wait for such checks to finish.
private _checkPending = Observable.create(this, false);
// If the formula failed validation, the error message to show. Blank if valid.
private _formulaError = Observable.create(this, '');
private _formulaProperties = Observable.create<FormulaProperties>(this, getAclFormulaProperties(this._rulePart));
// Error message if any validation failed.
private _error: Computed<string>;
// rulePart is omitted for a new ObsRulePart added by the user. If given, isNew may be set to
// treat the rule as new and only use the rulePart for its initialization.
constructor(private _ruleSet: ObsRuleSet, private _rulePart?: RulePart, isNew = false) {
super();
if (_rulePart && isNew) {
this._rulePart = undefined;
}
this._error = Computed.create(this, (use) => {
return use(this._formulaError) ||
this._warnInvalidColIds(use(this._formulaProperties).usedColIds) ||
( !this._ruleSet.isLastCondition(use, this) &&
use(this._aclFormula) === '' &&
permissionSetToText(use(this._permissions)) !== '' ?
'Condition cannot be blank' : ''
);
});
this.ruleStatus = Computed.create(this, (use) => {
if (use(this._error)) { return RuleStatus.Invalid; }
if (use(this._checkPending)) { return RuleStatus.CheckPending; }
return getChangedStatus(
use(this._aclFormula) !== this._rulePart?.aclFormula ||
!isEqual(use(this._permissions), this._rulePart?.permissions)
);
});
}
public getRulePart(): RuleRec {
// Use id of 0 to distinguish built-in rules from newly added rule, which will have id of undefined.
const id = this.isBuiltIn() ? 0 : this._rulePart?.origRecord?.id;
return {
id,
aclFormula: this._aclFormula.get(),
permissionsText: permissionSetToText(this._permissions.get()),
rulePos: this._rulePart?.origRecord?.rulePos as number|undefined,
};
}
public hasEmptyCondition(use: UseCB): boolean {
return use(this._aclFormula) === '';
}
public matches(use: UseCB, aclFormula: string, permissionsText: string): boolean {
return (use(this._aclFormula) === aclFormula &&
permissionSetToText(use(this._permissions)) === permissionsText);
}
/**
* Check if RulePart may only add permissions, only remove permissions, or may do either.
* A rule that neither adds nor removes permissions is treated as mixed for simplicity,
* though this would be suboptimal if this were a useful case to support.
*/
public summarizePermissions(): MixedPermissionValue {
return summarizePermissionSet(this._permissions.get());
}
/**
* Verify that the rule is in a good state, optionally given a proposed permission change.
*/
public sanityCheck(pset?: PartialPermissionSet) {
// Nothing to do! We now support all expressible rule permutations.
}
public buildRulePartDom(wide: boolean = false) {
return cssColumnGroup(
cssCellIcon(
(this._isNonFirstBuiltIn() ?
null :
cssIconButton(icon('Plus'),
dom.on('click', () => this._ruleSet.addRulePart(this)),
testId('rule-add'),
)
),
),
cssCell2(
wide ? cssCell4.cls('') : null,
aclFormulaEditor({
initialValue: this._aclFormula.get(),
readOnly: this.isBuiltIn(),
setValue: (value) => this._setAclFormula(value),
placeholder: dom.text((use) => {
return (
this._ruleSet.isSoleCondition(use, this) ? 'Everyone' :
this._ruleSet.isLastCondition(use, this) ? 'Everyone Else' :
'Enter Condition'
);
}),
getSuggestions: (prefix) => this._completions.get(),
}),
testId('rule-acl-formula'),
),
cssCell1(cssCell.cls('-stretch'),
permissionsWidget(this._ruleSet.getAvailableBits(), this._permissions,
{disabled: this.isBuiltIn(), sanityCheck: (pset) => this.sanityCheck(pset)},
testId('rule-permissions')
),
),
cssCellIcon(
(this.isBuiltIn() ?
null :
cssIconButton(icon('Remove'),
dom.on('click', () => this._ruleSet.removeRulePart(this)),
testId('rule-remove'),
)
),
),
dom.maybe(this._error, (msg) => cssConditionError(msg, testId('rule-error'))),
testId('rule-part'),
);
}
public isBuiltIn(): boolean {
return this._rulePart ? !this._rulePart.origRecord?.id : false;
}
private _isNonFirstBuiltIn(): boolean {
return this.isBuiltIn() && this._ruleSet.getFirstBuiltIn() !== this;
}
private async _setAclFormula(text: string) {
if (text === this._aclFormula.get()) { return; }
this._aclFormula.set(text);
this._checkPending.set(true);
this._formulaProperties.set({});
this._formulaError.set('');
try {
this._formulaProperties.set(await this._ruleSet.accessRules.checkAclFormula(text));
this.sanityCheck();
} catch (e) {
this._formulaError.set(e.message);
} finally {
this._checkPending.set(false);
}
}
private _warnInvalidColIds(colIds?: string[]) {
if (!colIds || !colIds.length) { return false; }
const allValid = new Set(this._ruleSet.getValidColIds());
const invalid = colIds.filter(c => !allValid.has(c));
if (invalid.length > 0) {
return `Invalid columns: ${invalid.join(', ')}`;
}
}
}
/**
* Produce UserActions to create/update/remove records, to replace data in tableData
* with newRecords. Records are matched on uniqueId(record), which defaults to returning
* String(record.id). UniqueIds of new records don't need to be unique as long as they don't
* overlap with uniqueIds of existing records.
*
* Return also a rowIdMap, mapping uniqueId(record) to a rowId used in the actions. The rowIds may
* include negative values (auto-generated when newRecords doesn't include one). These may be used
* in Reference values within the same action bundle.
*
* TODO This is a general-purpose function, and should live in a separate module.
*/
function syncRecords(tableData: TableData, newRecords: RowRecord[],
uniqueId: (r: RowRecord) => string = (r => String(r.id))
): {userActions: UserAction[], rowIdMap: Map<string, number>} {
const oldRecords = tableData.getRecords();
const rowIdMap = new Map<string, number>(oldRecords.map(r => [uniqueId(r), r.id]));
const newRecordMap = new Map<string, RowRecord>(newRecords.map(r => [uniqueId(r), r]));
const removedRecords: RowRecord[] = oldRecords.filter(r => !newRecordMap.has(uniqueId(r)));
// Generate a unique negative rowId for each added record.
const addedRecords: RowRecord[] = newRecords.filter(r => !rowIdMap.has(uniqueId(r)))
.map((r, index) => ({...r, id: -(index + 1)}));
// Array of [before, after] pairs for changed records.
const updatedRecords: Array<[RowRecord, RowRecord]> = oldRecords.map((r): ([RowRecord, RowRecord]|null) => {
const newRec = newRecordMap.get(uniqueId(r));
const updated = newRec && {...r, ...newRec, id: r.id};
return updated && !isEqual(updated, r) ? [r, updated] : null;
}).filter(isObject);
console.log("syncRecords: removing [%s], adding [%s], updating [%s]",
removedRecords.map(uniqueId).join(", "),
addedRecords.map(uniqueId).join(", "),
updatedRecords.map(([r]) => uniqueId(r)).join(", "));
const tableId = tableData.tableId;
const userActions: UserAction[] = [];
if (removedRecords.length > 0) {
userActions.push(['BulkRemoveRecord', tableId, removedRecords.map(r => r.id)]);
}
if (updatedRecords.length > 0) {
userActions.push(['BulkUpdateRecord', tableId, updatedRecords.map(([r]) => r.id), getColChanges(updatedRecords)]);
}
if (addedRecords.length > 0) {
userActions.push(['BulkAddRecord', tableId, addedRecords.map(r => r.id), getColValues(addedRecords)]);
}
// Include generated rowIds for added records into the returned map.
addedRecords.forEach(r => rowIdMap.set(uniqueId(r), r.id));
return {userActions, rowIdMap};
}
/**
* Convert a list of rows into an object with columns of values, used for
* BulkAddRecord/BulkUpdateRecord actions.
*/
function getColValues(records: RowRecord[]): BulkColValues {
const colIdSet = new Set<string>();
for (const r of records) {
for (const c of Object.keys(r)) {
if (c !== 'id') {
colIdSet.add(c);
}
}
}
const result: BulkColValues = {};
for (const colId of colIdSet) {
result[colId] = records.map(r => r[colId]);
}
return result;
}
/**
* Convert a list of [before, after] rows into an object of changes, skipping columns which
* haven't changed.
*/
function getColChanges(pairs: Array<[RowRecord, RowRecord]>): BulkColValues {
const colIdSet = new Set<string>();
for (const [before, after] of pairs) {
for (const c of Object.keys(after)) {
if (c !== 'id' && !isEqual(before[c], after[c])) {
colIdSet.add(c);
}
}
}
const result: BulkColValues = {};
for (const colId of colIdSet) {
result[colId] = pairs.map(([before, after]) => after[colId]);
}
return result;
}
function serializeResource(rec: RowRecord): string {
return JSON.stringify([rec.tableId, rec.colIds]);
}
function flatten<T>(...args: T[][]): T[] {
return ([] as T[]).concat(...args);
}
function removeItem<T>(observableArray: MutableObsArray<T>, item: T): boolean {
const i = observableArray.get().indexOf(item);
if (i >= 0) {
observableArray.splice(i, 1);
return true;
}
return false;
}
function getChangedStatus(value: boolean): RuleStatus {
return value ? RuleStatus.ChangedValid : RuleStatus.Unchanged;
}
function getAclFormulaProperties(part?: RulePart): FormulaProperties {
const aclFormulaParsed = part?.origRecord?.aclFormulaParsed;
return aclFormulaParsed ? getFormulaProperties(JSON.parse(String(aclFormulaParsed))) : {};
}
const cssOuter = styled('div', `
flex: auto;
height: 100%;
width: 100%;
max-width: 800px;
margin: 0 auto;
display: flex;
flex-direction: column;
`);
const cssAddTableRow = styled('div', `
flex: none;
margin: 16px 16px 8px 16px;
display: flex;
gap: 16px;
`);
const cssDropdownIcon = styled(icon, `
margin: -2px -2px 0 4px;
`);
const cssSection = styled('div', `
margin: 16px 16px 24px 16px;
`);
const cssSectionHeading = styled('div', `
display: flex;
align-items: center;
margin-bottom: 8px;
font-weight: bold;
color: ${colors.slate};
`);
const cssTableName = styled('span', `
color: ${colors.dark};
`);
const cssInput = styled(textInput, `
width: 100%;
border: 1px solid transparent;
cursor: pointer;
&:hover {
border: 1px solid ${colors.darkGrey};
}
&:focus {
box-shadow: inset 0 0 0 1px ${colors.cursor};
border-color: ${colors.cursor};
cursor: unset;
}
&[disabled] {
color: ${colors.dark};
background-color: ${colors.mediumGreyOpaque};
box-shadow: unset;
border-color: transparent;
}
`);
const cssConditionError = styled('div', `
margin-top: 4px;
width: 100%;
color: ${colors.error};
`);
/**
* Fairly general table styles.
*/
const cssTableRounded = styled('div', `
border: 1px solid ${colors.slate};
border-radius: 8px;
overflow: hidden;
`);
// Row with a border
const cssTableRow = styled('div', `
display: flex;
border-bottom: 1px solid ${colors.slate};
&:last-child {
border-bottom: none;
}
`);
// Darker table header
const cssTableHeaderRow = styled(cssTableRow, `
background-color: ${colors.mediumGrey};
color: ${colors.dark};
`);
// Cell for table column header.
const cssColHeaderCell = styled('div', `
margin: 4px 8px;
text-transform: uppercase;
font-weight: 500;
font-size: 10px;
`);
// General table cell.
const cssCell = styled('div', `
min-width: 0px;
overflow: hidden;
&-rborder {
border-right: 1px solid ${colors.slate};
}
&-center {
text-align: center;
}
&-stretch {
min-width: unset;
overflow: visible;
}
`);
// Variations on columns of different widths.
const cssCellIcon = styled(cssCell, `flex: none; width: 24px;`);
const cssCell1 = styled(cssCell, `flex: 1;`);
const cssCell2 = styled(cssCell, `flex: 2;`);
const cssCell4 = styled(cssCell, `flex: 4;`);
// Group of columns, which may be placed inside a cell.
const cssColumnGroup = styled('div', `
display: flex;
align-items: center;
gap: 0px 8px;
margin: 0 8px;
flex-wrap: wrap;
`);
const cssRuleBody = styled('div', `
display: flex;
flex-direction: column;
gap: 4px;
margin: 4px 0;
`);
const cssRuleDescription = styled('div', `
display: flex;
align-items: center;
margin: 16px 0 8px 0;
gap: 8px;
`);
const cssCellContent = styled('div', `
margin: 4px 8px;
`);
const cssCenterContent = styled('div', `
display: flex;
align-items: center;
justify-content: center;
`);
const cssDefaultLabel = styled('div', `
color: ${colors.slate};
font-weight: bold;
`); | the_stack |
module Fayde {
export class UINode extends DONode {
XObject: UIElement;
LayoutUpdater: minerva.core.Updater;
IsMouseOver: boolean = false;
constructor(xobj: UIElement) {
super(xobj);
var upd = this.LayoutUpdater = xobj.CreateLayoutUpdater();
upd.setAttachedValue("$node", this);
upd.setAttachedValue("$id", (<any>this.XObject)._ID);
}
VisualParentNode: UINode;
GetVisualRoot(): UINode {
var curNode = this;
var vpNode: UINode;
while (vpNode = curNode.VisualParentNode) {
curNode = vpNode;
}
return curNode;
}
IsLoaded: boolean = false;
SetIsLoaded(value: boolean) { }
OnVisualChildAttached(uie: UIElement) {
var un = uie.XamlNode;
Providers.InheritedStore.PropagateInheritedOnAdd(this.XObject, un);
un.SetVisualParentNode(this);
}
OnVisualChildDetached(uie: UIElement) {
var un = uie.XamlNode;
un.SetVisualParentNode(null);
Providers.InheritedStore.ClearInheritedOnRemove(this.XObject, un);
}
private SetVisualParentNode(visualParentNode: UINode) {
if (this.VisualParentNode === visualParentNode)
return;
this.VisualParentNode = visualParentNode;
this.LayoutUpdater.setVisualParent(visualParentNode ? visualParentNode.LayoutUpdater : null);
}
Focus(recurse?: boolean): boolean { return false; }
_EmitFocusChange(type: string) {
if (type === "got")
this._EmitGotFocus();
else if (type === "lost")
this._EmitLostFocus();
}
private _EmitLostFocus() {
var e = new Fayde.RoutedEventArgs();
var x = this.XObject;
x.OnLostFocus(e);
x.LostFocus.raise(x, e);
}
private _EmitGotFocus() {
var e = new Fayde.RoutedEventArgs();
var x = this.XObject;
x.OnGotFocus(e);
x.GotFocus.raise(x, e);
}
_EmitKeyDown(args: Fayde.Input.KeyEventArgs) {
var x = this.XObject;
x.OnKeyDown(args);
x.KeyDown.raise(x, args);
}
_EmitKeyUp(args: Fayde.Input.KeyEventArgs) {
var x = this.XObject;
x.OnKeyUp(args);
x.KeyUp.raise(x, args);
}
_EmitLostMouseCapture(pos: Point) {
var x = this.XObject;
var e = new Input.MouseEventArgs(pos);
x.OnLostMouseCapture(e);
x.LostMouseCapture.raise(x, e);
}
_EmitMouseEvent(type: Input.MouseInputType, isLeftButton: boolean, isRightButton: boolean, args: Input.MouseEventArgs): boolean {
var x = this.XObject;
switch (type) {
case Input.MouseInputType.MouseUp:
if (isLeftButton) {
x.OnMouseLeftButtonUp(<Input.MouseButtonEventArgs>args);
x.MouseLeftButtonUp.raise(x, args);
} else if (isRightButton) {
x.OnMouseRightButtonUp(<Input.MouseButtonEventArgs>args);
x.MouseRightButtonUp.raise(x, args);
}
break;
case Input.MouseInputType.MouseDown:
if (isLeftButton) {
x.OnMouseLeftButtonDown(<Input.MouseButtonEventArgs>args);
x.MouseLeftButtonDown.raise(x, args);
} else if (isRightButton) {
x.OnMouseRightButtonDown(<Input.MouseButtonEventArgs>args);
x.MouseRightButtonDown.raise(x, args);
}
break;
case Input.MouseInputType.MouseLeave:
this.IsMouseOver = false;
x.OnMouseLeave(args);
x.MouseLeave.raise(x, args);
break;
case Input.MouseInputType.MouseEnter:
this.IsMouseOver = true;
x.OnMouseEnter(args);
x.MouseEnter.raise(x, args);
break;
case Input.MouseInputType.MouseMove:
x.OnMouseMove(args);
x.MouseMove.raise(x, args);
break;
case Input.MouseInputType.MouseWheel:
x.OnMouseWheel(<Input.MouseWheelEventArgs>args);
x.MouseWheel.raise(x, <Input.MouseWheelEventArgs>args);
break;
default:
return false;
}
return args.Handled;
}
_EmitTouchEvent(type: Input.TouchInputType, args: Input.TouchEventArgs) {
var x = this.XObject;
switch (type) {
case Input.TouchInputType.TouchDown:
x.OnTouchDown(args);
x.TouchDown.raise(x, args);
break;
case Input.TouchInputType.TouchUp:
x.OnTouchUp(args);
x.TouchUp.raise(x, args);
break;
case Input.TouchInputType.TouchMove:
x.OnTouchMove(args);
x.TouchMove.raise(x, args);
break;
case Input.TouchInputType.TouchEnter:
x.OnTouchEnter(args);
x.TouchEnter.raise(x, args);
break;
case Input.TouchInputType.TouchLeave:
x.OnTouchLeave(args);
x.TouchLeave.raise(x, args);
break;
default:
return false;
}
return args.Handled;
}
_EmitGotTouchCapture(e: Input.TouchEventArgs) {
var x = this.XObject;
x.OnGotTouchCapture(e);
x.GotTouchCapture.raise(this, e);
}
_EmitLostTouchCapture(e: Input.TouchEventArgs) {
var x = this.XObject;
x.OnLostTouchCapture(e);
x.LostTouchCapture.raise(this, e);
}
CanCaptureMouse(): boolean { return true; }
CaptureMouse(): boolean {
if (!this.IsAttached)
return false;
Surface.SetMouseCapture(this);
return true;
}
ReleaseMouseCapture() {
if (!this.IsAttached)
return;
Surface.ReleaseMouseCapture(this);
}
IsAncestorOf(uin: UINode) {
var vpNode = uin;
while (vpNode && vpNode !== this)
vpNode = vpNode.VisualParentNode;
return vpNode === this;
}
TransformToVisual (uin?: UINode): Media.GeneralTransform {
var raw = minerva.core.Updater.transformToVisual(this.LayoutUpdater, uin ? uin.LayoutUpdater : null);
if (!raw)
throw new ArgumentException("UIElement not attached.");
var mt = new Media.MatrixTransform();
mt.SetCurrentValue(Media.MatrixTransform.MatrixProperty, new Media.Matrix(raw));
return mt;
}
}
export class UIElement extends DependencyObject implements Providers.IIsPropertyInheritable {
XamlNode: UINode;
CreateNode(): UINode { return new UINode(this); }
CreateLayoutUpdater(): minerva.core.Updater { return new minerva.core.Updater(); }
get IsItemsControl(): boolean { return false; }
get VisualParent() {
var vpNode = this.XamlNode.VisualParentNode;
if (vpNode) return vpNode.XObject;
return undefined;
}
static AllowDropProperty: DependencyProperty;
static CacheModeProperty: DependencyProperty;
static ClipProperty = DependencyProperty.RegisterCore("Clip", () => Media.Geometry, UIElement);
static EffectProperty = DependencyProperty.Register("Effect", () => Media.Effects.Effect, UIElement);
static IsHitTestVisibleProperty = DependencyProperty.RegisterCore("IsHitTestVisible", () => Boolean, UIElement, true);
static OpacityMaskProperty = DependencyProperty.RegisterCore("OpacityMask", () => Media.Brush, UIElement);
static OpacityProperty = DependencyProperty.RegisterCore("Opacity", () => Number, UIElement, 1.0);
static RenderTransformProperty = DependencyProperty.RegisterCore("RenderTransform", () => Media.Transform, UIElement);
static RenderTransformOriginProperty = DependencyProperty.Register("RenderTransformOrigin", () => Point, UIElement);
static TagProperty = DependencyProperty.Register("Tag", () => Object, UIElement);
static TriggersProperty: DependencyProperty = DependencyProperty.RegisterCore("Triggers", () => TriggerCollection, UIElement, undefined, (d, args) => (<UIElement>d)._TriggersChanged(args));
static UseLayoutRoundingProperty = InheritableOwner.UseLayoutRoundingProperty.ExtendTo(UIElement);
static VisibilityProperty = DependencyProperty.RegisterCore("Visibility", () => new Enum(Visibility), UIElement, Visibility.Visible);
IsInheritable(propd: DependencyProperty): boolean {
return propd === UIElement.UseLayoutRoundingProperty;
}
get IsMouseOver() { return this.XamlNode.IsMouseOver; }
get DesiredSize(): minerva.Size {
var ds = this.XamlNode.LayoutUpdater.assets.desiredSize;
return new minerva.Size(ds.width, ds.height);
}
get RenderSize(): minerva.Size {
var ds = this.XamlNode.LayoutUpdater.assets.renderSize;
return new minerva.Size(ds.width, ds.height);
}
//AllowDrop: boolean;
//CacheMode;
Clip: Media.Geometry;
Effect: Media.Effects.Effect;
IsHitTestVisible: boolean;
Cursor: CursorType;
OpacityMask: Media.Brush;
Opacity: number;
//Projection: Media.Projection;
RenderTransform: Media.Transform;
RenderTransformOrigin: Point;
Tag: any;
Triggers: TriggerCollection;
UseLayoutRounding: boolean;
Visibility: Visibility;
Focus(): boolean { return this.XamlNode.Focus(); }
CaptureMouse():boolean { return this.XamlNode.CaptureMouse(); }
ReleaseMouseCapture() { this.XamlNode.ReleaseMouseCapture(); }
IsAncestorOf(uie: UIElement): boolean {
if (!uie) return false;
return this.XamlNode.IsAncestorOf(uie.XamlNode);
}
TransformToVisual(uie: UIElement): Media.GeneralTransform {
var uin = (uie) ? uie.XamlNode : null;
return this.XamlNode.TransformToVisual(uin);
}
InvalidateMeasure() { this.XamlNode.LayoutUpdater.invalidateMeasure(); }
Measure(availableSize: minerva.Size) {
this.XamlNode.LayoutUpdater.measure(availableSize);
}
InvalidateArrange() { this.XamlNode.LayoutUpdater.invalidateArrange(); }
Arrange(finalRect: minerva.Rect) {
this.XamlNode.LayoutUpdater.arrange(finalRect);
}
LostFocus = new RoutedEvent<RoutedEventArgs>();
GotFocus = new RoutedEvent<RoutedEventArgs>();
LostMouseCapture = new RoutedEvent<Input.MouseEventArgs>();
KeyDown = new RoutedEvent<Input.KeyEventArgs>();
KeyUp = new RoutedEvent<Input.KeyEventArgs>();
MouseLeftButtonUp = new RoutedEvent<Input.MouseButtonEventArgs>();
MouseRightButtonUp = new RoutedEvent<Input.MouseButtonEventArgs>();
MouseLeftButtonDown = new RoutedEvent<Input.MouseButtonEventArgs>();
MouseRightButtonDown = new RoutedEvent<Input.MouseButtonEventArgs>();
MouseLeave = new RoutedEvent<Input.MouseEventArgs>();
MouseEnter = new RoutedEvent<Input.MouseEventArgs>();
MouseMove = new RoutedEvent<Input.MouseEventArgs>();
MouseWheel = new RoutedEvent<Input.MouseWheelEventArgs>();
TouchDown = new RoutedEvent<Input.TouchEventArgs>();
TouchUp = new RoutedEvent<Input.TouchEventArgs>();
TouchEnter = new RoutedEvent<Input.TouchEventArgs>();
TouchLeave = new RoutedEvent<Input.TouchEventArgs>();
TouchMove = new RoutedEvent<Input.TouchEventArgs>();
GotTouchCapture = new RoutedEvent<Input.TouchEventArgs>();
LostTouchCapture = new RoutedEvent<Input.TouchEventArgs>();
OnGotFocus(e: RoutedEventArgs) { }
OnLostFocus(e: RoutedEventArgs) { }
OnLostMouseCapture(e: Input.MouseEventArgs) { }
OnKeyDown(e: Input.KeyEventArgs) { }
OnKeyUp(e: Input.KeyEventArgs) { }
OnMouseEnter(e: Input.MouseEventArgs) { }
OnMouseLeave(e: Input.MouseEventArgs) { }
OnMouseLeftButtonDown(e: Input.MouseButtonEventArgs) { }
OnMouseLeftButtonUp(e: Input.MouseButtonEventArgs) { }
OnMouseMove(e: Input.MouseEventArgs) { }
OnMouseRightButtonDown(e: Input.MouseButtonEventArgs) { }
OnMouseRightButtonUp(e: Input.MouseButtonEventArgs) { }
OnMouseWheel(e: Input.MouseWheelEventArgs) { }
OnTouchDown(e: Input.TouchEventArgs) { }
OnTouchUp(e: Input.TouchEventArgs) { }
OnTouchEnter(e: Input.TouchEventArgs) { }
OnTouchLeave(e: Input.TouchEventArgs) { }
OnTouchMove(e: Input.TouchEventArgs) { }
OnGotTouchCapture(e: Input.TouchEventArgs) { }
OnLostTouchCapture(e: Input.TouchEventArgs) { }
private _TriggersChanged(args: IDependencyPropertyChangedEventArgs) {
var oldTriggers = <TriggerCollection>args.OldValue;
var newTriggers = <TriggerCollection>args.NewValue;
if (oldTriggers instanceof TriggerCollection)
oldTriggers.DetachTarget(this);
if (newTriggers instanceof TriggerCollection)
newTriggers.AttachTarget(this);
}
}
Fayde.CoreLibrary.add(UIElement);
module reactions {
UIReaction<minerva.IGeometry>(UIElement.ClipProperty, minerva.core.reactTo.clip);
UIReaction<minerva.IEffect>(UIElement.EffectProperty, minerva.core.reactTo.effect);
UIReaction<boolean>(UIElement.IsHitTestVisibleProperty, minerva.core.reactTo.isHitTestVisible, false);
UIReaction<number>(UIElement.OpacityProperty, minerva.core.reactTo.opacity, false);
UIReaction<Media.Transform>(UIElement.RenderTransformProperty, minerva.core.reactTo.renderTransform);
UIReaction<minerva.Point>(UIElement.RenderTransformOriginProperty, minerva.core.reactTo.renderTransformOrigin, false, minerva.Point.copyTo);
UIReaction<minerva.Visibility>(UIElement.VisibilityProperty, (upd, ov, nv, uie?) => {
minerva.core.reactTo.visibility(upd, ov, nv);
Surface.RemoveFocusFrom(uie);
}, false);
}
} | the_stack |
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
import { MediaCrossOriginOption, MediaPreloadOption } from "./components/providers/file/MediaFileProvider";
import { TooltipDirection, TooltipPosition } from "./components/ui/tooltip/types";
import { PlayerProps } from "./components/core/player/PlayerProps";
import { Logger } from "./components/core/player/PlayerLogger";
import { Params } from "./utils/network";
import { ViewType } from "./components/core/player/ViewType";
import { MediaResource } from "./components/providers/file/MediaResource";
import { PlayerProps as PlayerProps1 } from ".";
import { IconLibraryResolver } from "./components/ui/icon-library/IconRegistry";
import { Provider } from "./components/providers/Provider";
import { MediaType } from "./components/core/player/MediaType";
import { Translation } from "./components/core/player/lang/Translation";
import { AdapterHost, MediaProviderAdapter } from "./components/providers/MediaProvider";
import { SettingsController } from "./components/ui/settings/settings/SettingsController";
export namespace Components {
interface VmAudio {
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLMediaElement>; play: () => Promise<void | undefined>; pause: () => Promise<void | undefined>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; canSetPiP: () => Promise<boolean>; enterPiP: () => Promise<any>; exitPiP: () => Promise<any>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; setCurrentTextTrack: (trackId: number) => Promise<void>; setTextTrackVisibility: (isVisible: boolean) => Promise<void>; }>;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"willAttach": boolean;
}
interface VmCaptionControl {
/**
* The URL to an SVG element or fragment to load.
*/
"hideIcon": string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isTextTrackVisible": PlayerProps['isTextTrackVisible'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady": PlayerProps['playbackReady'];
/**
* The URL to an SVG element or fragment to load.
*/
"showIcon": string;
"textTracks": PlayerProps['textTracks'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
}
interface VmCaptions {
"currentTextTrack": PlayerProps['currentTextTrack'];
/**
* Whether the captions should be visible or not.
*/
"hidden": boolean;
"isControlsActive": PlayerProps['isControlsActive'];
"isTextTrackVisible": PlayerProps['isTextTrackVisible'];
"isVideoView": PlayerProps['isVideoView'];
"playbackStarted": PlayerProps['playbackStarted'];
"textTracks": PlayerProps['textTracks'];
}
interface VmClickToPlay {
"forceClick": () => Promise<void>;
"isMobile": PlayerProps['isMobile'];
"isVideoView": PlayerProps['isVideoView'];
"paused": PlayerProps['paused'];
/**
* By default this is disabled on mobile to not interfere with playback, set this to `true` to enable it.
*/
"useOnMobile": boolean;
}
interface VmControl {
/**
* Removes focus from the control.
*/
"blurControl": () => Promise<void>;
/**
* If the control has a popup menu, this indicates whether the menu is open or not. Sets the `aria-expanded` property.
*/
"expanded"?: boolean;
/**
* Focuses the control.
*/
"focusControl": () => Promise<void>;
/**
* Whether the control should be displayed or not.
*/
"hidden": boolean;
/**
* The `id` attribute of the control.
*/
"identifier"?: string;
"isTouch": PlayerProps['isTouch'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The `aria-label` property of the control.
*/
"label": string;
/**
* If the control has a popup menu, then this should be the `id` of said menu. Sets the `aria-controls` property.
*/
"menu"?: string;
/**
* If the control is a toggle, this indicated whether the control is in a "pressed" state or not. Sets the `aria-pressed` property.
*/
"pressed"?: boolean;
}
interface VmControlGroup {
/**
* Determines where to add spacing/margin. The amount of spacing is determined by the CSS variable `--control-group-spacing`.
*/
"space": 'top' | 'bottom' | 'both' | 'none';
}
interface VmControlSpacer {
}
interface VmControls {
/**
* The length in milliseconds that the controls are active for before fading out. Audio players are not effected by this prop.
*/
"activeDuration": number;
/**
* Sets the `align-items` flex property that aligns the individual controls on the cross-axis.
*/
"align": 'start' | 'center' | 'end';
/**
* Sets the `flex-direction` property that manages the direction in which the controls are layed out.
*/
"direction": 'row' | 'column';
/**
* Whether the controls container should be 100% height. This has no effect if the view is of type `audio`.
*/
"fullHeight": boolean;
/**
* Whether the controls container should be 100% width. This has no effect if the view is of type `audio`.
*/
"fullWidth": boolean;
/**
* Whether the controls are visible or not.
*/
"hidden": boolean;
/**
* Whether the controls should hide when the mouse leaves the player. Audio players are not effected by this prop.
*/
"hideOnMouseLeave": boolean;
/**
* Whether the controls should show/hide when paused. Audio players are not effected by this prop.
*/
"hideWhenPaused": boolean;
"isAudioView": PlayerProps['isAudioView'];
"isControlsActive": PlayerProps['isControlsActive'];
"isSettingsActive": PlayerProps['isSettingsActive'];
/**
* Sets the `justify-content` flex property that aligns the individual controls on the main-axis.
*/
"justify": | 'start'
| 'center'
| 'end'
| 'space-around'
| 'space-between'
| 'space-evenly';
"paused": PlayerProps['paused'];
/**
* Pins the controls to the defined position inside the video player. This has no effect when the view is of type `audio`.
*/
"pin": 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'center';
"playbackReady": PlayerProps['playbackReady'];
"playbackStarted": PlayerProps['playbackStarted'];
/**
* Whether the controls should wait for playback to start before being shown. Audio players are not effected by this prop.
*/
"waitForPlaybackStart": boolean;
}
interface VmCurrentTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours": boolean;
"currentTime": PlayerProps['currentTime'];
"i18n": PlayerProps['i18n'];
}
interface VmDailymotion {
"autoplay": boolean;
/**
* Change the default highlight color used in the controls (hex value without the leading #). Color set in the Partner HQ will override this prop.
*/
"color"?: string;
"controls": boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLVmEmbedElement>; play: () => Promise<void>; pause: () => Promise<void>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackQuality: () => Promise<boolean>; setPlaybackQuality: (quality: string) => Promise<void>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; }>;
"language": string;
"logger"?: Logger;
"loop": boolean;
"muted": boolean;
"playsinline": boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* Whether to automatically play the next video in the queue.
*/
"shouldAutoplayQueue": boolean;
/**
* Whether to display the Dailymotion logo.
*/
"showDailymotionLogo": boolean;
/**
* Whether to show buttons for sharing the video.
*/
"showShareButtons": boolean;
/**
* Whether to show the 'Up Next' queue.
*/
"showUpNextQueue": boolean;
/**
* Whether to show video information (title and owner) on the start screen.
*/
"showVideoInfo": boolean;
/**
* Forwards your syndication key to the player.
*/
"syndication"?: string;
/**
* The Dailymotion resource ID of the video to load.
*/
"videoId": string;
}
interface VmDash {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
"autoplay": boolean;
/**
* The `dashjs` configuration.
*/
"config": Record<string, any>;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
"currentTextTrack": number;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
/**
* Are text tracks enabled by default.
*/
"enableTextTracksByDefault": boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<any>; canPlay: (type: any) => Promise<boolean>; canSetPlaybackQuality: () => Promise<boolean>; setPlaybackQuality: (quality: string) => Promise<void>; setCurrentTextTrack: (trackId: number) => Promise<void>; setTextTrackVisibility: (isVisible: boolean) => Promise<void>; play: () => Promise<void | undefined>; pause: () => Promise<void | undefined>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; canSetPiP: () => Promise<boolean>; enterPiP: () => Promise<any>; exitPiP: () => Promise<any>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; }>;
"isTextTrackVisible": boolean;
/**
* The URL where the `dashjs` library source can be found. If this property is used, then the `version` property is ignored.
*/
"libSrc"?: string;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"shouldRenderNativeTextTracks": boolean;
/**
* The URL of the `manifest.mpd` file to use.
*/
"src": string;
/**
* The NPM package version of the `dashjs` library to download and use.
*/
"version": string;
}
interface VmDblClickFullscreen {
"isFullscreenActive": PlayerProps['isFullscreenActive'];
"isMobile": PlayerProps['isMobile'];
"isVideoView": PlayerProps['isVideoView'];
"playbackReady": PlayerProps['playbackReady'];
/**
* By default this is disabled on mobile to not interfere with playback, set this to `true` to enable it.
*/
"useOnMobile": boolean;
}
interface VmDefaultControls {
/**
* The length in milliseconds that the controls are active for before fading out. Audio players are not effected by this prop.
*/
"activeDuration": number;
/**
* Whether the controls should hide when the mouse leaves the player. Audio players are not effected by this prop.
*/
"hideOnMouseLeave": boolean;
/**
* Whether the controls should show/hide when paused. Audio players are not effected by this prop.
*/
"hideWhenPaused": boolean;
"isAudioView": PlayerProps['isAudioView'];
"isLive": PlayerProps['isLive'];
"isMobile": PlayerProps['isMobile'];
"isVideoView": PlayerProps['isVideoView'];
"theme"?: PlayerProps['theme'];
/**
* Whether the controls should wait for playback to start before being shown. Audio players are not effected by this prop.
*/
"waitForPlaybackStart": boolean;
}
interface VmDefaultSettings {
"audioTracks": PlayerProps['audioTracks'];
"currentAudioTrack": number;
"currentTextTrack": number;
"i18n": PlayerProps['i18n'];
"isTextTrackVisible": boolean;
"isVideoView": PlayerProps['isAudioView'];
/**
* Pins the settings to the defined position inside the video player. This has no effect when the view is of type `audio`, it will always be `bottomRight`.
*/
"pin": 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
"playbackQualities": PlayerProps['playbackQualities'];
"playbackQuality"?: PlayerProps['playbackQuality'];
"playbackRate": PlayerProps['playbackRate'];
"playbackRates": PlayerProps['playbackRates'];
"playbackReady": PlayerProps['playbackReady'];
"textTracks": PlayerProps['textTracks'];
}
interface VmDefaultUi {
/**
* Whether the custom captions UI should not be loaded.
*/
"noCaptions": boolean;
/**
* Whether clicking the player should not toggle playback.
*/
"noClickToPlay": boolean;
/**
* Whether the custom default controls should not be loaded.
*/
"noControls": boolean;
/**
* Whether double clicking the player should not toggle fullscreen mode.
*/
"noDblClickFullscreen": boolean;
/**
* Whether the default loading screen should not be loaded.
*/
"noLoadingScreen": boolean;
/**
* Whether the custom poster UI should not be loaded.
*/
"noPoster": boolean;
/**
* Whether the custom default settings menu should not be loaded.
*/
"noSettings": boolean;
/**
* Whether the custom spinner UI should not be loaded.
*/
"noSpinner": boolean;
}
interface VmEmbed {
/**
* A function which accepts the raw message received from the embedded media player via `postMessage` and converts it into a POJO.
*/
"decoder"?: (
data: string,
) => Params | undefined;
/**
* A URL that will load the external player and media (Eg: https://www.youtube.com/embed/DyTCOwB0DVw).
*/
"embedSrc": string;
/**
* The title of the current media so it can be set on the inner `iframe` for screen readers.
*/
"mediaTitle": string;
/**
* Where the src request had originated from without any path information.
*/
"origin"?: string;
/**
* The parameters to pass to the embedded player which are appended to the `embedSrc` prop. These can be passed in as a query string or object.
*/
"params": string | Params;
/**
* Posts a message to the embedded media player.
*/
"postMessage": (message: any, target?: string | undefined) => Promise<void>;
/**
* A collection of URLs to that the browser should immediately start establishing a connection with.
*/
"preconnections": string[];
}
interface VmEndTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours": boolean;
"duration": PlayerProps['duration'];
"i18n": PlayerProps['i18n'];
}
interface VmFile {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
"autoplay": boolean;
"controls": boolean;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
"currentTextTrack": number;
"currentTime": number;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLMediaElement>; play: () => Promise<void | undefined>; pause: () => Promise<void | undefined>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; canSetPiP: () => Promise<boolean>; enterPiP: () => Promise<any>; exitPiP: () => Promise<any>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; setCurrentTextTrack: (trackId: number) => Promise<void>; setTextTrackVisibility: (isVisible: boolean) => Promise<void>; }>;
"hasCustomTextManager": boolean;
"isTextTrackVisible": boolean;
"language": string;
"logger"?: Logger;
"loop": boolean;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
"muted": boolean;
"noConnect": boolean;
"paused": boolean;
/**
* The playback rates that are available for this media.
*/
"playbackRates": number[];
"playbackReady": boolean;
"playbackStarted": boolean;
"playsinline": boolean;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"shouldRenderNativeTextTracks": boolean;
/**
* Whether to use an `audio` or `video` element to play the media.
*/
"viewType"?: ViewType;
"volume": number;
"willAttach": boolean;
}
interface VmFullscreenControl {
/**
* The name of the enter fullscreen icon to resolve from the icon library.
*/
"enterIcon": string;
/**
* The name of the exit fullscreen icon to resolve from the icon library.
*/
"exitIcon": string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isFullscreenActive": PlayerProps['isFullscreenActive'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady": PlayerProps['playbackReady'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
}
interface VmHls {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
/**
* The `hls.js` configuration.
*/
"config"?: any;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<any>; canPlay: (type: any) => Promise<boolean>; canSetPlaybackQuality: () => Promise<boolean>; setPlaybackQuality: (quality: string) => Promise<void>; setCurrentAudioTrack: (trackId: number) => Promise<void>; play: () => Promise<void | undefined>; pause: () => Promise<void | undefined>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; canSetPiP: () => Promise<boolean>; enterPiP: () => Promise<any>; exitPiP: () => Promise<any>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; setCurrentTextTrack: (trackId: number) => Promise<void>; setTextTrackVisibility: (isVisible: boolean) => Promise<void>; }>;
/**
* The URL where the `hls.js` library source can be found. If this property is used, then the `version` property is ignored.
*/
"libSrc"?: string;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
"playbackReady": boolean;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
/**
* The NPM package version of the `hls.js` library to download and use if HLS is not natively supported.
*/
"version": string;
}
interface VmIcon {
"icons": PlayerProps['icons'];
/**
* An alternative description to use for accessibility. If omitted, the name or src will be used to generate it.
*/
"label"?: string;
/**
* The name of a registered icon library.
*/
"library"?: string;
/**
* The name of the icon to draw.
*/
"name"?: string;
"redraw": () => Promise<void>;
/**
* The absolute URL of an SVG file to load.
*/
"src"?: string;
}
interface VmIconLibrary {
"icons": PlayerProps['icons'];
/**
* The name of the icon library to register. Vime provides some default libraries out of the box such as `vime`or `material`.
*/
"name"?: string;
/**
* A function that translates an icon name to a URL where the corresponding SVG file exists. The URL can be local or a CORS-enabled endpoint.
*/
"resolver"?: IconLibraryResolver;
}
interface VmLiveIndicator {
"i18n": PlayerProps['i18n'];
"isLive": PlayerProps['isLive'];
}
interface VmLoadingScreen {
/**
* Whether the loading dots are hidden or not.
*/
"hideDots": boolean;
"playbackReady": boolean;
}
interface VmMenu {
/**
* Whether the menu is open/visible.
*/
"active": boolean;
/**
* Removes focus from the menu.
*/
"blurMenu": () => Promise<void>;
/**
* Calculates the height of the settings menu based on its children.
*/
"calculateHeight": () => Promise<number>;
/**
* Reference to the controller DOM element that is responsible for opening/closing this menu.
*/
"controller"?: HTMLElement;
/**
* Focuses the menu.
*/
"focusMenu": () => Promise<void>;
/**
* Returns the currently focused menu item.
*/
"getActiveMenuItem": () => Promise<HTMLVmMenuItemElement | undefined>;
/**
* The `id` attribute of the menu.
*/
"identifier": string;
/**
* Sets the currently focused menu item.
*/
"setActiveMenuItem": (item?: HTMLVmMenuItemElement | undefined) => Promise<void>;
/**
* The direction the menu should slide in from.
*/
"slideInDirection"?: 'left' | 'right';
}
interface VmMenuItem {
/**
* This can provide additional context about the value of a menu item. For example, if the item is a radio button for a set of video qualities, the badge could describe whether the quality is UHD, HD etc. If `hint` is shown, `badge` is not shown.
*/
"badge"?: string;
/**
* Removes focus from the menu item.
*/
"blurItem": () => Promise<void>;
/**
* The name of the checkmark icon to resolve from the icon library.
*/
"checkIcon"?: string;
/**
* If this item is to behave as a radio button, then this property determines whether the radio is selected or not. Sets the `aria-checked` property.
*/
"checked"?: boolean;
/**
* If the item has a popup menu, this indicates whether the menu is open or not. Sets the `aria-expanded` property.
*/
"expanded"?: boolean;
/**
* Focuses the menu item.
*/
"focusItem": () => Promise<void>;
/**
* Returns the height of the menu item.
*/
"getHeight": () => Promise<number>;
/**
* Whether the item is displayed or not.
*/
"hidden": boolean;
/**
* This can provide additional context about some underlying state of the item. For example, if the menu item opens/closes a submenu with options, the hint could be the currently selected option. If `checked` is defined, `hint` is not shown.
*/
"hint"?: string;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The `id` attribute of the item.
*/
"identifier"?: string;
"isTouch": PlayerProps['isTouch'];
/**
* The label/title of the item.
*/
"label": string;
/**
* If the item has a popup menu, then this should be a reference to it.
*/
"menu"?: HTMLVmMenuElement;
}
interface VmMenuRadio {
/**
* This can provide additional context about the value. For example, if the option is for a set of video qualities, the badge could describe whether the quality is UHD, HD etc.
*/
"badge"?: string;
/**
* The URL to an SVG element or fragment to load.
*/
"checkIcon"?: string;
/**
* Whether the radio item is selected or not.
*/
"checked": boolean;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The title of the radio item displayed to the user.
*/
"label": string;
/**
* The value associated with this radio item.
*/
"value": string;
}
interface VmMenuRadioGroup {
/**
* The current value selected for this group.
*/
"value"?: string;
}
interface VmMuteControl {
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
/**
* The name of the high volume icon to resolve from the icon library.
*/
"highVolumeIcon": string;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The name of the low volume icon to resolve from the icon library.
*/
"lowVolumeIcon": string;
"muted": PlayerProps['muted'];
/**
* The name of the muted volume icon to resolve from the icon library.
*/
"mutedIcon": string;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
"volume": PlayerProps['volume'];
}
interface VmPipControl {
/**
* The name of the enter pip icon to resolve from the icon library.
*/
"enterIcon": string;
/**
* The name of the exit pip icon to resolve from the icon library.
*/
"exitIcon": string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isPiPActive": PlayerProps['isPiPActive'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady": PlayerProps['playbackReady'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
}
interface VmPlaybackControl {
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The name of the pause icon to resolve from the icon library.
*/
"pauseIcon": string;
"paused": PlayerProps['paused'];
/**
* The name of the play icon to resolve from the icon library.
*/
"playIcon": string;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
}
interface VmPlayer {
/**
* The aspect ratio of the player expressed as `width:height` (`16:9`). This is only applied if the `viewType` is `video` and the player is not in fullscreen mode.
* @inheritDoc
*/
"aspectRatio": string;
/**
* The audio tracks associated with the current media.
* @inheritDoc
* @readonly
*/
"audioTracks": never[];
/**
* Whether the player should automatically pause when another Vime player starts/resumes playback.
* @inheritDoc
*/
"autopause": boolean;
/**
* Whether playback should automatically begin playing once the media is ready to do so. This will only work if the browsers `autoplay` policies have been satisfied. It'll generally work if the player is muted, or the user frequently interacts with your site. You can check if it's possible to autoplay via the `canAutoplay()` or `canMutedAutoplay()` methods. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"autoplay": boolean;
/**
* The length of the media in seconds that has been downloaded by the browser.
* @inheritDoc
* @readonly
*/
"buffered": number;
/**
* Whether playback has temporarily stopped because of a lack of temporary data.
* @inheritDoc
* @readonly
*/
"buffering": boolean;
"callAdapter": (method: keyof MediaProviderAdapter, value?: any) => Promise<any>;
/**
* Determines whether the player can start playback of the current media automatically.
* @inheritDoc
*/
"canAutoplay": () => Promise<boolean>;
/**
* Determines whether the player can start playback of the current media automatically given the player is muted.
* @inheritDoc
*/
"canMutedAutoplay": () => Promise<boolean>;
/**
* Determines whether the current provider recognizes, and can play the given type.
* @inheritDoc
*/
"canPlay": (type: string) => Promise<boolean>;
/**
* Returns whether the current providers allows changing the audio track.
* @inheritDoc
*/
"canSetAudioTrack": () => Promise<boolean>;
/**
* Returns whether the native browser fullscreen API is available, or the current provider can toggle fullscreen mode. This does not mean that the operation is guaranteed to be successful, only that it can be attempted.
* @inheritDoc
*/
"canSetFullscreen": () => Promise<boolean>;
/**
* Returns whether the current provider exposes an API for entering and exiting picture-in-picture mode. This does not mean the operation is guaranteed to be successful, only that it can be attempted.
* @inheritDoc
*/
"canSetPiP": () => Promise<boolean>;
/**
* Returns whether the current provider allows setting the `playbackQuality` prop.
* @inheritDoc
*/
"canSetPlaybackQuality": () => Promise<boolean>;
/**
* Returns whether the current provider allows setting the `playbackRate` prop.
* @inheritDoc
*/
"canSetPlaybackRate": () => Promise<boolean>;
/**
* Returns whether the current provider allows changing the text track.
* @inheritDoc
*/
"canSetTextTrack": () => Promise<boolean>;
/**
* Returns whether the current providers allows setting the text track visibility.
* @inheritDoc
*/
"canSetTextTrackVisibility": () => Promise<boolean>;
/**
* Indicates whether a user interface should be shown for controlling the resource. Set this to `false` when you want to provide your own custom controls, and `true` if you want the current provider to supply its own default controls. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"controls": boolean;
/**
* Gets the index of the currently active audio track. Defaults to `-1` to when the default audio track is used. If you'd like to set it than see the `setCurrentAudioTrack` method.
* @inheritDoc
* @readonly
*/
"currentAudioTrack": number;
/**
* The absolute URL of the poster for the current media resource. Defaults to `undefined` if no media/poster has been loaded.
* @inheritDoc
* @readonly
*/
"currentPoster"?: string;
/**
* The current provider name whose responsible for loading and playing media. Defaults to `undefined` when no provider has been loaded.
* @inheritDoc
* @readonly
*/
"currentProvider"?: Provider;
/**
* The absolute URL of the media resource that has been chosen. Defaults to `undefined` if no media has been loaded.
* @inheritDoc
* @readonly
*/
"currentSrc"?: string;
/**
* Gets the index of the currently active text track. Defaults to `-1` to when all text tracks are disabled. If you'd like to set it than see the `setCurrentTextTrack` method.
* @inheritDoc
* @readonly
*/
"currentTextTrack": number;
/**
* A `double` indicating the current playback time in seconds. Defaults to `0` if the media has not started to play and has not seeked. Setting this value seeks the media to the new time. The value can be set to a minimum of `0` and maximum of the total length of the media (indicated by the duration prop).
* @inheritDoc
*/
"currentTime": number;
/**
* Whether the player is in debug mode and should `console.x` information about its internal state.
* @inheritDoc
*/
"debug": boolean;
/**
* A `double` indicating the total playback length of the media in seconds. Defaults to `-1` if no media has been loaded. If the media is being streamed live then the duration is equal to `Infinity`.
* @inheritDoc
* @readonly
*/
"duration": number;
/**
* Requests to enter fullscreen mode, returning a `Promise` that will resolve if the request is made, or reject with a reason for failure. This method will first attempt to use the browsers native fullscreen API, and then fallback to requesting the provider to do it (if available). Do not rely on a resolved promise to determine if the player is in fullscreen or not. The only way to be certain is by listening to the `vmFullscreenChange` event. Some common reasons for failure are: the fullscreen API is not available, the request is made when `viewType` is audio, or the user has not interacted with the page yet.
* @inheritDoc
*/
"enterFullscreen": (options?: FullscreenOptions | undefined) => Promise<void>;
/**
* Request to enter picture-in-picture (PiP) mode, returning a `Promise` that will resolve if the request is made, or reject with a reason for failure. Do not rely on a resolved promise to determine if the player is in PiP mode or not. The only way to be certain is by listening to the `vmPiPChange` event. Some common reasons for failure are the same as the reasons for `enterFullscreen()`.
* @inheritDoc
*/
"enterPiP": () => Promise<void | undefined>;
/**
* Requests to exit fullscreen mode, returning a `Promise` that will resolve if the request is successful, or reject with a reason for failure. Refer to `enterFullscreen()` for more information.
* @inheritDoc
*/
"exitFullscreen": () => Promise<void>;
/**
* Request to exit picture-in-picture mode, returns a `Promise` that will resolve if the request is successful, or reject with a reason for failure. Refer to `enterPiP()` for more information.
* @inheritDoc
*/
"exitPiP": () => Promise<void | undefined>;
/**
* Extends the translation map for a given language.
* @inheritDoc
*/
"extendLanguage": (language: string, translation: Partial<Translation>) => Promise<void>;
/**
* Returns the current media provider's adapter. Shorthand for `getProvider().getAdapter()`.
*/
"getAdapter": <InternalPlayerType = any>() => Promise<MediaProviderAdapter<InternalPlayerType> | undefined>;
/**
* Returns the inner container.
*/
"getContainer": () => Promise<HTMLDivElement | undefined>;
/**
* Returns the current media provider.
* @inheritDoc
*/
"getProvider": <InternalPlayerType = any>() => Promise<AdapterHost<InternalPlayerType> | undefined>;
/**
* A dictionary of translations for the current language.
* @inheritDoc
* @readonly
*/
"i18n": Translation;
/**
* The default icon library to be used throughout the player. You can use a predefined icon library such as vime, material, remix or boxicons. If you'd like to provide your own see the `<vm-icon-library>` component. Remember to pass in the name of your icon library here.
* @inheritDoc
*/
"icons": string;
/**
* Whether the current media is of type `audio`, shorthand for `mediaType === MediaType.Audio`.
* @inheritDoc
* @readonly
*/
"isAudio": boolean;
/**
* Whether the current view is of type `audio`, shorthand for `viewType === ViewType.Audio`.
* @inheritDoc
* @readonly
*/
"isAudioView": boolean;
/**
* Whether the controls are currently visible. This is currently only supported by custom controls.
* @inheritDoc
*/
"isControlsActive": boolean;
/**
* Whether the player is currently in fullscreen mode.
* @inheritDoc
* @readonly
*/
"isFullscreenActive": boolean;
/**
* Whether the current media is being broadcast live (`duration === Infinity`).
* @inheritDoc
* @readonly
*/
"isLive": boolean;
/**
* Whether the player is in mobile mode. This is determined by parsing `window.navigator.userAgent`.
* @inheritDoc
* @readonly
*/
"isMobile": boolean;
/**
* Whether the player is currently in picture-in-picture mode.
* @inheritDoc
* @readonly
*/
"isPiPActive": boolean;
/**
* Whether the settings menu has been opened and is currently visible. This is currently only supported by custom settings.
* @inheritDoc
* @readonly
*/
"isSettingsActive": boolean;
/**
* Whether the current text tracks is visible. If you'd like to set it than see the `setTrackTrackVisibility` method.
* @inheritDoc
* @readonly
*/
"isTextTrackVisible": boolean;
/**
* Whether the player is in touch mode. This is determined by listening for mouse/touch events and toggling this value.
* @inheritDoc
* @readonly
*/
"isTouch": boolean;
/**
* Whether the current media is of type `video`, shorthand for `mediaType === MediaType.Video`.
* @inheritDoc
* @readonly
*/
"isVideo": boolean;
/**
* Whether the current view is of type `video`, shorthand for `viewType === ViewType.Video`.
* @inheritDoc
* @readonly
*/
"isVideoView": boolean;
/**
* The current language of the player. This can be any code defined via the `extendLanguage` method or the default `en`. It's recommended to use an ISO 639-1 code as that'll be used by Vime when adding new language defaults in the future.
* @inheritDoc
*/
"language": string;
/**
* The languages that are currently available. You can add new languages via the `extendLanguage` method.
* @inheritDoc
* @readonly
*/
"languages": string[];
/**
* @readonly
*/
"logger": Logger;
/**
* Whether media should automatically start playing from the beginning every time it ends.
* @inheritDoc
*/
"loop": boolean;
/**
* The title of the current media. Defaults to `undefined` if no media has been loaded.
* @inheritDoc
* @readonly
*/
"mediaTitle"?: string;
/**
* The type of media that is currently active, whether it's audio or video. Defaults to `undefined` when no media has been loaded or the type cannot be determined.
* @inheritDoc
* @readonly
*/
"mediaType"?: MediaType;
/**
* Whether the audio is muted or not.
* @inheritDoc
*/
"muted": boolean;
/**
* Pauses playback of the media.
* @inheritDoc
*/
"pause": () => Promise<void | undefined>;
/**
* Whether playback should be paused. Defaults to `true` if no media has loaded or playback has not started. Setting this to `true` will begin/resume playback.
* @inheritDoc
*/
"paused": boolean;
/**
* Begins/resumes playback of the media. If this method is called programmatically before the user has interacted with the player, the promise may be rejected subject to the browser's autoplay policies.
* @inheritDoc
*/
"play": () => Promise<void | undefined>;
/**
* Whether media playback has reached the end. In other words it'll be true if `currentTime === duration`.
* @inheritDoc
* @readonly
*/
"playbackEnded": boolean;
/**
* The media qualities available for the current media.
* @inheritDoc
* @readonly
*/
"playbackQualities": string[];
/**
* Indicates the quality of the media. The value will differ between audio and video. For audio this might be some combination of the encoding format (AAC, MP3), bitrate in kilobits per second (kbps) and sample rate in kilohertz (kHZ). For video this will be the number of vertical pixels it supports. For example, if the video has a resolution of `1920x1080` then the quality will return `1080p`. Defaults to `undefined` which you can interpret as the quality is unknown. The value can also be `Auto` for adaptive bit streams (ABR), where the provider can automatically manage the playback quality. The quality can only be set to a quality found in the `playbackQualities` prop. Some providers may not allow changing the quality, you can check if it's possible via `canSetPlaybackQuality()`.
* @inheritDoc
*/
"playbackQuality"?: string;
/**
* A `double` indicating the rate at which media is being played back. If the value is `<1` then playback is slowed down; if `>1` then playback is sped up. Defaults to `1`. The playback rate can only be set to a rate found in the `playbackRates` prop. Some providers may not allow changing the playback rate, you can check if it's possible via `canSetPlaybackRate()`.
* @inheritDoc
*/
"playbackRate": number;
/**
* The playback rates available for the current media.
* @inheritDoc
* @readonly
*/
"playbackRates": number[];
/**
* Whether media is ready for playback to begin.
* @inheritDoc
* @readonly
*/
"playbackReady": boolean;
/**
* Whether the media has initiated playback. In other words it will be true if `currentTime > 0`.
* @inheritDoc
* @readonly
*/
"playbackStarted": boolean;
/**
* Whether media is actively playing back. Defaults to `false` if no media has loaded or playback has not started.
* @inheritDoc
* @readonly
*/
"playing": boolean;
/**
* Whether the video is to be played "inline", that is within the element's playback area. Note that setting this to false does not imply that the video will always be played in fullscreen. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"playsinline": boolean;
/**
* Whether the player has loaded and is ready to be interacted with.
* @inheritDoc
* @readonly
*/
"ready": boolean;
/**
* Whether the player is in the process of seeking to a new time position.
* @inheritDoc
* @readonly
*/
"seeking": boolean;
/**
* Sets the currently active audio track given the index.
* @inheritDoc
*/
"setCurrentAudioTrack": (trackId: number) => Promise<void>;
/**
* Sets the currently active text track given the index. Set to -1 to disable all text tracks.
* @inheritDoc
*/
"setCurrentTextTrack": (trackId: number) => Promise<void>;
/**
* Sets the visibility of the currently active text track.
* @inheritDoc
*/
"setTextTrackVisibility": (isVisible: boolean) => Promise<void>;
/**
* Whether text tracks should be rendered by native player, set to `false` if using custom display.
* @inheritDoc
*/
"shouldRenderNativeTextTracks": boolean;
/**
* The text tracks associated with the current media.
* @inheritDoc
* @readonly
*/
"textTracks": never[];
/**
* This property has no role other than scoping CSS selectors.
* @inheritDoc
*/
"theme"?: string;
/**
* Contains each language and its respective translation map.
* @inheritDoc
*/
"translations": Record<string, Translation>;
/**
* The type of player view that is being used, whether it's an audio player view or video player view. Normally if the media type is of audio then the view is of type audio, but in some cases it might be desirable to show a different view type. For example, when playing audio with a poster. This is subject to the provider allowing it. Defaults to `undefined` when no media has been loaded.
* @inheritDoc
* @readonly
*/
"viewType"?: ViewType;
/**
* An `int` between `0` (silent) and `100` (loudest) indicating the audio volume.
* @inheritDoc
*/
"volume": number;
}
interface VmPoster {
"currentPoster"?: PlayerProps['currentPoster'];
"currentTime": PlayerProps['currentTime'];
/**
* How the poster image should be resized to fit the container (sets the `object-fit` property).
*/
"fit"?: 'fill' | 'contain' | 'cover' | 'scale-down' | 'none';
"isVideoView": PlayerProps['isVideoView'];
"mediaTitle"?: PlayerProps['mediaTitle'];
"playbackStarted": PlayerProps['playbackStarted'];
}
interface VmScrim {
/**
* If this prop is defined, a dark gradient that smoothly fades out without being noticed will be used instead of a set color. This prop also sets the direction in which the dark end of the gradient should start. If the direction is set to `up`, the dark end of the gradient will start at the bottom of the player and fade out to the center. If the direction is set to `down`, the gradient will start at the top of the player and fade out to the center.
*/
"gradient"?: 'up' | 'down';
"isControlsActive": PlayerProps['isControlsActive'];
"isVideoView": PlayerProps['isVideoView'];
}
interface VmScrubberControl {
/**
* Whether the timestamp in the tooltip should show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours": boolean;
"buffered": PlayerProps['buffered'];
"buffering": PlayerProps['buffering'];
"currentTime": PlayerProps['currentTime'];
"duration": PlayerProps['duration'];
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip": boolean;
"i18n": PlayerProps['i18n'];
/**
* Prevents seeking forward/backward by using the Left/Right arrow keys.
*/
"noKeyboard": boolean;
}
interface VmSettings {
/**
* Whether the settings menu is opened/closed.
*/
"active": boolean;
"isAudioView": PlayerProps['isAudioView'];
"isMobile": PlayerProps['isMobile'];
/**
* Pins the settings to the defined position inside the video player. This has no effect when the view is of type `audio` (always `bottomRight`) and on mobile devices (always bottom sheet).
*/
"pin": 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
/**
* Sets the controller responsible for opening/closing this settings menu.
*/
"setController": (controller: SettingsController) => Promise<void>;
}
interface VmSettingsControl {
/**
* Removes focus from the control.
*/
"blurControl": () => Promise<void>;
/**
* Whether the settings menu this control manages is open.
*/
"expanded": boolean;
/**
* Focuses the control.
*/
"focusControl": () => Promise<void>;
"i18n": PlayerProps['i18n'];
/**
* The name of the settings icon to resolve from the icon library.
*/
"icon": string;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The DOM `id` of the settings menu this control is responsible for opening/closing.
*/
"menu"?: string;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
}
interface VmSkeleton {
/**
* Determines which animation effect the skeleton will use.
*/
"effect": 'sheen' | 'none';
"ready": PlayerProps['ready'];
}
interface VmSlider {
/**
* A human-readable label for the purpose of the slider.
*/
"label"?: string;
/**
* The greatest permitted value.
*/
"max": number;
/**
* The lowest value in the range of permitted values.
*/
"min": number;
/**
* A number that specifies the granularity that the value must adhere to.
*/
"step": number;
/**
* The current value.
*/
"value": number;
/**
* Human-readable text alternative for the current value. Defaults to `value:max` percentage.
*/
"valueText"?: string;
}
interface VmSpinner {
"buffering": PlayerProps['buffering'];
"currentProvider"?: PlayerProps['currentProvider'];
"isVideoView": PlayerProps['isVideoView'];
"playbackReady": PlayerProps['playbackReady'];
/**
* Whether the spinner should be active when the player is booting or media is loading.
*/
"showWhenMediaLoading": boolean;
}
interface VmSubmenu {
/**
* Whether the submenu is open/closed.
*/
"active": boolean;
/**
* Returns the controller (`vm-menu-item`) for this submenu.
*/
"getController": () => Promise<HTMLVmMenuItemElement | undefined>;
/**
* Returns the height of the submenu controller.
*/
"getControllerHeight": () => Promise<number>;
/**
* Returns the menu (`vm-menu`) for this submenu.
*/
"getMenu": () => Promise<HTMLVmMenuElement | undefined>;
/**
* This can provide additional context about the current state of the submenu. For example, the hint could be the currently selected option if the submenu contains a radio group.
*/
"hint"?: string;
/**
* The title of the submenu.
*/
"label": string;
/**
* The direction the submenu should slide in from.
*/
"slideInDirection"?: 'left' | 'right';
}
interface VmTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours": boolean;
/**
* The `aria-label` property of the time.
*/
"label": string;
/**
* The length of time in seconds.
*/
"seconds": number;
}
interface VmTimeProgress {
/**
* Whether the times should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours": boolean;
/**
* The string used to separate the current time and end time.
*/
"separator": string;
}
interface VmTooltip {
/**
* Whether the tooltip is visible or not.
*/
"active": boolean;
/**
* Determines if the tooltip should grow according to its contents to the left/right. By default content grows outwards from the center.
*/
"direction"?: TooltipDirection;
/**
* Whether the tooltip is displayed or not.
*/
"hidden": boolean;
"isMobile": PlayerProps['isMobile'];
"isTouch": PlayerProps['isTouch'];
/**
* Determines if the tooltip appears on top/bottom of it's parent.
*/
"position": TooltipPosition;
}
interface VmUi {
"isFullscreenActive": PlayerProps['isFullscreenActive'];
"isVideoView": PlayerProps['isVideoView'];
"playsinline": PlayerProps['playsinline'];
}
interface VmVideo {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLMediaElement>; play: () => Promise<void | undefined>; pause: () => Promise<void | undefined>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; canSetPiP: () => Promise<boolean>; enterPiP: () => Promise<any>; exitPiP: () => Promise<any>; canSetFullscreen: () => Promise<boolean>; enterFullscreen: () => Promise<void>; exitFullscreen: () => Promise<void>; setCurrentTextTrack: (trackId: number) => Promise<void>; setTextTrackVisibility: (isVisible: boolean) => Promise<void>; }>;
"hasCustomTextManager": boolean;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"willAttach": boolean;
}
interface VmVimeo {
"aspectRatio": string;
"autoplay": boolean;
/**
* Whether to display the video owner's name.
*/
"byline": boolean;
/**
* The hexadecimal color value of the playback controls. The embed settings of the video might override this value.
*/
"color"?: string;
"controls": boolean;
/**
* Whether cookies should be enabled on the embed.
*/
"cookies": boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLVmEmbedElement>; play: () => Promise<void>; pause: () => Promise<void>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; }>;
"language": string;
"logger"?: Logger;
"loop": boolean;
"muted": boolean;
/**
* Turns off automatically determining the aspect ratio of the current video.
*/
"noAutoAspectRatio": boolean;
"playsinline": boolean;
/**
* Whether to display the video owner's portrait.
*/
"portrait": boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* The Vimeo resource ID of the video to load.
*/
"videoId": string;
}
interface VmVolumeControl {
/**
* Whether the tooltip should be hidden.
*/
"hideTooltip": boolean;
/**
* The name of the high volume icon to resolve from the icon library.
*/
"highVolumeIcon": string;
"i18n": PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isMobile": PlayerProps['isMobile'];
/**
* The name of the low volume icon to resolve from the icon library.
*/
"lowVolumeIcon": string;
/**
* A pipe (`/`) separated string of JS keyboard keys, that when caught in a `keydown` event, will toggle the muted state of the player.
*/
"muteKeys"?: string;
"muted": PlayerProps['muted'];
/**
* The name of the muted volume icon to resolve from the icon library.
*/
"mutedIcon": string;
/**
* Prevents the volume being changed using the Up/Down arrow keys.
*/
"noKeyboard": boolean;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection": TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition": TooltipPosition;
"volume": PlayerProps['volume'];
}
interface VmYoutube {
"autoplay": boolean;
"controls": boolean;
/**
* Whether cookies should be enabled on the embed.
*/
"cookies": boolean;
"getAdapter": () => Promise<{ getInternalPlayer: () => Promise<HTMLVmEmbedElement>; play: () => Promise<void>; pause: () => Promise<void>; canPlay: (type: any) => Promise<boolean>; setCurrentTime: (time: number) => Promise<void>; setMuted: (muted: boolean) => Promise<void>; setVolume: (volume: number) => Promise<void>; canSetPlaybackRate: () => Promise<boolean>; setPlaybackRate: (rate: number) => Promise<void>; }>;
"language": string;
"logger"?: Logger;
"loop": boolean;
"muted": boolean;
"playsinline": boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* Whether the fullscreen control should be shown.
*/
"showFullscreenControl": boolean;
/**
* The YouTube resource ID of the video to load.
*/
"videoId": string;
}
}
declare global {
interface HTMLVmAudioElement extends Components.VmAudio, HTMLStencilElement {
}
var HTMLVmAudioElement: {
prototype: HTMLVmAudioElement;
new (): HTMLVmAudioElement;
};
interface HTMLVmCaptionControlElement extends Components.VmCaptionControl, HTMLStencilElement {
}
var HTMLVmCaptionControlElement: {
prototype: HTMLVmCaptionControlElement;
new (): HTMLVmCaptionControlElement;
};
interface HTMLVmCaptionsElement extends Components.VmCaptions, HTMLStencilElement {
}
var HTMLVmCaptionsElement: {
prototype: HTMLVmCaptionsElement;
new (): HTMLVmCaptionsElement;
};
interface HTMLVmClickToPlayElement extends Components.VmClickToPlay, HTMLStencilElement {
}
var HTMLVmClickToPlayElement: {
prototype: HTMLVmClickToPlayElement;
new (): HTMLVmClickToPlayElement;
};
interface HTMLVmControlElement extends Components.VmControl, HTMLStencilElement {
}
var HTMLVmControlElement: {
prototype: HTMLVmControlElement;
new (): HTMLVmControlElement;
};
interface HTMLVmControlGroupElement extends Components.VmControlGroup, HTMLStencilElement {
}
var HTMLVmControlGroupElement: {
prototype: HTMLVmControlGroupElement;
new (): HTMLVmControlGroupElement;
};
interface HTMLVmControlSpacerElement extends Components.VmControlSpacer, HTMLStencilElement {
}
var HTMLVmControlSpacerElement: {
prototype: HTMLVmControlSpacerElement;
new (): HTMLVmControlSpacerElement;
};
interface HTMLVmControlsElement extends Components.VmControls, HTMLStencilElement {
}
var HTMLVmControlsElement: {
prototype: HTMLVmControlsElement;
new (): HTMLVmControlsElement;
};
interface HTMLVmCurrentTimeElement extends Components.VmCurrentTime, HTMLStencilElement {
}
var HTMLVmCurrentTimeElement: {
prototype: HTMLVmCurrentTimeElement;
new (): HTMLVmCurrentTimeElement;
};
interface HTMLVmDailymotionElement extends Components.VmDailymotion, HTMLStencilElement {
}
var HTMLVmDailymotionElement: {
prototype: HTMLVmDailymotionElement;
new (): HTMLVmDailymotionElement;
};
interface HTMLVmDashElement extends Components.VmDash, HTMLStencilElement {
}
var HTMLVmDashElement: {
prototype: HTMLVmDashElement;
new (): HTMLVmDashElement;
};
interface HTMLVmDblClickFullscreenElement extends Components.VmDblClickFullscreen, HTMLStencilElement {
}
var HTMLVmDblClickFullscreenElement: {
prototype: HTMLVmDblClickFullscreenElement;
new (): HTMLVmDblClickFullscreenElement;
};
interface HTMLVmDefaultControlsElement extends Components.VmDefaultControls, HTMLStencilElement {
}
var HTMLVmDefaultControlsElement: {
prototype: HTMLVmDefaultControlsElement;
new (): HTMLVmDefaultControlsElement;
};
interface HTMLVmDefaultSettingsElement extends Components.VmDefaultSettings, HTMLStencilElement {
}
var HTMLVmDefaultSettingsElement: {
prototype: HTMLVmDefaultSettingsElement;
new (): HTMLVmDefaultSettingsElement;
};
interface HTMLVmDefaultUiElement extends Components.VmDefaultUi, HTMLStencilElement {
}
var HTMLVmDefaultUiElement: {
prototype: HTMLVmDefaultUiElement;
new (): HTMLVmDefaultUiElement;
};
interface HTMLVmEmbedElement extends Components.VmEmbed, HTMLStencilElement {
}
var HTMLVmEmbedElement: {
prototype: HTMLVmEmbedElement;
new (): HTMLVmEmbedElement;
};
interface HTMLVmEndTimeElement extends Components.VmEndTime, HTMLStencilElement {
}
var HTMLVmEndTimeElement: {
prototype: HTMLVmEndTimeElement;
new (): HTMLVmEndTimeElement;
};
interface HTMLVmFileElement extends Components.VmFile, HTMLStencilElement {
}
var HTMLVmFileElement: {
prototype: HTMLVmFileElement;
new (): HTMLVmFileElement;
};
interface HTMLVmFullscreenControlElement extends Components.VmFullscreenControl, HTMLStencilElement {
}
var HTMLVmFullscreenControlElement: {
prototype: HTMLVmFullscreenControlElement;
new (): HTMLVmFullscreenControlElement;
};
interface HTMLVmHlsElement extends Components.VmHls, HTMLStencilElement {
}
var HTMLVmHlsElement: {
prototype: HTMLVmHlsElement;
new (): HTMLVmHlsElement;
};
interface HTMLVmIconElement extends Components.VmIcon, HTMLStencilElement {
}
var HTMLVmIconElement: {
prototype: HTMLVmIconElement;
new (): HTMLVmIconElement;
};
interface HTMLVmIconLibraryElement extends Components.VmIconLibrary, HTMLStencilElement {
}
var HTMLVmIconLibraryElement: {
prototype: HTMLVmIconLibraryElement;
new (): HTMLVmIconLibraryElement;
};
interface HTMLVmLiveIndicatorElement extends Components.VmLiveIndicator, HTMLStencilElement {
}
var HTMLVmLiveIndicatorElement: {
prototype: HTMLVmLiveIndicatorElement;
new (): HTMLVmLiveIndicatorElement;
};
interface HTMLVmLoadingScreenElement extends Components.VmLoadingScreen, HTMLStencilElement {
}
var HTMLVmLoadingScreenElement: {
prototype: HTMLVmLoadingScreenElement;
new (): HTMLVmLoadingScreenElement;
};
interface HTMLVmMenuElement extends Components.VmMenu, HTMLStencilElement {
}
var HTMLVmMenuElement: {
prototype: HTMLVmMenuElement;
new (): HTMLVmMenuElement;
};
interface HTMLVmMenuItemElement extends Components.VmMenuItem, HTMLStencilElement {
}
var HTMLVmMenuItemElement: {
prototype: HTMLVmMenuItemElement;
new (): HTMLVmMenuItemElement;
};
interface HTMLVmMenuRadioElement extends Components.VmMenuRadio, HTMLStencilElement {
}
var HTMLVmMenuRadioElement: {
prototype: HTMLVmMenuRadioElement;
new (): HTMLVmMenuRadioElement;
};
interface HTMLVmMenuRadioGroupElement extends Components.VmMenuRadioGroup, HTMLStencilElement {
}
var HTMLVmMenuRadioGroupElement: {
prototype: HTMLVmMenuRadioGroupElement;
new (): HTMLVmMenuRadioGroupElement;
};
interface HTMLVmMuteControlElement extends Components.VmMuteControl, HTMLStencilElement {
}
var HTMLVmMuteControlElement: {
prototype: HTMLVmMuteControlElement;
new (): HTMLVmMuteControlElement;
};
interface HTMLVmPipControlElement extends Components.VmPipControl, HTMLStencilElement {
}
var HTMLVmPipControlElement: {
prototype: HTMLVmPipControlElement;
new (): HTMLVmPipControlElement;
};
interface HTMLVmPlaybackControlElement extends Components.VmPlaybackControl, HTMLStencilElement {
}
var HTMLVmPlaybackControlElement: {
prototype: HTMLVmPlaybackControlElement;
new (): HTMLVmPlaybackControlElement;
};
interface HTMLVmPlayerElement extends Components.VmPlayer, HTMLStencilElement {
}
var HTMLVmPlayerElement: {
prototype: HTMLVmPlayerElement;
new (): HTMLVmPlayerElement;
};
interface HTMLVmPosterElement extends Components.VmPoster, HTMLStencilElement {
}
var HTMLVmPosterElement: {
prototype: HTMLVmPosterElement;
new (): HTMLVmPosterElement;
};
interface HTMLVmScrimElement extends Components.VmScrim, HTMLStencilElement {
}
var HTMLVmScrimElement: {
prototype: HTMLVmScrimElement;
new (): HTMLVmScrimElement;
};
interface HTMLVmScrubberControlElement extends Components.VmScrubberControl, HTMLStencilElement {
}
var HTMLVmScrubberControlElement: {
prototype: HTMLVmScrubberControlElement;
new (): HTMLVmScrubberControlElement;
};
interface HTMLVmSettingsElement extends Components.VmSettings, HTMLStencilElement {
}
var HTMLVmSettingsElement: {
prototype: HTMLVmSettingsElement;
new (): HTMLVmSettingsElement;
};
interface HTMLVmSettingsControlElement extends Components.VmSettingsControl, HTMLStencilElement {
}
var HTMLVmSettingsControlElement: {
prototype: HTMLVmSettingsControlElement;
new (): HTMLVmSettingsControlElement;
};
interface HTMLVmSkeletonElement extends Components.VmSkeleton, HTMLStencilElement {
}
var HTMLVmSkeletonElement: {
prototype: HTMLVmSkeletonElement;
new (): HTMLVmSkeletonElement;
};
interface HTMLVmSliderElement extends Components.VmSlider, HTMLStencilElement {
}
var HTMLVmSliderElement: {
prototype: HTMLVmSliderElement;
new (): HTMLVmSliderElement;
};
interface HTMLVmSpinnerElement extends Components.VmSpinner, HTMLStencilElement {
}
var HTMLVmSpinnerElement: {
prototype: HTMLVmSpinnerElement;
new (): HTMLVmSpinnerElement;
};
interface HTMLVmSubmenuElement extends Components.VmSubmenu, HTMLStencilElement {
}
var HTMLVmSubmenuElement: {
prototype: HTMLVmSubmenuElement;
new (): HTMLVmSubmenuElement;
};
interface HTMLVmTimeElement extends Components.VmTime, HTMLStencilElement {
}
var HTMLVmTimeElement: {
prototype: HTMLVmTimeElement;
new (): HTMLVmTimeElement;
};
interface HTMLVmTimeProgressElement extends Components.VmTimeProgress, HTMLStencilElement {
}
var HTMLVmTimeProgressElement: {
prototype: HTMLVmTimeProgressElement;
new (): HTMLVmTimeProgressElement;
};
interface HTMLVmTooltipElement extends Components.VmTooltip, HTMLStencilElement {
}
var HTMLVmTooltipElement: {
prototype: HTMLVmTooltipElement;
new (): HTMLVmTooltipElement;
};
interface HTMLVmUiElement extends Components.VmUi, HTMLStencilElement {
}
var HTMLVmUiElement: {
prototype: HTMLVmUiElement;
new (): HTMLVmUiElement;
};
interface HTMLVmVideoElement extends Components.VmVideo, HTMLStencilElement {
}
var HTMLVmVideoElement: {
prototype: HTMLVmVideoElement;
new (): HTMLVmVideoElement;
};
interface HTMLVmVimeoElement extends Components.VmVimeo, HTMLStencilElement {
}
var HTMLVmVimeoElement: {
prototype: HTMLVmVimeoElement;
new (): HTMLVmVimeoElement;
};
interface HTMLVmVolumeControlElement extends Components.VmVolumeControl, HTMLStencilElement {
}
var HTMLVmVolumeControlElement: {
prototype: HTMLVmVolumeControlElement;
new (): HTMLVmVolumeControlElement;
};
interface HTMLVmYoutubeElement extends Components.VmYoutube, HTMLStencilElement {
}
var HTMLVmYoutubeElement: {
prototype: HTMLVmYoutubeElement;
new (): HTMLVmYoutubeElement;
};
interface HTMLElementTagNameMap {
"vm-audio": HTMLVmAudioElement;
"vm-caption-control": HTMLVmCaptionControlElement;
"vm-captions": HTMLVmCaptionsElement;
"vm-click-to-play": HTMLVmClickToPlayElement;
"vm-control": HTMLVmControlElement;
"vm-control-group": HTMLVmControlGroupElement;
"vm-control-spacer": HTMLVmControlSpacerElement;
"vm-controls": HTMLVmControlsElement;
"vm-current-time": HTMLVmCurrentTimeElement;
"vm-dailymotion": HTMLVmDailymotionElement;
"vm-dash": HTMLVmDashElement;
"vm-dbl-click-fullscreen": HTMLVmDblClickFullscreenElement;
"vm-default-controls": HTMLVmDefaultControlsElement;
"vm-default-settings": HTMLVmDefaultSettingsElement;
"vm-default-ui": HTMLVmDefaultUiElement;
"vm-embed": HTMLVmEmbedElement;
"vm-end-time": HTMLVmEndTimeElement;
"vm-file": HTMLVmFileElement;
"vm-fullscreen-control": HTMLVmFullscreenControlElement;
"vm-hls": HTMLVmHlsElement;
"vm-icon": HTMLVmIconElement;
"vm-icon-library": HTMLVmIconLibraryElement;
"vm-live-indicator": HTMLVmLiveIndicatorElement;
"vm-loading-screen": HTMLVmLoadingScreenElement;
"vm-menu": HTMLVmMenuElement;
"vm-menu-item": HTMLVmMenuItemElement;
"vm-menu-radio": HTMLVmMenuRadioElement;
"vm-menu-radio-group": HTMLVmMenuRadioGroupElement;
"vm-mute-control": HTMLVmMuteControlElement;
"vm-pip-control": HTMLVmPipControlElement;
"vm-playback-control": HTMLVmPlaybackControlElement;
"vm-player": HTMLVmPlayerElement;
"vm-poster": HTMLVmPosterElement;
"vm-scrim": HTMLVmScrimElement;
"vm-scrubber-control": HTMLVmScrubberControlElement;
"vm-settings": HTMLVmSettingsElement;
"vm-settings-control": HTMLVmSettingsControlElement;
"vm-skeleton": HTMLVmSkeletonElement;
"vm-slider": HTMLVmSliderElement;
"vm-spinner": HTMLVmSpinnerElement;
"vm-submenu": HTMLVmSubmenuElement;
"vm-time": HTMLVmTimeElement;
"vm-time-progress": HTMLVmTimeProgressElement;
"vm-tooltip": HTMLVmTooltipElement;
"vm-ui": HTMLVmUiElement;
"vm-video": HTMLVmVideoElement;
"vm-vimeo": HTMLVmVimeoElement;
"vm-volume-control": HTMLVmVolumeControlElement;
"vm-youtube": HTMLVmYoutubeElement;
}
}
declare namespace LocalJSX {
interface VmAudio {
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"willAttach"?: boolean;
}
interface VmCaptionControl {
/**
* The URL to an SVG element or fragment to load.
*/
"hideIcon"?: string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isTextTrackVisible"?: PlayerProps['isTextTrackVisible'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady"?: PlayerProps['playbackReady'];
/**
* The URL to an SVG element or fragment to load.
*/
"showIcon"?: string;
"textTracks"?: PlayerProps['textTracks'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
}
interface VmCaptions {
"currentTextTrack"?: PlayerProps['currentTextTrack'];
/**
* Whether the captions should be visible or not.
*/
"hidden"?: boolean;
"isControlsActive"?: PlayerProps['isControlsActive'];
"isTextTrackVisible"?: PlayerProps['isTextTrackVisible'];
"isVideoView"?: PlayerProps['isVideoView'];
"playbackStarted"?: PlayerProps['playbackStarted'];
"textTracks"?: PlayerProps['textTracks'];
}
interface VmClickToPlay {
"isMobile"?: PlayerProps['isMobile'];
"isVideoView"?: PlayerProps['isVideoView'];
"paused"?: PlayerProps['paused'];
/**
* By default this is disabled on mobile to not interfere with playback, set this to `true` to enable it.
*/
"useOnMobile"?: boolean;
}
interface VmControl {
/**
* If the control has a popup menu, this indicates whether the menu is open or not. Sets the `aria-expanded` property.
*/
"expanded"?: boolean;
/**
* Whether the control should be displayed or not.
*/
"hidden"?: boolean;
/**
* The `id` attribute of the control.
*/
"identifier"?: string;
"isTouch"?: PlayerProps['isTouch'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The `aria-label` property of the control.
*/
"label": string;
/**
* If the control has a popup menu, then this should be the `id` of said menu. Sets the `aria-controls` property.
*/
"menu"?: string;
/**
* Emitted when the control loses focus.
*/
"onVmBlur"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the control receives focus.
*/
"onVmFocus"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the user is interacting with the control by focusing, touching or hovering on it.
*/
"onVmInteractionChange"?: (event: CustomEvent<boolean>) => void;
/**
* If the control is a toggle, this indicated whether the control is in a "pressed" state or not. Sets the `aria-pressed` property.
*/
"pressed"?: boolean;
}
interface VmControlGroup {
/**
* Determines where to add spacing/margin. The amount of spacing is determined by the CSS variable `--control-group-spacing`.
*/
"space"?: 'top' | 'bottom' | 'both' | 'none';
}
interface VmControlSpacer {
}
interface VmControls {
/**
* The length in milliseconds that the controls are active for before fading out. Audio players are not effected by this prop.
*/
"activeDuration"?: number;
/**
* Sets the `align-items` flex property that aligns the individual controls on the cross-axis.
*/
"align"?: 'start' | 'center' | 'end';
/**
* Sets the `flex-direction` property that manages the direction in which the controls are layed out.
*/
"direction"?: 'row' | 'column';
/**
* Whether the controls container should be 100% height. This has no effect if the view is of type `audio`.
*/
"fullHeight"?: boolean;
/**
* Whether the controls container should be 100% width. This has no effect if the view is of type `audio`.
*/
"fullWidth"?: boolean;
/**
* Whether the controls are visible or not.
*/
"hidden"?: boolean;
/**
* Whether the controls should hide when the mouse leaves the player. Audio players are not effected by this prop.
*/
"hideOnMouseLeave"?: boolean;
/**
* Whether the controls should show/hide when paused. Audio players are not effected by this prop.
*/
"hideWhenPaused"?: boolean;
"isAudioView"?: PlayerProps['isAudioView'];
"isControlsActive"?: PlayerProps['isControlsActive'];
"isSettingsActive"?: PlayerProps['isSettingsActive'];
/**
* Sets the `justify-content` flex property that aligns the individual controls on the main-axis.
*/
"justify"?: | 'start'
| 'center'
| 'end'
| 'space-around'
| 'space-between'
| 'space-evenly';
"paused"?: PlayerProps['paused'];
/**
* Pins the controls to the defined position inside the video player. This has no effect when the view is of type `audio`.
*/
"pin"?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'center';
"playbackReady"?: PlayerProps['playbackReady'];
"playbackStarted"?: PlayerProps['playbackStarted'];
/**
* Whether the controls should wait for playback to start before being shown. Audio players are not effected by this prop.
*/
"waitForPlaybackStart"?: boolean;
}
interface VmCurrentTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours"?: boolean;
"currentTime"?: PlayerProps['currentTime'];
"i18n"?: PlayerProps['i18n'];
}
interface VmDailymotion {
"autoplay"?: boolean;
/**
* Change the default highlight color used in the controls (hex value without the leading #). Color set in the Partner HQ will override this prop.
*/
"color"?: string;
"controls"?: boolean;
"language"?: string;
"logger"?: Logger;
"loop"?: boolean;
"muted"?: boolean;
/**
* Emitted when an error has occurred.
*/
"onVmError"?: (event: CustomEvent<string | undefined>) => void;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
"playsinline"?: boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* Whether to automatically play the next video in the queue.
*/
"shouldAutoplayQueue"?: boolean;
/**
* Whether to display the Dailymotion logo.
*/
"showDailymotionLogo"?: boolean;
/**
* Whether to show buttons for sharing the video.
*/
"showShareButtons"?: boolean;
/**
* Whether to show the 'Up Next' queue.
*/
"showUpNextQueue"?: boolean;
/**
* Whether to show video information (title and owner) on the start screen.
*/
"showVideoInfo"?: boolean;
/**
* Forwards your syndication key to the player.
*/
"syndication"?: string;
/**
* The Dailymotion resource ID of the video to load.
*/
"videoId": string;
}
interface VmDash {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
"autoplay"?: boolean;
/**
* The `dashjs` configuration.
*/
"config"?: Record<string, any>;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
"currentTextTrack"?: number;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
/**
* Are text tracks enabled by default.
*/
"enableTextTracksByDefault"?: boolean;
"isTextTrackVisible"?: boolean;
/**
* The URL where the `dashjs` library source can be found. If this property is used, then the `version` property is ignored.
*/
"libSrc"?: string;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* Emitted when an error has occurred.
*/
"onVmError"?: (event: CustomEvent<any>) => void;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"shouldRenderNativeTextTracks"?: boolean;
/**
* The URL of the `manifest.mpd` file to use.
*/
"src": string;
/**
* The NPM package version of the `dashjs` library to download and use.
*/
"version"?: string;
}
interface VmDblClickFullscreen {
"isFullscreenActive"?: PlayerProps['isFullscreenActive'];
"isMobile"?: PlayerProps['isMobile'];
"isVideoView"?: PlayerProps['isVideoView'];
"playbackReady"?: PlayerProps['playbackReady'];
/**
* By default this is disabled on mobile to not interfere with playback, set this to `true` to enable it.
*/
"useOnMobile"?: boolean;
}
interface VmDefaultControls {
/**
* The length in milliseconds that the controls are active for before fading out. Audio players are not effected by this prop.
*/
"activeDuration"?: number;
/**
* Whether the controls should hide when the mouse leaves the player. Audio players are not effected by this prop.
*/
"hideOnMouseLeave"?: boolean;
/**
* Whether the controls should show/hide when paused. Audio players are not effected by this prop.
*/
"hideWhenPaused"?: boolean;
"isAudioView"?: PlayerProps['isAudioView'];
"isLive"?: PlayerProps['isLive'];
"isMobile"?: PlayerProps['isMobile'];
"isVideoView"?: PlayerProps['isVideoView'];
"theme"?: PlayerProps['theme'];
/**
* Whether the controls should wait for playback to start before being shown. Audio players are not effected by this prop.
*/
"waitForPlaybackStart"?: boolean;
}
interface VmDefaultSettings {
"audioTracks"?: PlayerProps['audioTracks'];
"currentAudioTrack"?: number;
"currentTextTrack"?: number;
"i18n"?: PlayerProps['i18n'];
"isTextTrackVisible"?: boolean;
"isVideoView"?: PlayerProps['isAudioView'];
/**
* Pins the settings to the defined position inside the video player. This has no effect when the view is of type `audio`, it will always be `bottomRight`.
*/
"pin"?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
"playbackQualities"?: PlayerProps['playbackQualities'];
"playbackQuality"?: PlayerProps['playbackQuality'];
"playbackRate"?: PlayerProps['playbackRate'];
"playbackRates"?: PlayerProps['playbackRates'];
"playbackReady"?: PlayerProps['playbackReady'];
"textTracks"?: PlayerProps['textTracks'];
}
interface VmDefaultUi {
/**
* Whether the custom captions UI should not be loaded.
*/
"noCaptions"?: boolean;
/**
* Whether clicking the player should not toggle playback.
*/
"noClickToPlay"?: boolean;
/**
* Whether the custom default controls should not be loaded.
*/
"noControls"?: boolean;
/**
* Whether double clicking the player should not toggle fullscreen mode.
*/
"noDblClickFullscreen"?: boolean;
/**
* Whether the default loading screen should not be loaded.
*/
"noLoadingScreen"?: boolean;
/**
* Whether the custom poster UI should not be loaded.
*/
"noPoster"?: boolean;
/**
* Whether the custom default settings menu should not be loaded.
*/
"noSettings"?: boolean;
/**
* Whether the custom spinner UI should not be loaded.
*/
"noSpinner"?: boolean;
}
interface VmEmbed {
/**
* A function which accepts the raw message received from the embedded media player via `postMessage` and converts it into a POJO.
*/
"decoder"?: (
data: string,
) => Params | undefined;
/**
* A URL that will load the external player and media (Eg: https://www.youtube.com/embed/DyTCOwB0DVw).
*/
"embedSrc"?: string;
/**
* The title of the current media so it can be set on the inner `iframe` for screen readers.
*/
"mediaTitle"?: string;
/**
* Emitted when the embedded player and any new media has loaded.
*/
"onVmEmbedLoaded"?: (event: CustomEvent<void>) => void;
/**
* Emitted when a new message is received from the embedded player via `postMessage`.
*/
"onVmEmbedMessage"?: (event: CustomEvent<any>) => void;
/**
* Emitted when the `embedSrc` or `params` props change. The payload contains the `params` serialized into a query string and appended to `embedSrc`.
*/
"onVmEmbedSrcChange"?: (event: CustomEvent<string>) => void;
/**
* Where the src request had originated from without any path information.
*/
"origin"?: string;
/**
* The parameters to pass to the embedded player which are appended to the `embedSrc` prop. These can be passed in as a query string or object.
*/
"params"?: string | Params;
/**
* A collection of URLs to that the browser should immediately start establishing a connection with.
*/
"preconnections"?: string[];
}
interface VmEndTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours"?: boolean;
"duration"?: PlayerProps['duration'];
"i18n"?: PlayerProps['i18n'];
}
interface VmFile {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
"autoplay"?: boolean;
"controls"?: boolean;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
"currentTextTrack"?: number;
"currentTime"?: number;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"hasCustomTextManager"?: boolean;
"isTextTrackVisible"?: boolean;
"language"?: string;
"logger"?: Logger;
"loop"?: boolean;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
"muted"?: boolean;
"noConnect"?: boolean;
/**
* Emitted when an error has occurred.
*/
"onVmError"?: (event: CustomEvent<any>) => void;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the underlying media element changes.
*/
"onVmMediaElChange"?: (event: CustomEvent<HTMLAudioElement | HTMLVideoElement | undefined>) => void;
/**
* Emitted when the child `<source />` elements are modified.
*/
"onVmSrcSetChange"?: (event: CustomEvent<MediaResource[]>) => void;
"paused"?: boolean;
/**
* The playback rates that are available for this media.
*/
"playbackRates"?: number[];
"playbackReady"?: boolean;
"playbackStarted"?: boolean;
"playsinline"?: boolean;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"shouldRenderNativeTextTracks"?: boolean;
/**
* Whether to use an `audio` or `video` element to play the media.
*/
"viewType"?: ViewType;
"volume"?: number;
"willAttach"?: boolean;
}
interface VmFullscreenControl {
/**
* The name of the enter fullscreen icon to resolve from the icon library.
*/
"enterIcon"?: string;
/**
* The name of the exit fullscreen icon to resolve from the icon library.
*/
"exitIcon"?: string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isFullscreenActive"?: PlayerProps['isFullscreenActive'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady"?: PlayerProps['playbackReady'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
}
interface VmHls {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
/**
* The `hls.js` configuration.
*/
"config"?: any;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
/**
* The URL where the `hls.js` library source can be found. If this property is used, then the `version` property is ignored.
*/
"libSrc"?: string;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* Emitted when an error has occurred.
*/
"onVmError"?: (event: CustomEvent<any>) => void;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
"playbackReady"?: boolean;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
/**
* The NPM package version of the `hls.js` library to download and use if HLS is not natively supported.
*/
"version"?: string;
}
interface VmIcon {
"icons"?: PlayerProps['icons'];
/**
* An alternative description to use for accessibility. If omitted, the name or src will be used to generate it.
*/
"label"?: string;
/**
* The name of a registered icon library.
*/
"library"?: string;
/**
* The name of the icon to draw.
*/
"name"?: string;
/**
* Emitted when the icon failed to load.
*/
"onVmError"?: (event: CustomEvent<{ status?: number }>) => void;
/**
* Emitted when the icon has loaded.
*/
"onVmLoad"?: (event: CustomEvent<void>) => void;
/**
* The absolute URL of an SVG file to load.
*/
"src"?: string;
}
interface VmIconLibrary {
"icons"?: PlayerProps['icons'];
/**
* The name of the icon library to register. Vime provides some default libraries out of the box such as `vime`or `material`.
*/
"name"?: string;
/**
* A function that translates an icon name to a URL where the corresponding SVG file exists. The URL can be local or a CORS-enabled endpoint.
*/
"resolver"?: IconLibraryResolver;
}
interface VmLiveIndicator {
"i18n"?: PlayerProps['i18n'];
"isLive"?: PlayerProps['isLive'];
}
interface VmLoadingScreen {
/**
* Whether the loading dots are hidden or not.
*/
"hideDots"?: boolean;
"playbackReady"?: boolean;
}
interface VmMenu {
/**
* Whether the menu is open/visible.
*/
"active"?: boolean;
/**
* Reference to the controller DOM element that is responsible for opening/closing this menu.
*/
"controller"?: HTMLElement;
/**
* The `id` attribute of the menu.
*/
"identifier": string;
/**
* Emitted when the currently focused menu item changes.
*/
"onVmActiveMenuItemChange"?: (event: CustomEvent<HTMLVmMenuItemElement | undefined>) => void;
/**
* Emitted when the active submenu changes.
*/
"onVmActiveSubmenuChange"?: (event: CustomEvent<HTMLVmSubmenuElement | undefined>) => void;
/**
* Emitted when the menu loses focus.
*/
"onVmBlur"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the menu has closed/is not active.
*/
"onVmClose"?: (event: CustomEvent<HTMLVmMenuElement>) => void;
/**
* Emitted when the menu is focused.
*/
"onVmFocus"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the height of the menu changes.
*/
"onVmMenuHeightChange"?: (event: CustomEvent<number>) => void;
/**
* Emitted when the menu is open/active.
*/
"onVmOpen"?: (event: CustomEvent<HTMLVmMenuElement>) => void;
/**
* The direction the menu should slide in from.
*/
"slideInDirection"?: 'left' | 'right';
}
interface VmMenuItem {
/**
* This can provide additional context about the value of a menu item. For example, if the item is a radio button for a set of video qualities, the badge could describe whether the quality is UHD, HD etc. If `hint` is shown, `badge` is not shown.
*/
"badge"?: string;
/**
* The name of the checkmark icon to resolve from the icon library.
*/
"checkIcon"?: string;
/**
* If this item is to behave as a radio button, then this property determines whether the radio is selected or not. Sets the `aria-checked` property.
*/
"checked"?: boolean;
/**
* If the item has a popup menu, this indicates whether the menu is open or not. Sets the `aria-expanded` property.
*/
"expanded"?: boolean;
/**
* Whether the item is displayed or not.
*/
"hidden"?: boolean;
/**
* This can provide additional context about some underlying state of the item. For example, if the menu item opens/closes a submenu with options, the hint could be the currently selected option. If `checked` is defined, `hint` is not shown.
*/
"hint"?: string;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The `id` attribute of the item.
*/
"identifier"?: string;
"isTouch"?: PlayerProps['isTouch'];
/**
* The label/title of the item.
*/
"label": string;
/**
* If the item has a popup menu, then this should be a reference to it.
*/
"menu"?: HTMLVmMenuElement;
/**
* Emitted when the item loses focus.
*/
"onVmBlur"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the item is focused.
*/
"onVmFocus"?: (event: CustomEvent<void>) => void;
}
interface VmMenuRadio {
/**
* This can provide additional context about the value. For example, if the option is for a set of video qualities, the badge could describe whether the quality is UHD, HD etc.
*/
"badge"?: string;
/**
* The URL to an SVG element or fragment to load.
*/
"checkIcon"?: string;
/**
* Whether the radio item is selected or not.
*/
"checked"?: boolean;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The title of the radio item displayed to the user.
*/
"label": string;
/**
* Emitted when the radio button is selected.
*/
"onVmCheck"?: (event: CustomEvent<void>) => void;
/**
* The value associated with this radio item.
*/
"value": string;
}
interface VmMenuRadioGroup {
/**
* Emitted when a new radio button is selected for this group.
*/
"onVmCheck"?: (event: CustomEvent<void>) => void;
/**
* The current value selected for this group.
*/
"value"?: string;
}
interface VmMuteControl {
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
/**
* The name of the high volume icon to resolve from the icon library.
*/
"highVolumeIcon"?: string;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The name of the low volume icon to resolve from the icon library.
*/
"lowVolumeIcon"?: string;
"muted"?: PlayerProps['muted'];
/**
* The name of the muted volume icon to resolve from the icon library.
*/
"mutedIcon"?: string;
/**
* Emitted when the control loses focus.
*/
"onVmBlur"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the control receives focus.
*/
"onVmFocus"?: (event: CustomEvent<void>) => void;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
"volume"?: PlayerProps['volume'];
}
interface VmPipControl {
/**
* The name of the enter pip icon to resolve from the icon library.
*/
"enterIcon"?: string;
/**
* The name of the exit pip icon to resolve from the icon library.
*/
"exitIcon"?: string;
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isPiPActive"?: PlayerProps['isPiPActive'];
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
"playbackReady"?: PlayerProps['playbackReady'];
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
}
interface VmPlaybackControl {
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* A slash (`/`) separated string of JS keyboard keys (`KeyboardEvent.key`), that when caught in a `keydown` event, will trigger a `click` event on the control.
* @inheritdoc
*/
"keys"?: string;
/**
* The name of the pause icon to resolve from the icon library.
*/
"pauseIcon"?: string;
"paused"?: PlayerProps['paused'];
/**
* The name of the play icon to resolve from the icon library.
*/
"playIcon"?: string;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
}
interface VmPlayer {
/**
* The aspect ratio of the player expressed as `width:height` (`16:9`). This is only applied if the `viewType` is `video` and the player is not in fullscreen mode.
* @inheritDoc
*/
"aspectRatio"?: string;
/**
* The audio tracks associated with the current media.
* @inheritDoc
* @readonly
*/
"audioTracks"?: never[];
/**
* Whether the player should automatically pause when another Vime player starts/resumes playback.
* @inheritDoc
*/
"autopause"?: boolean;
/**
* Whether playback should automatically begin playing once the media is ready to do so. This will only work if the browsers `autoplay` policies have been satisfied. It'll generally work if the player is muted, or the user frequently interacts with your site. You can check if it's possible to autoplay via the `canAutoplay()` or `canMutedAutoplay()` methods. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"autoplay"?: boolean;
/**
* The length of the media in seconds that has been downloaded by the browser.
* @inheritDoc
* @readonly
*/
"buffered"?: number;
/**
* Whether playback has temporarily stopped because of a lack of temporary data.
* @inheritDoc
* @readonly
*/
"buffering"?: boolean;
/**
* Indicates whether a user interface should be shown for controlling the resource. Set this to `false` when you want to provide your own custom controls, and `true` if you want the current provider to supply its own default controls. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"controls"?: boolean;
/**
* Gets the index of the currently active audio track. Defaults to `-1` to when the default audio track is used. If you'd like to set it than see the `setCurrentAudioTrack` method.
* @inheritDoc
* @readonly
*/
"currentAudioTrack"?: number;
/**
* The absolute URL of the poster for the current media resource. Defaults to `undefined` if no media/poster has been loaded.
* @inheritDoc
* @readonly
*/
"currentPoster"?: string;
/**
* The current provider name whose responsible for loading and playing media. Defaults to `undefined` when no provider has been loaded.
* @inheritDoc
* @readonly
*/
"currentProvider"?: Provider;
/**
* The absolute URL of the media resource that has been chosen. Defaults to `undefined` if no media has been loaded.
* @inheritDoc
* @readonly
*/
"currentSrc"?: string;
/**
* Gets the index of the currently active text track. Defaults to `-1` to when all text tracks are disabled. If you'd like to set it than see the `setCurrentTextTrack` method.
* @inheritDoc
* @readonly
*/
"currentTextTrack"?: number;
/**
* A `double` indicating the current playback time in seconds. Defaults to `0` if the media has not started to play and has not seeked. Setting this value seeks the media to the new time. The value can be set to a minimum of `0` and maximum of the total length of the media (indicated by the duration prop).
* @inheritDoc
*/
"currentTime"?: number;
/**
* Whether the player is in debug mode and should `console.x` information about its internal state.
* @inheritDoc
*/
"debug"?: boolean;
/**
* A `double` indicating the total playback length of the media in seconds. Defaults to `-1` if no media has been loaded. If the media is being streamed live then the duration is equal to `Infinity`.
* @inheritDoc
* @readonly
*/
"duration"?: number;
/**
* A dictionary of translations for the current language.
* @inheritDoc
* @readonly
*/
"i18n"?: Translation;
/**
* The default icon library to be used throughout the player. You can use a predefined icon library such as vime, material, remix or boxicons. If you'd like to provide your own see the `<vm-icon-library>` component. Remember to pass in the name of your icon library here.
* @inheritDoc
*/
"icons"?: string;
/**
* Whether the current media is of type `audio`, shorthand for `mediaType === MediaType.Audio`.
* @inheritDoc
* @readonly
*/
"isAudio"?: boolean;
/**
* Whether the current view is of type `audio`, shorthand for `viewType === ViewType.Audio`.
* @inheritDoc
* @readonly
*/
"isAudioView"?: boolean;
/**
* Whether the controls are currently visible. This is currently only supported by custom controls.
* @inheritDoc
*/
"isControlsActive"?: boolean;
/**
* Whether the player is currently in fullscreen mode.
* @inheritDoc
* @readonly
*/
"isFullscreenActive"?: boolean;
/**
* Whether the current media is being broadcast live (`duration === Infinity`).
* @inheritDoc
* @readonly
*/
"isLive"?: boolean;
/**
* Whether the player is in mobile mode. This is determined by parsing `window.navigator.userAgent`.
* @inheritDoc
* @readonly
*/
"isMobile"?: boolean;
/**
* Whether the player is currently in picture-in-picture mode.
* @inheritDoc
* @readonly
*/
"isPiPActive"?: boolean;
/**
* Whether the settings menu has been opened and is currently visible. This is currently only supported by custom settings.
* @inheritDoc
* @readonly
*/
"isSettingsActive"?: boolean;
/**
* Whether the current text tracks is visible. If you'd like to set it than see the `setTrackTrackVisibility` method.
* @inheritDoc
* @readonly
*/
"isTextTrackVisible"?: boolean;
/**
* Whether the player is in touch mode. This is determined by listening for mouse/touch events and toggling this value.
* @inheritDoc
* @readonly
*/
"isTouch"?: boolean;
/**
* Whether the current media is of type `video`, shorthand for `mediaType === MediaType.Video`.
* @inheritDoc
* @readonly
*/
"isVideo"?: boolean;
/**
* Whether the current view is of type `video`, shorthand for `viewType === ViewType.Video`.
* @inheritDoc
* @readonly
*/
"isVideoView"?: boolean;
/**
* The current language of the player. This can be any code defined via the `extendLanguage` method or the default `en`. It's recommended to use an ISO 639-1 code as that'll be used by Vime when adding new language defaults in the future.
* @inheritDoc
*/
"language"?: string;
/**
* The languages that are currently available. You can add new languages via the `extendLanguage` method.
* @inheritDoc
* @readonly
*/
"languages"?: string[];
/**
* @readonly
*/
"logger"?: Logger;
/**
* Whether media should automatically start playing from the beginning every time it ends.
* @inheritDoc
*/
"loop"?: boolean;
/**
* The title of the current media. Defaults to `undefined` if no media has been loaded.
* @inheritDoc
* @readonly
*/
"mediaTitle"?: string;
/**
* The type of media that is currently active, whether it's audio or video. Defaults to `undefined` when no media has been loaded or the type cannot be determined.
* @inheritDoc
* @readonly
*/
"mediaType"?: MediaType;
/**
* Whether the audio is muted or not.
* @inheritDoc
*/
"muted"?: boolean;
/**
* Emitted when the `audioTracks` prop changes value.
* @inheritDoc
*/
"onVmAudioTracksChange"?: (event: CustomEvent<PlayerProps['audioTracks']>) => void;
/**
* Emitted when the `buffered` prop changes value.
* @inheritDoc
*/
"onVmBufferedChange"?: (event: CustomEvent<PlayerProps['buffered']>) => void;
/**
* Emitted when the `buffering` prop changes value.
* @inheritDoc
*/
"onVmBufferingChange"?: (event: CustomEvent<PlayerProps['buffering']>) => void;
/**
* Emitted when the `isControlsActive` prop changes value.
* @inheritDoc
*/
"onVmControlsChange"?: (event: CustomEvent<PlayerProps['isControlsActive']>) => void;
/**
* Emitted when the `currentAudioTrack` prop changes value.
* @inheritDoc
*/
"onVmCurrentAudioTrackChange"?: (event: CustomEvent<PlayerProps['currentAudioTrack']>) => void;
/**
* Emitted when the `currentPoster` prop changes value.
* @inheritDoc
*/
"onVmCurrentPosterChange"?: (event: CustomEvent<PlayerProps['currentPoster']>) => void;
/**
* Emitted when the `currentProvider` prop changes value.
* @inheritDoc
*/
"onVmCurrentProviderChange"?: (event: CustomEvent<PlayerProps['currentProvider']>) => void;
/**
* Emitted when the `currentSrc` prop changes value.
* @inheritDoc
*/
"onVmCurrentSrcChange"?: (event: CustomEvent<PlayerProps['currentSrc']>) => void;
/**
* Emitted when the `currentTextTrack` prop changes value.
* @inheritDoc
*/
"onVmCurrentTextTrackChange"?: (event: CustomEvent<PlayerProps['currentTextTrack']>) => void;
/**
* Emitted when the `currentTime` prop changes value.
* @inheritDoc
*/
"onVmCurrentTimeChange"?: (event: CustomEvent<PlayerProps['currentTime']>) => void;
/**
* Emitted when the `duration` prop changes value.
* @inheritDoc
*/
"onVmDurationChange"?: (event: CustomEvent<PlayerProps['duration']>) => void;
/**
* Emitted when an any error has occurred within the player.
* @inheritDoc
*/
"onVmError"?: (event: CustomEvent<any>) => void;
/**
* Emitted when the `isFullscreenActive` prop changes value.
* @inheritDoc
*/
"onVmFullscreenChange"?: (event: CustomEvent<PlayerProps['isFullscreenActive']>) => void;
/**
* Emitted when the `i18n` prop changes value.
* @inheritDoc
*/
"onVmI18nChange"?: (event: CustomEvent<PlayerProps['i18n']>) => void;
/**
* Emitted when the `language` prop changes value.
* @inheritDoc
*/
"onVmLanguageChange"?: (event: CustomEvent<PlayerProps['language']>) => void;
/**
* Emitted when the `languages` prop changes value.
* @inheritDoc
*/
"onVmLanguagesChange"?: (event: CustomEvent<PlayerProps['languages']>) => void;
/**
* Emitted when the `isLive` prop changes value.
* @inheritDoc
*/
"onVmLiveChange"?: (event: CustomEvent<PlayerProps['isLive']>) => void;
/**
* Emitted when the provider starts loading a media resource.
* @inheritDoc
*/
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the `mediaTitle` prop changes value.
* @inheritDoc
*/
"onVmMediaTitleChange"?: (event: CustomEvent<PlayerProps['mediaTitle']>) => void;
/**
* Emitted when the `mediaType` prop changes value.
* @inheritDoc
*/
"onVmMediaTypeChange"?: (event: CustomEvent<PlayerProps['mediaType']>) => void;
/**
* Emitted when the `muted` prop changes value.
* @inheritDoc
*/
"onVmMutedChange"?: (event: CustomEvent<PlayerProps['muted']>) => void;
/**
* Emitted when the `paused` prop changes value.
* @inheritDoc
*/
"onVmPausedChange"?: (event: CustomEvent<PlayerProps['paused']>) => void;
/**
* Emitted when the `isPiPActive` prop changes value.
* @inheritDoc
*/
"onVmPiPChange"?: (event: CustomEvent<PlayerProps['isPiPActive']>) => void;
/**
* Emitted when the media is transitioning from `paused` to `playing`. Event flow: `paused` -> `play` -> `playing`. The media starts `playing` once enough content has buffered to begin/resume playback.
* @inheritDoc
*/
"onVmPlay"?: (event: CustomEvent<void>) => void;
/**
* Emitted when playback reaches the end of the media.
* @inheritDoc
*/
"onVmPlaybackEnded"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the `playbackQualities` prop changes value.
* @inheritDoc
*/
"onVmPlaybackQualitiesChange"?: (event: CustomEvent<PlayerProps['playbackQualities']>) => void;
/**
* Emitted when the `playbackQuality` prop changes value.
* @inheritDoc
*/
"onVmPlaybackQualityChange"?: (event: CustomEvent<PlayerProps['playbackQuality']>) => void;
/**
* Emitted when the `playbackRate` prop changes value.
* @inheritDoc
*/
"onVmPlaybackRateChange"?: (event: CustomEvent<PlayerProps['playbackRate']>) => void;
/**
* Emitted when the `playbackRates` prop changes value.
* @inheritDoc
*/
"onVmPlaybackRatesChange"?: (event: CustomEvent<PlayerProps['playbackRates']>) => void;
/**
* Emitted when the media is ready to begin playback. The following props are guaranteed to be defined when this fires: `mediaTitle`, `currentSrc`, `currentPoster`, `duration`, `mediaType`, `viewType`.
* @inheritDoc
*/
"onVmPlaybackReady"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the media initiates playback.
* @inheritDoc
*/
"onVmPlaybackStarted"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the `playing` prop changes value.
* @inheritDoc
*/
"onVmPlayingChange"?: (event: CustomEvent<PlayerProps['playing']>) => void;
/**
* Emitted when the player has loaded and is ready to be interacted with.
* @inheritDoc
*/
"onVmReady"?: (event: CustomEvent<void>) => void;
/**
* Emitted directly after the player has successfully transitioned/seeked to a new time position. Event flow: `seeking` -> `seeked`.
* @inheritDoc
*/
"onVmSeeked"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the `seeking` prop changes value.
* @inheritDoc
*/
"onVmSeekingChange"?: (event: CustomEvent<PlayerProps['seeking']>) => void;
/**
* Emitted when the `isTextTrackVisible` prop changes value.
* @inheritDoc
*/
"onVmTextTrackVisibleChange"?: (event: CustomEvent<PlayerProps['isTextTrackVisible']>) => void;
/**
* Emitted when the `textTracks` prop changes value.
* @inheritDoc
*/
"onVmTextTracksChange"?: (event: CustomEvent<PlayerProps['textTracks']>) => void;
/**
* Emitted when the `theme` prop changes value.
* @inheritDoc
*/
"onVmThemeChange"?: (event: CustomEvent<PlayerProps['theme']>) => void;
/**
* Emitted when the `isTouch` prop changes value.
* @inheritDoc
*/
"onVmTouchChange"?: (event: CustomEvent<PlayerProps['isTouch']>) => void;
/**
* Emitted when the `translations` prop changes value.
* @inheritDoc
*/
"onVmTranslationsChange"?: (event: CustomEvent<PlayerProps['translations']>) => void;
/**
* Emitted when the `viewType` prop changes value.
* @inheritDoc
*/
"onVmViewTypeChange"?: (event: CustomEvent<PlayerProps['viewType']>) => void;
/**
* Emitted when the `volume` prop changes value.
* @inheritDoc
*/
"onVmVolumeChange"?: (event: CustomEvent<PlayerProps['volume']>) => void;
/**
* Whether playback should be paused. Defaults to `true` if no media has loaded or playback has not started. Setting this to `true` will begin/resume playback.
* @inheritDoc
*/
"paused"?: boolean;
/**
* Whether media playback has reached the end. In other words it'll be true if `currentTime === duration`.
* @inheritDoc
* @readonly
*/
"playbackEnded"?: boolean;
/**
* The media qualities available for the current media.
* @inheritDoc
* @readonly
*/
"playbackQualities"?: string[];
/**
* Indicates the quality of the media. The value will differ between audio and video. For audio this might be some combination of the encoding format (AAC, MP3), bitrate in kilobits per second (kbps) and sample rate in kilohertz (kHZ). For video this will be the number of vertical pixels it supports. For example, if the video has a resolution of `1920x1080` then the quality will return `1080p`. Defaults to `undefined` which you can interpret as the quality is unknown. The value can also be `Auto` for adaptive bit streams (ABR), where the provider can automatically manage the playback quality. The quality can only be set to a quality found in the `playbackQualities` prop. Some providers may not allow changing the quality, you can check if it's possible via `canSetPlaybackQuality()`.
* @inheritDoc
*/
"playbackQuality"?: string;
/**
* A `double` indicating the rate at which media is being played back. If the value is `<1` then playback is slowed down; if `>1` then playback is sped up. Defaults to `1`. The playback rate can only be set to a rate found in the `playbackRates` prop. Some providers may not allow changing the playback rate, you can check if it's possible via `canSetPlaybackRate()`.
* @inheritDoc
*/
"playbackRate"?: number;
/**
* The playback rates available for the current media.
* @inheritDoc
* @readonly
*/
"playbackRates"?: number[];
/**
* Whether media is ready for playback to begin.
* @inheritDoc
* @readonly
*/
"playbackReady"?: boolean;
/**
* Whether the media has initiated playback. In other words it will be true if `currentTime > 0`.
* @inheritDoc
* @readonly
*/
"playbackStarted"?: boolean;
/**
* Whether media is actively playing back. Defaults to `false` if no media has loaded or playback has not started.
* @inheritDoc
* @readonly
*/
"playing"?: boolean;
/**
* Whether the video is to be played "inline", that is within the element's playback area. Note that setting this to false does not imply that the video will always be played in fullscreen. Depending on the provider, changing this prop may cause the player to completely reset.
* @inheritDoc
*/
"playsinline"?: boolean;
/**
* Whether the player has loaded and is ready to be interacted with.
* @inheritDoc
* @readonly
*/
"ready"?: boolean;
/**
* Whether the player is in the process of seeking to a new time position.
* @inheritDoc
* @readonly
*/
"seeking"?: boolean;
/**
* Whether text tracks should be rendered by native player, set to `false` if using custom display.
* @inheritDoc
*/
"shouldRenderNativeTextTracks"?: boolean;
/**
* The text tracks associated with the current media.
* @inheritDoc
* @readonly
*/
"textTracks"?: never[];
/**
* This property has no role other than scoping CSS selectors.
* @inheritDoc
*/
"theme"?: string;
/**
* Contains each language and its respective translation map.
* @inheritDoc
*/
"translations"?: Record<string, Translation>;
/**
* The type of player view that is being used, whether it's an audio player view or video player view. Normally if the media type is of audio then the view is of type audio, but in some cases it might be desirable to show a different view type. For example, when playing audio with a poster. This is subject to the provider allowing it. Defaults to `undefined` when no media has been loaded.
* @inheritDoc
* @readonly
*/
"viewType"?: ViewType;
/**
* An `int` between `0` (silent) and `100` (loudest) indicating the audio volume.
* @inheritDoc
*/
"volume"?: number;
}
interface VmPoster {
"currentPoster"?: PlayerProps['currentPoster'];
"currentTime"?: PlayerProps['currentTime'];
/**
* How the poster image should be resized to fit the container (sets the `object-fit` property).
*/
"fit"?: 'fill' | 'contain' | 'cover' | 'scale-down' | 'none';
"isVideoView"?: PlayerProps['isVideoView'];
"mediaTitle"?: PlayerProps['mediaTitle'];
/**
* Emitted when the poster has loaded.
*/
"onVmLoaded"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the poster will be hidden.
*/
"onVmWillHide"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the poster will be shown.
*/
"onVmWillShow"?: (event: CustomEvent<void>) => void;
"playbackStarted"?: PlayerProps['playbackStarted'];
}
interface VmScrim {
/**
* If this prop is defined, a dark gradient that smoothly fades out without being noticed will be used instead of a set color. This prop also sets the direction in which the dark end of the gradient should start. If the direction is set to `up`, the dark end of the gradient will start at the bottom of the player and fade out to the center. If the direction is set to `down`, the gradient will start at the top of the player and fade out to the center.
*/
"gradient"?: 'up' | 'down';
"isControlsActive"?: PlayerProps['isControlsActive'];
"isVideoView"?: PlayerProps['isVideoView'];
}
interface VmScrubberControl {
/**
* Whether the timestamp in the tooltip should show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours"?: boolean;
"buffered"?: PlayerProps['buffered'];
"buffering"?: PlayerProps['buffering'];
"currentTime"?: PlayerProps['currentTime'];
"duration"?: PlayerProps['duration'];
/**
* Whether the tooltip should not be displayed.
*/
"hideTooltip"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* Prevents seeking forward/backward by using the Left/Right arrow keys.
*/
"noKeyboard"?: boolean;
}
interface VmSettings {
/**
* Whether the settings menu is opened/closed.
*/
"active"?: boolean;
"isAudioView"?: PlayerProps['isAudioView'];
"isMobile"?: PlayerProps['isMobile'];
/**
* Pins the settings to the defined position inside the video player. This has no effect when the view is of type `audio` (always `bottomRight`) and on mobile devices (always bottom sheet).
*/
"pin"?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
}
interface VmSettingsControl {
/**
* Whether the settings menu this control manages is open.
*/
"expanded"?: boolean;
"i18n"?: PlayerProps['i18n'];
/**
* The name of the settings icon to resolve from the icon library.
*/
"icon"?: string;
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
/**
* The DOM `id` of the settings menu this control is responsible for opening/closing.
*/
"menu"?: string;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
}
interface VmSkeleton {
/**
* Determines which animation effect the skeleton will use.
*/
"effect"?: 'sheen' | 'none';
"ready"?: PlayerProps['ready'];
}
interface VmSlider {
/**
* A human-readable label for the purpose of the slider.
*/
"label"?: string;
/**
* The greatest permitted value.
*/
"max"?: number;
/**
* The lowest value in the range of permitted values.
*/
"min"?: number;
/**
* Emitted when the slider loses focus.
*/
"onVmBlur"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the slider receives focus.
*/
"onVmFocus"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the value of the underlying `input` field changes.
*/
"onVmValueChange"?: (event: CustomEvent<number>) => void;
/**
* A number that specifies the granularity that the value must adhere to.
*/
"step"?: number;
/**
* The current value.
*/
"value"?: number;
/**
* Human-readable text alternative for the current value. Defaults to `value:max` percentage.
*/
"valueText"?: string;
}
interface VmSpinner {
"buffering"?: PlayerProps['buffering'];
"currentProvider"?: PlayerProps['currentProvider'];
"isVideoView"?: PlayerProps['isVideoView'];
/**
* Emitted when the spinner will be hidden.
*/
"onVmWillHide"?: (event: CustomEvent<void>) => void;
/**
* Emitted when the spinner will be shown.
*/
"onVmWillShow"?: (event: CustomEvent<void>) => void;
"playbackReady"?: PlayerProps['playbackReady'];
/**
* Whether the spinner should be active when the player is booting or media is loading.
*/
"showWhenMediaLoading"?: boolean;
}
interface VmSubmenu {
/**
* Whether the submenu is open/closed.
*/
"active"?: boolean;
/**
* This can provide additional context about the current state of the submenu. For example, the hint could be the currently selected option if the submenu contains a radio group.
*/
"hint"?: string;
/**
* The title of the submenu.
*/
"label": string;
/**
* Emitted when the submenu has closed/is not active.
*/
"onVmCloseSubmenu"?: (event: CustomEvent<HTMLVmSubmenuElement>) => void;
/**
* Emitted when the submenu is open/active.
*/
"onVmOpenSubmenu"?: (event: CustomEvent<HTMLVmSubmenuElement>) => void;
/**
* The direction the submenu should slide in from.
*/
"slideInDirection"?: 'left' | 'right';
}
interface VmTime {
/**
* Whether the time should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours"?: boolean;
/**
* The `aria-label` property of the time.
*/
"label": string;
/**
* The length of time in seconds.
*/
"seconds"?: number;
}
interface VmTimeProgress {
/**
* Whether the times should always show the hours unit, even if the time is less than 1 hour (eg: `20:35` -> `00:20:35`).
*/
"alwaysShowHours"?: boolean;
/**
* The string used to separate the current time and end time.
*/
"separator"?: string;
}
interface VmTooltip {
/**
* Whether the tooltip is visible or not.
*/
"active"?: boolean;
/**
* Determines if the tooltip should grow according to its contents to the left/right. By default content grows outwards from the center.
*/
"direction"?: TooltipDirection;
/**
* Whether the tooltip is displayed or not.
*/
"hidden"?: boolean;
"isMobile"?: PlayerProps['isMobile'];
"isTouch"?: PlayerProps['isTouch'];
/**
* Determines if the tooltip appears on top/bottom of it's parent.
*/
"position"?: TooltipPosition;
}
interface VmUi {
"isFullscreenActive"?: PlayerProps['isFullscreenActive'];
"isVideoView"?: PlayerProps['isVideoView'];
"playsinline"?: PlayerProps['playsinline'];
}
interface VmVideo {
/**
* **EXPERIMENTAL:** Whether the browser should automatically toggle picture-in-picture mode as the user switches back and forth between this document and another document or application.
* @inheritdoc
*/
"autoPiP"?: boolean;
/**
* Determines what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified).
* @inheritdoc
*/
"controlsList"?: string;
/**
* Whether to use CORS to fetch the related image. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more information.
* @inheritdoc
*/
"crossOrigin"?: MediaCrossOriginOption;
/**
* **EXPERIMENTAL:** Prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases.
* @inheritdoc
*/
"disablePiP"?: boolean;
/**
* **EXPERIMENTAL:** Whether to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc).
* @inheritdoc
*/
"disableRemotePlayback"?: boolean;
"hasCustomTextManager"?: boolean;
/**
* The title of the current media.
*/
"mediaTitle"?: string;
/**
* A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
* @inheritdoc
*/
"poster"?: string;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more information.
* @inheritdoc
*/
"preload"?: MediaPreloadOption;
"willAttach"?: boolean;
}
interface VmVimeo {
"aspectRatio"?: string;
"autoplay"?: boolean;
/**
* Whether to display the video owner's name.
*/
"byline"?: boolean;
/**
* The hexadecimal color value of the playback controls. The embed settings of the video might override this value.
*/
"color"?: string;
"controls"?: boolean;
/**
* Whether cookies should be enabled on the embed.
*/
"cookies"?: boolean;
"language"?: string;
"logger"?: Logger;
"loop"?: boolean;
"muted"?: boolean;
/**
* Turns off automatically determining the aspect ratio of the current video.
*/
"noAutoAspectRatio"?: boolean;
/**
* Emitted when an error has occurred.
*/
"onVmError"?: (event: CustomEvent<any>) => void;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
"playsinline"?: boolean;
/**
* Whether to display the video owner's portrait.
*/
"portrait"?: boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* The Vimeo resource ID of the video to load.
*/
"videoId": string;
}
interface VmVolumeControl {
/**
* Whether the tooltip should be hidden.
*/
"hideTooltip"?: boolean;
/**
* The name of the high volume icon to resolve from the icon library.
*/
"highVolumeIcon"?: string;
"i18n"?: PlayerProps['i18n'];
/**
* The name of an icon library to use. Defaults to the library defined by the `icons` player property.
*/
"icons"?: string;
"isMobile"?: PlayerProps['isMobile'];
/**
* The name of the low volume icon to resolve from the icon library.
*/
"lowVolumeIcon"?: string;
/**
* A pipe (`/`) separated string of JS keyboard keys, that when caught in a `keydown` event, will toggle the muted state of the player.
*/
"muteKeys"?: string;
"muted"?: PlayerProps['muted'];
/**
* The name of the muted volume icon to resolve from the icon library.
*/
"mutedIcon"?: string;
/**
* Prevents the volume being changed using the Up/Down arrow keys.
*/
"noKeyboard"?: boolean;
/**
* The direction in which the tooltip should grow.
*/
"tooltipDirection"?: TooltipDirection;
/**
* Whether the tooltip is positioned above/below the control.
*/
"tooltipPosition"?: TooltipPosition;
"volume"?: PlayerProps['volume'];
}
interface VmYoutube {
"autoplay"?: boolean;
"controls"?: boolean;
/**
* Whether cookies should be enabled on the embed.
*/
"cookies"?: boolean;
"language"?: string;
"logger"?: Logger;
"loop"?: boolean;
"muted"?: boolean;
"onVmLoadStart"?: (event: CustomEvent<void>) => void;
"playsinline"?: boolean;
/**
* The absolute URL of a custom poster to be used for the current video.
*/
"poster"?: string;
/**
* Whether the fullscreen control should be shown.
*/
"showFullscreenControl"?: boolean;
/**
* The YouTube resource ID of the video to load.
*/
"videoId": string;
}
interface IntrinsicElements {
"vm-audio": VmAudio;
"vm-caption-control": VmCaptionControl;
"vm-captions": VmCaptions;
"vm-click-to-play": VmClickToPlay;
"vm-control": VmControl;
"vm-control-group": VmControlGroup;
"vm-control-spacer": VmControlSpacer;
"vm-controls": VmControls;
"vm-current-time": VmCurrentTime;
"vm-dailymotion": VmDailymotion;
"vm-dash": VmDash;
"vm-dbl-click-fullscreen": VmDblClickFullscreen;
"vm-default-controls": VmDefaultControls;
"vm-default-settings": VmDefaultSettings;
"vm-default-ui": VmDefaultUi;
"vm-embed": VmEmbed;
"vm-end-time": VmEndTime;
"vm-file": VmFile;
"vm-fullscreen-control": VmFullscreenControl;
"vm-hls": VmHls;
"vm-icon": VmIcon;
"vm-icon-library": VmIconLibrary;
"vm-live-indicator": VmLiveIndicator;
"vm-loading-screen": VmLoadingScreen;
"vm-menu": VmMenu;
"vm-menu-item": VmMenuItem;
"vm-menu-radio": VmMenuRadio;
"vm-menu-radio-group": VmMenuRadioGroup;
"vm-mute-control": VmMuteControl;
"vm-pip-control": VmPipControl;
"vm-playback-control": VmPlaybackControl;
"vm-player": VmPlayer;
"vm-poster": VmPoster;
"vm-scrim": VmScrim;
"vm-scrubber-control": VmScrubberControl;
"vm-settings": VmSettings;
"vm-settings-control": VmSettingsControl;
"vm-skeleton": VmSkeleton;
"vm-slider": VmSlider;
"vm-spinner": VmSpinner;
"vm-submenu": VmSubmenu;
"vm-time": VmTime;
"vm-time-progress": VmTimeProgress;
"vm-tooltip": VmTooltip;
"vm-ui": VmUi;
"vm-video": VmVideo;
"vm-vimeo": VmVimeo;
"vm-volume-control": VmVolumeControl;
"vm-youtube": VmYoutube;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"vm-audio": LocalJSX.VmAudio & JSXBase.HTMLAttributes<HTMLVmAudioElement>;
"vm-caption-control": LocalJSX.VmCaptionControl & JSXBase.HTMLAttributes<HTMLVmCaptionControlElement>;
"vm-captions": LocalJSX.VmCaptions & JSXBase.HTMLAttributes<HTMLVmCaptionsElement>;
"vm-click-to-play": LocalJSX.VmClickToPlay & JSXBase.HTMLAttributes<HTMLVmClickToPlayElement>;
"vm-control": LocalJSX.VmControl & JSXBase.HTMLAttributes<HTMLVmControlElement>;
"vm-control-group": LocalJSX.VmControlGroup & JSXBase.HTMLAttributes<HTMLVmControlGroupElement>;
"vm-control-spacer": LocalJSX.VmControlSpacer & JSXBase.HTMLAttributes<HTMLVmControlSpacerElement>;
"vm-controls": LocalJSX.VmControls & JSXBase.HTMLAttributes<HTMLVmControlsElement>;
"vm-current-time": LocalJSX.VmCurrentTime & JSXBase.HTMLAttributes<HTMLVmCurrentTimeElement>;
"vm-dailymotion": LocalJSX.VmDailymotion & JSXBase.HTMLAttributes<HTMLVmDailymotionElement>;
"vm-dash": LocalJSX.VmDash & JSXBase.HTMLAttributes<HTMLVmDashElement>;
"vm-dbl-click-fullscreen": LocalJSX.VmDblClickFullscreen & JSXBase.HTMLAttributes<HTMLVmDblClickFullscreenElement>;
"vm-default-controls": LocalJSX.VmDefaultControls & JSXBase.HTMLAttributes<HTMLVmDefaultControlsElement>;
"vm-default-settings": LocalJSX.VmDefaultSettings & JSXBase.HTMLAttributes<HTMLVmDefaultSettingsElement>;
"vm-default-ui": LocalJSX.VmDefaultUi & JSXBase.HTMLAttributes<HTMLVmDefaultUiElement>;
"vm-embed": LocalJSX.VmEmbed & JSXBase.HTMLAttributes<HTMLVmEmbedElement>;
"vm-end-time": LocalJSX.VmEndTime & JSXBase.HTMLAttributes<HTMLVmEndTimeElement>;
"vm-file": LocalJSX.VmFile & JSXBase.HTMLAttributes<HTMLVmFileElement>;
"vm-fullscreen-control": LocalJSX.VmFullscreenControl & JSXBase.HTMLAttributes<HTMLVmFullscreenControlElement>;
"vm-hls": LocalJSX.VmHls & JSXBase.HTMLAttributes<HTMLVmHlsElement>;
"vm-icon": LocalJSX.VmIcon & JSXBase.HTMLAttributes<HTMLVmIconElement>;
"vm-icon-library": LocalJSX.VmIconLibrary & JSXBase.HTMLAttributes<HTMLVmIconLibraryElement>;
"vm-live-indicator": LocalJSX.VmLiveIndicator & JSXBase.HTMLAttributes<HTMLVmLiveIndicatorElement>;
"vm-loading-screen": LocalJSX.VmLoadingScreen & JSXBase.HTMLAttributes<HTMLVmLoadingScreenElement>;
"vm-menu": LocalJSX.VmMenu & JSXBase.HTMLAttributes<HTMLVmMenuElement>;
"vm-menu-item": LocalJSX.VmMenuItem & JSXBase.HTMLAttributes<HTMLVmMenuItemElement>;
"vm-menu-radio": LocalJSX.VmMenuRadio & JSXBase.HTMLAttributes<HTMLVmMenuRadioElement>;
"vm-menu-radio-group": LocalJSX.VmMenuRadioGroup & JSXBase.HTMLAttributes<HTMLVmMenuRadioGroupElement>;
"vm-mute-control": LocalJSX.VmMuteControl & JSXBase.HTMLAttributes<HTMLVmMuteControlElement>;
"vm-pip-control": LocalJSX.VmPipControl & JSXBase.HTMLAttributes<HTMLVmPipControlElement>;
"vm-playback-control": LocalJSX.VmPlaybackControl & JSXBase.HTMLAttributes<HTMLVmPlaybackControlElement>;
"vm-player": LocalJSX.VmPlayer & JSXBase.HTMLAttributes<HTMLVmPlayerElement>;
"vm-poster": LocalJSX.VmPoster & JSXBase.HTMLAttributes<HTMLVmPosterElement>;
"vm-scrim": LocalJSX.VmScrim & JSXBase.HTMLAttributes<HTMLVmScrimElement>;
"vm-scrubber-control": LocalJSX.VmScrubberControl & JSXBase.HTMLAttributes<HTMLVmScrubberControlElement>;
"vm-settings": LocalJSX.VmSettings & JSXBase.HTMLAttributes<HTMLVmSettingsElement>;
"vm-settings-control": LocalJSX.VmSettingsControl & JSXBase.HTMLAttributes<HTMLVmSettingsControlElement>;
"vm-skeleton": LocalJSX.VmSkeleton & JSXBase.HTMLAttributes<HTMLVmSkeletonElement>;
"vm-slider": LocalJSX.VmSlider & JSXBase.HTMLAttributes<HTMLVmSliderElement>;
"vm-spinner": LocalJSX.VmSpinner & JSXBase.HTMLAttributes<HTMLVmSpinnerElement>;
"vm-submenu": LocalJSX.VmSubmenu & JSXBase.HTMLAttributes<HTMLVmSubmenuElement>;
"vm-time": LocalJSX.VmTime & JSXBase.HTMLAttributes<HTMLVmTimeElement>;
"vm-time-progress": LocalJSX.VmTimeProgress & JSXBase.HTMLAttributes<HTMLVmTimeProgressElement>;
"vm-tooltip": LocalJSX.VmTooltip & JSXBase.HTMLAttributes<HTMLVmTooltipElement>;
"vm-ui": LocalJSX.VmUi & JSXBase.HTMLAttributes<HTMLVmUiElement>;
"vm-video": LocalJSX.VmVideo & JSXBase.HTMLAttributes<HTMLVmVideoElement>;
"vm-vimeo": LocalJSX.VmVimeo & JSXBase.HTMLAttributes<HTMLVmVimeoElement>;
"vm-volume-control": LocalJSX.VmVolumeControl & JSXBase.HTMLAttributes<HTMLVmVolumeControlElement>;
"vm-youtube": LocalJSX.VmYoutube & JSXBase.HTMLAttributes<HTMLVmYoutubeElement>;
}
}
} | the_stack |
import { ActionButton } from '@libs/neumorphism-ui/components/ActionButton';
import { Dialog } from '@libs/neumorphism-ui/components/Dialog';
import { HorizontalGraphBar } from '@libs/neumorphism-ui/components/HorizontalGraphBar';
import { HorizontalRuler } from '@libs/neumorphism-ui/components/HorizontalRuler';
import { HorizontalScrollTable } from '@libs/neumorphism-ui/components/HorizontalScrollTable';
import { NativeSelect } from '@libs/neumorphism-ui/components/NativeSelect';
import { Section } from '@libs/neumorphism-ui/components/Section';
import { SelectAndTextInputContainer } from '@libs/neumorphism-ui/components/SelectAndTextInputContainer';
import { Selector } from '@libs/neumorphism-ui/components/Selector';
import { Tab } from '@libs/neumorphism-ui/components/Tab';
import { TextButton } from '@libs/neumorphism-ui/components/TextButton';
import { TextInput } from '@libs/neumorphism-ui/components/TextInput';
import { Tooltip } from '@libs/neumorphism-ui/components/Tooltip';
import { MessageColor, messageColors } from '@libs/neumorphism-ui/themes/Theme';
import { concave, convex, flat, pressed } from '@libs/styled-neumorphism';
import {
Input,
InputAdornment,
Modal,
NativeSelect as MuiNativeSelect,
} from '@material-ui/core';
import { Warning } from '@material-ui/icons';
import React, { ChangeEvent, Fragment, useState } from 'react';
import styled from 'styled-components';
export default {
title: 'components/Preview',
};
const screen = {
mobile: { max: 510 },
// mobile : @media (max-width: ${screen.mobile.max}px)
tablet: { min: 511, max: 830 },
// tablet : @media (min-width: ${screen.tablet.min}px) and (max-width: ${screen.tablet.max}px)
pc: { min: 831, max: 1439 },
// pc : @media (min-width: ${screen.pc.min}px)
monitor: { min: 1440 },
// monitor : @media (min-width: ${screen.pc.min}px) and (max-width: ${screen.pc.max}px)
// huge monitor : @media (min-width: ${screen.monitor.min}px)
} as const;
const textFieldInputProps = {
endAdornment: (
<InputAdornment position="end">
<Tooltip color="error" title="Error Tooltip Content" placement="top">
<Warning />
</Tooltip>
</InputAdornment>
),
};
interface Item {
label: string;
value: string;
}
const selectorItems: Item[] = Array.from(
{ length: Math.floor(Math.random() * 30) },
(_, i) => ({
label: 'Item ' + i,
value: 'item' + i,
}),
);
const tabItems: Item[] = [
{ label: 'Mint', value: 'tab1' },
{ label: 'Burn', value: 'tab2' },
{ label: 'Claim', value: 'tab3' },
];
export const Preview = () => <Component />;
const Component = styled(({ className }: { className?: string }) => {
const [dialogOpen, setDialogOpen] = useState<Record<MessageColor, boolean>>(
() => ({
normal: false,
warning: false,
error: false,
success: false,
}),
);
const [selectedItem, setSelectedItem] = useState<Record<string, Item | null>>(
() => ({}),
);
return (
<div className={className}>
<div className="styles">
<section className="flat">FLAT</section>
<section className="concave">CONCAVE</section>
<section className="convex">CONVEX</section>
<section className="pressed">PRESSED</section>
</div>
<Section className="components">
<article className="buttons">
<TextButton>BUTTON</TextButton>
<ActionButton>BUTTON</ActionButton>
</article>
<HorizontalRuler />
<article className="text-fields">
<TextInput label="TEXT FIELD" />
<TextInput
label="ERROR"
error={true}
InputProps={textFieldInputProps}
helperText="Error Content"
/>
</article>
<HorizontalRuler />
<article className="text-fields">
<TextInput />
<TextInput
error={true}
InputProps={textFieldInputProps}
helperText="Error Content"
/>
</article>
<HorizontalRuler />
<article className="buttons">
{messageColors.map((color) => (
<Fragment key={color}>
<ActionButton
onClick={() =>
setDialogOpen((prev) => ({ ...prev, [color]: true }))
}
>
OPEN {color.toUpperCase()} DIALOG
</ActionButton>
<Modal
open={dialogOpen[color]}
onClose={() =>
setDialogOpen((prev) => ({ ...prev, [color]: false }))
}
>
<Dialog
color={color}
style={{ width: 600, height: 400 }}
onClose={() =>
setDialogOpen((prev) => ({ ...prev, [color]: false }))
}
>
<h1 style={{ textAlign: 'center', fontWeight: 300 }}>
Title
</h1>
</Dialog>
</Modal>
</Fragment>
))}
</article>
<HorizontalRuler />
<article className="buttons">
{messageColors.map((color) => (
<Tooltip key={color} title={color} color={color} placement="top">
<TextButton>{color.toUpperCase()} TOOLTIP</TextButton>
</Tooltip>
))}
</article>
<HorizontalRuler />
<article className="buttons">
<NativeSelect
value={
selectedItem['nativeSelect']?.value ?? selectorItems[0].value
}
onChange={(evt: ChangeEvent<HTMLSelectElement>) =>
setSelectedItem((prev) => ({
...prev,
nativeSelect:
selectorItems.find(
({ value }) => evt.target.value === value,
) ?? null,
}))
}
>
{selectorItems.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</NativeSelect>
<SelectAndTextInputContainer gridColumns={[100, '1fr']}>
<MuiNativeSelect
value={
selectedItem['selectAndTextInput']?.value ??
selectorItems[0].value
}
onChange={(evt) =>
setSelectedItem((prev) => ({
...prev,
selectAndTextInput:
selectorItems.find(
({ value }) => evt.target.value === value,
) ?? null,
}))
}
>
{selectorItems.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</MuiNativeSelect>
<Input placeholder="PLACEHOLDER" />
</SelectAndTextInputContainer>
<Selector
items={selectorItems}
selectedItem={selectedItem['selector']}
onChange={(next) =>
setSelectedItem((prev) => ({ ...prev, selector: next }))
}
labelFunction={(item) => item?.label ?? 'None'}
keyFunction={(item) => item.value}
/>
</article>
<HorizontalRuler />
<article>
<Tab
items={tabItems}
selectedItem={selectedItem['tab'] ?? tabItems[0]}
onChange={(next) =>
setSelectedItem((prev) => ({ ...prev, tab: next }))
}
labelFunction={(item) => item.label}
keyFunction={(item) => item.value}
/>
</article>
<HorizontalRuler />
<article>
<HorizontalGraphBar<{ value: number; color: string }>
style={{ margin: '50px 0' }}
min={-100}
max={100}
data={[
{ value: 50, color: '#4da3ee' },
{ value: 0, color: '#ffffff' },
{ value: -50, color: '#ff8a4b' },
]}
colorFunction={({ color }) => color}
valueFunction={({ value }) => value}
labelRenderer={({ value }, rect) => {
return (
<span
style={{
top: -25,
left: rect.x + rect.width,
transform: 'translateX(-50%)',
}}
>
{value}
</span>
);
}}
>
<span style={{ top: 25, left: 0 }}>Borrow Limit</span>
<span style={{ top: 25, right: 0 }}>$246k</span>
</HorizontalGraphBar>
</article>
</Section>
<Section className="table">
<HorizontalScrollTable minWidth={800}>
<colgroup>
<col style={{ width: 300 }} />
<col style={{ width: 300 }} />
<col style={{ width: 300 }} />
<col style={{ width: 300 }} />
</colgroup>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th style={{ textAlign: 'right' }}>C</th>
<th style={{ textAlign: 'right' }}>D</th>
</tr>
</thead>
<tbody>
{Array.from({ length: 5 }, (_, i) => (
<tr key={`row-${i}`}>
<td>{'A'.repeat(i * 3 + 1)}</td>
<td>{'B'.repeat(i * 3 + 1)}</td>
<td style={{ textAlign: 'right' }}>
{'C'.repeat(i * 3 + 1)}
<br />
{'C'.repeat(i * 2 + 1)}
</td>
<td style={{ textAlign: 'right' }}>{'D'.repeat(i * 3 + 1)}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<td>A</td>
<td>B</td>
<td style={{ textAlign: 'right' }}>C</td>
<td style={{ textAlign: 'right' }}>D</td>
</tr>
</tfoot>
</HorizontalScrollTable>
</Section>
</div>
);
})`
// ---------------------------------------------
// style
// ---------------------------------------------
background-color: ${({ theme }) => theme.backgroundColor};
color: ${({ theme }) => theme.textColor};
.styles {
section {
border-radius: 20px;
padding: 20px;
text-align: center;
color: ${({ theme }) => theme.textColor};
&.flat {
${({ theme }) =>
flat({
color: theme.backgroundColor,
distance: 6,
intensity: theme.intensity,
})};
}
&.concave {
${({ theme }) =>
concave({
color: theme.backgroundColor,
distance: 6,
intensity: theme.intensity,
})};
}
&.convex {
${({ theme }) =>
convex({
color: theme.backgroundColor,
distance: 6,
intensity: theme.intensity,
})};
}
&.pressed {
${({ theme }) =>
pressed({
color: theme.backgroundColor,
distance: 6,
intensity: theme.intensity,
})};
}
}
}
margin-bottom: 1px;
// ---------------------------------------------
// layout
// ---------------------------------------------
.styles {
display: flex;
margin-bottom: 30px;
}
.components {
hr {
margin: 30px 0;
}
margin-bottom: 30px;
}
.table {
margin-bottom: 30px;
}
// pc
@media (min-width: ${screen.pc.min}px) {
padding: 100px;
.styles {
section {
flex: 1;
&:not(:last-child) {
margin-right: 30px;
}
}
}
.components {
.buttons,
.text-fields {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 15px;
}
}
}
// tablet
@media (min-width: ${screen.tablet.min}px) and (max-width: ${screen.tablet
.max}px) {
padding: 30px;
.styles {
section {
flex: 1;
&:not(:last-child) {
margin-right: 10px;
}
}
}
.components {
.buttons,
.text-fields {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 15px;
}
}
.NeuSection-content {
padding: 30px;
}
}
// mobile
@media (max-width: ${screen.mobile.max}px) {
padding: 30px 20px;
.styles {
flex-direction: column;
section {
&:not(:last-child) {
margin-bottom: 20px;
}
}
}
.components {
.buttons,
.text-fields {
display: grid;
grid-template-columns: repeat(1, 1fr);
grid-gap: 15px;
}
.text-fields {
grid-gap: 40px;
}
}
.NeuSection-content {
padding: 20px;
}
}
`; | the_stack |
declare var global: any;
import { TypedHash } from "../collections/collections";
import { RuntimeConfig } from "../configuration/pnplibconfig";
export function extractWebUrl(candidateUrl: string) {
if (candidateUrl === null) {
return "";
}
const index = candidateUrl.indexOf("_api/");
if (index > -1) {
return candidateUrl.substr(0, index);
}
// if all else fails just give them what they gave us back
return candidateUrl;
}
export class Util {
/**
* Gets a callback function which will maintain context across async calls.
* Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...)
*
* @param context The object that will be the 'this' value in the callback
* @param method The method to which we will apply the context and parameters
* @param params Optional, additional arguments to supply to the wrapped method when it is invoked
*/
public static getCtxCallback(context: any, method: Function, ...params: any[]): Function {
return function () {
method.apply(context, params);
};
}
/**
* Tests if a url param exists
*
* @param name The name of the url paramter to check
*/
public static urlParamExists(name: string): boolean {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
const regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
return regex.test(location.search);
}
/**
* Gets a url param value by name
*
* @param name The name of the paramter for which we want the value
*/
public static getUrlParamByName(name: string): string {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
const regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
const results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
/**
* Gets a url param by name and attempts to parse a bool value
*
* @param name The name of the paramter for which we want the boolean value
*/
public static getUrlParamBoolByName(name: string): boolean {
const p = this.getUrlParamByName(name);
const isFalse = (p === "" || /false|0/i.test(p));
return !isFalse;
}
/**
* Inserts the string s into the string target as the index specified by index
*
* @param target The string into which we will insert s
* @param index The location in target to insert s (zero based)
* @param s The string to insert into target at position index
*/
public static stringInsert(target: string, index: number, s: string): string {
if (index > 0) {
return target.substring(0, index) + s + target.substring(index, target.length);
}
return s + target;
}
/**
* Adds a value to a date
*
* @param date The date to which we will add units, done in local time
* @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second']
* @param units The amount to add to date of the given interval
*
* http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object
*/
public static dateAdd(date: Date, interval: string, units: number): Date {
let ret = new Date(date); // don't change original date
switch (interval.toLowerCase()) {
case "year": ret.setFullYear(ret.getFullYear() + units); break;
case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break;
case "month": ret.setMonth(ret.getMonth() + units); break;
case "week": ret.setDate(ret.getDate() + 7 * units); break;
case "day": ret.setDate(ret.getDate() + units); break;
case "hour": ret.setTime(ret.getTime() + units * 3600000); break;
case "minute": ret.setTime(ret.getTime() + units * 60000); break;
case "second": ret.setTime(ret.getTime() + units * 1000); break;
default: ret = undefined; break;
}
return ret;
}
/**
* Loads a stylesheet into the current page
*
* @param path The url to the stylesheet
* @param avoidCache If true a value will be appended as a query string to avoid browser caching issues
*/
public static loadStylesheet(path: string, avoidCache: boolean): void {
if (avoidCache) {
path += "?" + encodeURIComponent((new Date()).getTime().toString());
}
const head = document.getElementsByTagName("head");
if (head.length > 0) {
const e = document.createElement("link");
head[0].appendChild(e);
e.setAttribute("type", "text/css");
e.setAttribute("rel", "stylesheet");
e.setAttribute("href", path);
}
}
/**
* Combines an arbitrary set of paths ensuring that the slashes are normalized
*
* @param paths 0 to n path parts to combine
*/
public static combinePaths(...paths: string[]): string {
return paths
.filter(path => !Util.stringIsNullOrEmpty(path))
.map(path => path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""))
.join("/")
.replace(/\\/g, "/");
}
/**
* Gets a random string of chars length
*
* @param chars The length of the random string to generate
*/
public static getRandomString(chars: number): string {
const text = new Array(chars);
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < chars; i++) {
text[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
return text.join("");
}
/**
* Gets a random GUID value
*
* http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
/* tslint:disable no-bitwise */
public static getGUID(): string {
let d = new Date().getTime();
const guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
});
return guid;
}
/* tslint:enable */
/**
* Determines if a given value is a function
*
* @param candidateFunction The thing to test for being a function
*/
public static isFunction(candidateFunction: any): boolean {
return typeof candidateFunction === "function";
}
/**
* @returns whether the provided parameter is a JavaScript Array or not.
*/
public static isArray(array: any): boolean {
if (Array.isArray) {
return Array.isArray(array);
}
return array && typeof array.length === "number" && array.constructor === Array;
}
/**
* Determines if a string is null or empty or undefined
*
* @param s The string to test
*/
public static stringIsNullOrEmpty(s: string): boolean {
return typeof s === "undefined" || s === null || s.length < 1;
}
/**
* Provides functionality to extend the given object by doing a shallow copy
*
* @param target The object to which properties will be copied
* @param source The source object from which properties will be copied
* @param noOverwrite If true existing properties on the target are not overwritten from the source
*
*/
public static extend(target: any, source: TypedHash<any>, noOverwrite = false): any {
if (source === null || typeof source === "undefined") {
return target;
}
// ensure we don't overwrite things we don't want overwritten
const check: (o: any, i: string) => Boolean = noOverwrite ? (o, i) => !(i in o) : () => true;
return Object.getOwnPropertyNames(source)
.filter((v: string) => check(target, v))
.reduce((t: any, v: string) => {
t[v] = source[v];
return t;
}, target);
}
/**
* Determines if a given url is absolute
*
* @param url The url to check to see if it is absolute
*/
public static isUrlAbsolute(url: string): boolean {
return /^https?:\/\/|^\/\//i.test(url);
}
/**
* Ensures that a given url is absolute for the current web based on context
*
* @param candidateUrl The url to make absolute
*
*/
public static toAbsoluteUrl(candidateUrl: string): Promise<string> {
return new Promise((resolve) => {
if (Util.isUrlAbsolute(candidateUrl)) {
// if we are already absolute, then just return the url
return resolve(candidateUrl);
}
if (RuntimeConfig.spBaseUrl !== null) {
// base url specified either with baseUrl of spfxContext config property
return resolve(Util.combinePaths(RuntimeConfig.spBaseUrl, candidateUrl));
}
if (typeof global._spPageContextInfo !== "undefined") {
// operating in classic pages
if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) {
return resolve(Util.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl));
} else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) {
return resolve(Util.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl));
}
}
// does window.location exist and have a certain path part in it?
if (typeof global.location !== "undefined") {
const baseUrl = global.location.toString().toLowerCase();
["/_layouts/", "/siteassets/"].forEach((s: string) => {
const index = baseUrl.indexOf(s);
if (index > 0) {
return resolve(Util.combinePaths(baseUrl.substr(0, index), candidateUrl));
}
});
}
return resolve(candidateUrl);
});
}
} | 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';
interface Blob {}
declare class DynamoDBStreams extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: DynamoDBStreams.Types.ClientConfiguration)
config: Config & DynamoDBStreams.Types.ClientConfiguration;
/**
* Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table. You can call DescribeStream at a maximum rate of 10 times per second. Each shard in the stream has a SequenceNumberRange associated with it. If the SequenceNumberRange has a StartingSequenceNumber but no EndingSequenceNumber, then the shard is still open (able to receive more stream records). If both StartingSequenceNumber and EndingSequenceNumber are present, then that shard is closed and can no longer receive more data.
*/
describeStream(params: DynamoDBStreams.Types.DescribeStreamInput, callback?: (err: AWSError, data: DynamoDBStreams.Types.DescribeStreamOutput) => void): Request<DynamoDBStreams.Types.DescribeStreamOutput, AWSError>;
/**
* Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table. You can call DescribeStream at a maximum rate of 10 times per second. Each shard in the stream has a SequenceNumberRange associated with it. If the SequenceNumberRange has a StartingSequenceNumber but no EndingSequenceNumber, then the shard is still open (able to receive more stream records). If both StartingSequenceNumber and EndingSequenceNumber are present, then that shard is closed and can no longer receive more data.
*/
describeStream(callback?: (err: AWSError, data: DynamoDBStreams.Types.DescribeStreamOutput) => void): Request<DynamoDBStreams.Types.DescribeStreamOutput, AWSError>;
/**
* Retrieves the stream records from a given shard. Specify a shard iterator using the ShardIterator parameter. The shard iterator specifies the position in the shard from which you want to start reading stream records sequentially. If there are no stream records available in the portion of the shard that the iterator points to, GetRecords returns an empty list. Note that it might take multiple calls to get to a portion of the shard that contains stream records. GetRecords can retrieve a maximum of 1 MB of data or 1000 stream records, whichever comes first.
*/
getRecords(params: DynamoDBStreams.Types.GetRecordsInput, callback?: (err: AWSError, data: DynamoDBStreams.Types.GetRecordsOutput) => void): Request<DynamoDBStreams.Types.GetRecordsOutput, AWSError>;
/**
* Retrieves the stream records from a given shard. Specify a shard iterator using the ShardIterator parameter. The shard iterator specifies the position in the shard from which you want to start reading stream records sequentially. If there are no stream records available in the portion of the shard that the iterator points to, GetRecords returns an empty list. Note that it might take multiple calls to get to a portion of the shard that contains stream records. GetRecords can retrieve a maximum of 1 MB of data or 1000 stream records, whichever comes first.
*/
getRecords(callback?: (err: AWSError, data: DynamoDBStreams.Types.GetRecordsOutput) => void): Request<DynamoDBStreams.Types.GetRecordsOutput, AWSError>;
/**
* Returns a shard iterator. A shard iterator provides information about how to retrieve the stream records from within a shard. Use the shard iterator in a subsequent GetRecords request to read the stream records from the shard. A shard iterator expires 15 minutes after it is returned to the requester.
*/
getShardIterator(params: DynamoDBStreams.Types.GetShardIteratorInput, callback?: (err: AWSError, data: DynamoDBStreams.Types.GetShardIteratorOutput) => void): Request<DynamoDBStreams.Types.GetShardIteratorOutput, AWSError>;
/**
* Returns a shard iterator. A shard iterator provides information about how to retrieve the stream records from within a shard. Use the shard iterator in a subsequent GetRecords request to read the stream records from the shard. A shard iterator expires 15 minutes after it is returned to the requester.
*/
getShardIterator(callback?: (err: AWSError, data: DynamoDBStreams.Types.GetShardIteratorOutput) => void): Request<DynamoDBStreams.Types.GetShardIteratorOutput, AWSError>;
/**
* Returns an array of stream ARNs associated with the current account and endpoint. If the TableName parameter is present, then ListStreams will return only the streams ARNs for that table. You can call ListStreams at a maximum rate of 5 times per second.
*/
listStreams(params: DynamoDBStreams.Types.ListStreamsInput, callback?: (err: AWSError, data: DynamoDBStreams.Types.ListStreamsOutput) => void): Request<DynamoDBStreams.Types.ListStreamsOutput, AWSError>;
/**
* Returns an array of stream ARNs associated with the current account and endpoint. If the TableName parameter is present, then ListStreams will return only the streams ARNs for that table. You can call ListStreams at a maximum rate of 5 times per second.
*/
listStreams(callback?: (err: AWSError, data: DynamoDBStreams.Types.ListStreamsOutput) => void): Request<DynamoDBStreams.Types.ListStreamsOutput, AWSError>;
}
declare namespace DynamoDBStreams {
export type AttributeMap = {[key: string]: AttributeValue};
export type AttributeName = string;
export interface AttributeValue {
/**
* A String data type.
*/
S?: StringAttributeValue;
/**
* A Number data type.
*/
N?: NumberAttributeValue;
/**
* A Binary data type.
*/
B?: BinaryAttributeValue;
/**
* A String Set data type.
*/
SS?: StringSetAttributeValue;
/**
* A Number Set data type.
*/
NS?: NumberSetAttributeValue;
/**
* A Binary Set data type.
*/
BS?: BinarySetAttributeValue;
/**
* A Map data type.
*/
M?: MapAttributeValue;
/**
* A List data type.
*/
L?: ListAttributeValue;
/**
* A Null data type.
*/
NULL?: NullAttributeValue;
/**
* A Boolean data type.
*/
BOOL?: BooleanAttributeValue;
}
export type BinaryAttributeValue = Buffer|Uint8Array|Blob|string;
export type BinarySetAttributeValue = BinaryAttributeValue[];
export type BooleanAttributeValue = boolean;
export type _Date = Date;
export interface DescribeStreamInput {
/**
* The Amazon Resource Name (ARN) for the stream.
*/
StreamArn: StreamArn;
/**
* The maximum number of shard objects to return. The upper limit is 100.
*/
Limit?: PositiveIntegerObject;
/**
* The shard ID of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedShardId in the previous operation.
*/
ExclusiveStartShardId?: ShardId;
}
export interface DescribeStreamOutput {
/**
* A complete description of the stream, including its creation date and time, the DynamoDB table associated with the stream, the shard IDs within the stream, and the beginning and ending sequence numbers of stream records within the shards.
*/
StreamDescription?: StreamDescription;
}
export type ErrorMessage = string;
export interface GetRecordsInput {
/**
* A shard iterator that was retrieved from a previous GetShardIterator operation. This iterator can be used to access the stream records in this shard.
*/
ShardIterator: ShardIterator;
/**
* The maximum number of records to return from the shard. The upper limit is 1000.
*/
Limit?: PositiveIntegerObject;
}
export interface GetRecordsOutput {
/**
* The stream records from the shard, which were retrieved using the shard iterator.
*/
Records?: RecordList;
/**
* The next position in the shard from which to start sequentially reading stream records. If set to null, the shard has been closed and the requested iterator will not return any more data.
*/
NextShardIterator?: ShardIterator;
}
export interface GetShardIteratorInput {
/**
* The Amazon Resource Name (ARN) for the stream.
*/
StreamArn: StreamArn;
/**
* The identifier of the shard. The iterator will be returned for this shard ID.
*/
ShardId: ShardId;
/**
* Determines how the shard iterator is used to start reading stream records from the shard: AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted by a specific sequence number. AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted by a specific sequence number. TRIM_HORIZON - Start reading at the last (untrimmed) stream record, which is the oldest record in the shard. In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream. LATEST - Start reading just after the most recent stream record in the shard, so that you always read the most recent data in the shard.
*/
ShardIteratorType: ShardIteratorType;
/**
* The sequence number of a stream record in the shard from which to start reading.
*/
SequenceNumber?: SequenceNumber;
}
export interface GetShardIteratorOutput {
/**
* The position in the shard from which to start reading stream records sequentially. A shard iterator specifies this position using the sequence number of a stream record in a shard.
*/
ShardIterator?: ShardIterator;
}
export type KeySchema = KeySchemaElement[];
export type KeySchemaAttributeName = string;
export interface KeySchemaElement {
/**
* The name of a key attribute.
*/
AttributeName: KeySchemaAttributeName;
/**
* The attribute data, consisting of the data type and the attribute value itself.
*/
KeyType: KeyType;
}
export type KeyType = "HASH"|"RANGE"|string;
export type ListAttributeValue = AttributeValue[];
export interface ListStreamsInput {
/**
* If this parameter is provided, then only the streams associated with this table name are returned.
*/
TableName?: TableName;
/**
* The maximum number of streams to return. The upper limit is 100.
*/
Limit?: PositiveIntegerObject;
/**
* The ARN (Amazon Resource Name) of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedStreamArn in the previous operation.
*/
ExclusiveStartStreamArn?: StreamArn;
}
export interface ListStreamsOutput {
/**
* A list of stream descriptors associated with the current account and endpoint.
*/
Streams?: StreamList;
/**
* The stream ARN of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request. If LastEvaluatedStreamArn is empty, then the "last page" of results has been processed and there is no more data to be retrieved. If LastEvaluatedStreamArn is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when LastEvaluatedStreamArn is empty.
*/
LastEvaluatedStreamArn?: StreamArn;
}
export type MapAttributeValue = {[key: string]: AttributeValue};
export type NullAttributeValue = boolean;
export type NumberAttributeValue = string;
export type NumberSetAttributeValue = NumberAttributeValue[];
export type OperationType = "INSERT"|"MODIFY"|"REMOVE"|string;
export type PositiveIntegerObject = number;
export type PositiveLongObject = number;
export interface Record {
/**
* A globally unique identifier for the event that was recorded in this stream record.
*/
eventID?: String;
/**
* The type of data modification that was performed on the DynamoDB table: INSERT - a new item was added to the table. MODIFY - one or more of an existing item's attributes were modified. REMOVE - the item was deleted from the table
*/
eventName?: OperationType;
/**
* The version number of the stream record format. This number is updated whenever the structure of Record is modified. Client applications must not assume that eventVersion will remain at a particular value, as this number is subject to change at any time. In general, eventVersion will only increase as the low-level DynamoDB Streams API evolves.
*/
eventVersion?: String;
/**
* The AWS service from which the stream record originated. For DynamoDB Streams, this is aws:dynamodb.
*/
eventSource?: String;
/**
* The region in which the GetRecords request was received.
*/
awsRegion?: String;
/**
* The main body of the stream record, containing all of the DynamoDB-specific fields.
*/
dynamodb?: StreamRecord;
}
export type RecordList = Record[];
export type SequenceNumber = string;
export interface SequenceNumberRange {
/**
* The first sequence number.
*/
StartingSequenceNumber?: SequenceNumber;
/**
* The last sequence number.
*/
EndingSequenceNumber?: SequenceNumber;
}
export interface Shard {
/**
* The system-generated identifier for this shard.
*/
ShardId?: ShardId;
/**
* The range of possible sequence numbers for the shard.
*/
SequenceNumberRange?: SequenceNumberRange;
/**
* The shard ID of the current shard's parent.
*/
ParentShardId?: ShardId;
}
export type ShardDescriptionList = Shard[];
export type ShardId = string;
export type ShardIterator = string;
export type ShardIteratorType = "TRIM_HORIZON"|"LATEST"|"AT_SEQUENCE_NUMBER"|"AFTER_SEQUENCE_NUMBER"|string;
export interface Stream {
/**
* The Amazon Resource Name (ARN) for the stream.
*/
StreamArn?: StreamArn;
/**
* The DynamoDB table with which the stream is associated.
*/
TableName?: TableName;
/**
* A timestamp, in ISO 8601 format, for this stream. Note that LatestStreamLabel is not a unique identifier for the stream, because it is possible that a stream from another table might have the same timestamp. However, the combination of the following three elements is guaranteed to be unique: the AWS customer ID. the table name the StreamLabel
*/
StreamLabel?: String;
}
export type StreamArn = string;
export interface StreamDescription {
/**
* The Amazon Resource Name (ARN) for the stream.
*/
StreamArn?: StreamArn;
/**
* A timestamp, in ISO 8601 format, for this stream. Note that LatestStreamLabel is not a unique identifier for the stream, because it is possible that a stream from another table might have the same timestamp. However, the combination of the following three elements is guaranteed to be unique: the AWS customer ID. the table name the StreamLabel
*/
StreamLabel?: String;
/**
* Indicates the current status of the stream: ENABLING - Streams is currently being enabled on the DynamoDB table. ENABLED - the stream is enabled. DISABLING - Streams is currently being disabled on the DynamoDB table. DISABLED - the stream is disabled.
*/
StreamStatus?: StreamStatus;
/**
* Indicates the format of the records within this stream: KEYS_ONLY - only the key attributes of items that were modified in the DynamoDB table. NEW_IMAGE - entire items from the table, as they appeared after they were modified. OLD_IMAGE - entire items from the table, as they appeared before they were modified. NEW_AND_OLD_IMAGES - both the new and the old images of the items from the table.
*/
StreamViewType?: StreamViewType;
/**
* The date and time when the request to create this stream was issued.
*/
CreationRequestDateTime?: _Date;
/**
* The DynamoDB table with which the stream is associated.
*/
TableName?: TableName;
/**
* The key attribute(s) of the stream's DynamoDB table.
*/
KeySchema?: KeySchema;
/**
* The shards that comprise the stream.
*/
Shards?: ShardDescriptionList;
/**
* The shard ID of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request. If LastEvaluatedShardId is empty, then the "last page" of results has been processed and there is currently no more data to be retrieved. If LastEvaluatedShardId is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when LastEvaluatedShardId is empty.
*/
LastEvaluatedShardId?: ShardId;
}
export type StreamList = Stream[];
export interface StreamRecord {
/**
* The approximate date and time when the stream record was created, in UNIX epoch time format.
*/
ApproximateCreationDateTime?: _Date;
/**
* The primary key attribute(s) for the DynamoDB item that was modified.
*/
Keys?: AttributeMap;
/**
* The item in the DynamoDB table as it appeared after it was modified.
*/
NewImage?: AttributeMap;
/**
* The item in the DynamoDB table as it appeared before it was modified.
*/
OldImage?: AttributeMap;
/**
* The sequence number of the stream record.
*/
SequenceNumber?: SequenceNumber;
/**
* The size of the stream record, in bytes.
*/
SizeBytes?: PositiveLongObject;
/**
* The type of data from the modified DynamoDB item that was captured in this stream record: KEYS_ONLY - only the key attributes of the modified item. NEW_IMAGE - the entire item, as it appeared after it was modified. OLD_IMAGE - the entire item, as it appeared before it was modified. NEW_AND_OLD_IMAGES - both the new and the old item images of the item.
*/
StreamViewType?: StreamViewType;
}
export type StreamStatus = "ENABLING"|"ENABLED"|"DISABLING"|"DISABLED"|string;
export type StreamViewType = "NEW_IMAGE"|"OLD_IMAGE"|"NEW_AND_OLD_IMAGES"|"KEYS_ONLY"|string;
export type String = string;
export type StringAttributeValue = string;
export type StringSetAttributeValue = StringAttributeValue[];
export type TableName = 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 = "2012-08-10"|"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 DynamoDBStreams client.
*/
export import Types = DynamoDBStreams;
}
export = DynamoDBStreams; | the_stack |
import {
h,
ref,
Suspense,
ComponentOptions,
render,
nodeOps,
serializeInner,
nextTick,
onMounted,
watch,
watchEffect,
onUnmounted,
onErrorCaptured,
shallowRef
} from '@vue/runtime-test'
import { createApp } from 'vue'
describe('Suspense', () => {
const deps: Promise<any>[] = []
beforeEach(() => {
deps.length = 0
})
// a simple async factory for testing purposes only.
function defineAsyncComponent<T extends ComponentOptions>(
comp: T,
delay: number = 0
) {
return {
setup(props: any, { slots }: any) {
const p = new Promise(resolve => {
setTimeout(() => {
resolve(() => h(comp, props, slots))
}, delay)
})
// in Node 12, due to timer/nextTick mechanism change, we have to wait
// an extra tick to avoid race conditions
deps.push(p.then(() => Promise.resolve()))
return p
}
}
}
test('fallback content', async () => {
const Async = defineAsyncComponent({
render() {
return h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
})
test('emits events', async () => {
const Async = defineAsyncComponent({
render() {
return h('div', 'async')
}
})
const onFallback = jest.fn()
const onResolve = jest.fn()
const onPending = jest.fn()
const show = ref(true)
const Comp = {
setup() {
return () =>
h(
Suspense,
{
onFallback,
onResolve,
onPending,
// force displaying the fallback right away
timeout: 0
},
{
default: () => (show.value ? h(Async) : null),
fallback: h('div', 'fallback')
}
)
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(onFallback).toHaveBeenCalledTimes(1)
expect(onPending).toHaveBeenCalledTimes(1)
expect(onResolve).toHaveBeenCalledTimes(0)
await Promise.all(deps)
await nextTick()
expect(onFallback).toHaveBeenCalledTimes(1)
expect(onPending).toHaveBeenCalledTimes(1)
expect(onResolve).toHaveBeenCalledTimes(1)
show.value = false
await nextTick()
expect(onFallback).toHaveBeenCalledTimes(1)
expect(onPending).toHaveBeenCalledTimes(2)
expect(onResolve).toHaveBeenCalledTimes(2)
deps.length = 0
show.value = true
await nextTick()
expect(onFallback).toHaveBeenCalledTimes(2)
expect(onPending).toHaveBeenCalledTimes(3)
expect(onResolve).toHaveBeenCalledTimes(2)
await Promise.all(deps)
await nextTick()
expect(onFallback).toHaveBeenCalledTimes(2)
expect(onPending).toHaveBeenCalledTimes(3)
expect(onResolve).toHaveBeenCalledTimes(3)
})
test('nested async deps', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent({
setup() {
onMounted(() => {
calls.push('outer mounted')
})
return () => h(AsyncInner)
}
})
const AsyncInner = defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'inner')
}
},
10
)
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncOuter),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(calls).toEqual([`outer mounted`, `inner mounted`])
expect(serializeInner(root)).toBe(`<div>inner</div>`)
})
test('onResolve', async () => {
const Async = defineAsyncComponent({
render() {
return h('div', 'async')
}
})
const onResolve = jest.fn()
const Comp = {
setup() {
return () =>
h(
Suspense,
{
onResolve
},
{
default: h(Async),
fallback: h('div', 'fallback')
}
)
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(onResolve).not.toHaveBeenCalled()
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(onResolve).toHaveBeenCalled()
})
test('buffer mounted/updated hooks & post flush watch callbacks', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
// extra tick needed for Node 12+
deps.push(p.then(() => Promise.resolve()))
watchEffect(
() => {
calls.push('watch effect')
},
{ flush: 'post' }
)
const count = ref(0)
watch(
count,
() => {
calls.push('watch callback')
},
{ flush: 'post' }
)
count.value++ // trigger the watcher now
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
await p
return () => h('div', 'async')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(calls).toEqual([`watch effect`, `watch callback`, `mounted`])
// effects inside an already resolved suspense should happen at normal timing
toggle.value = false
await nextTick()
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(calls).toEqual([
`watch effect`,
`watch callback`,
`mounted`,
'unmounted'
])
})
// #1059
test('mounted/updated hooks & fallback component', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
// extra tick needed for Node 12+
deps.push(p.then(() => Promise.resolve()))
await p
return () => h('div', 'async')
}
}
const Fallback = {
setup() {
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
return () => h('div', 'fallback')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h(Fallback)
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([`mounted`])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(calls).toEqual([`mounted`, `unmounted`])
})
test('content update before suspense resolve', async () => {
const Async = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
return () => h('div', props.msg)
}
})
const msg = ref('foo')
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(Async, { msg: msg.value }),
fallback: h('div', `fallback ${msg.value}`)
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback foo</div>`)
// value changed before resolve
msg.value = 'bar'
await nextTick()
// fallback content should be updated
expect(serializeInner(root)).toBe(`<div>fallback bar</div>`)
await Promise.all(deps)
await nextTick()
// async component should receive updated props/slots when resolved
expect(serializeInner(root)).toBe(`<div>bar</div>`)
})
// mount/unmount hooks should not even fire
test('unmount before suspense resolve', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
deps.push(p)
watchEffect(
() => {
calls.push('watch effect')
},
{ flush: 'post' }
)
const count = ref(0)
watch(
count,
() => {
calls.push('watch callback')
},
{ flush: 'post' }
)
count.value++ // trigger the watcher now
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
await p
return () => h('div', 'async')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
// remove the async dep before it's resolved
toggle.value = false
await nextTick()
// should cause the suspense to resolve immediately
expect(serializeInner(root)).toBe(`<!---->`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
// should discard effects
expect(calls).toEqual([])
})
test('unmount suspense after resolve', async () => {
const toggle = ref(true)
const unmounted = jest.fn()
const Async = defineAsyncComponent({
setup() {
onUnmounted(unmounted)
return () => h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
toggle.value
? h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
: null
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(unmounted).not.toHaveBeenCalled()
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(unmounted).toHaveBeenCalled()
})
test('unmount suspense before resolve', async () => {
const toggle = ref(true)
const mounted = jest.fn()
const unmounted = jest.fn()
const Async = defineAsyncComponent({
setup() {
onMounted(mounted)
onUnmounted(unmounted)
return () => h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
toggle.value
? h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
: null
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(mounted).not.toHaveBeenCalled()
expect(unmounted).not.toHaveBeenCalled()
await Promise.all(deps)
await nextTick()
// should not resolve and cause unmount
expect(mounted).not.toHaveBeenCalled()
expect(unmounted).not.toHaveBeenCalled()
})
test('nested suspense (parent resolves first)', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('outer mounted')
})
return () => h('div', 'async outer')
}
},
1
)
const AsyncInner = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'async inner')
}
},
10
)
const Inner = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncInner),
fallback: h('div', 'fallback inner')
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h('div', [h(AsyncOuter), h(Inner)]),
fallback: h('div', 'fallback outer')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>async outer</div><div>fallback inner</div></div>`
)
expect(calls).toEqual([`outer mounted`])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>async outer</div><div>async inner</div></div>`
)
expect(calls).toEqual([`outer mounted`, `inner mounted`])
})
test('nested suspense (child resolves first)', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('outer mounted')
})
return () => h('div', 'async outer')
}
},
10
)
const AsyncInner = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'async inner')
}
},
1
)
const Inner = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncInner),
fallback: h('div', 'fallback inner')
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h('div', [h(AsyncOuter), h(Inner)]),
fallback: h('div', 'fallback outer')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
await deps[1]
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>async outer</div><div>async inner</div></div>`
)
expect(calls).toEqual([`inner mounted`, `outer mounted`])
})
test('error handling', async () => {
const Async = {
async setup() {
throw new Error('oops')
}
}
const Comp = {
setup() {
const errorMessage = ref<string | null>(null)
onErrorCaptured(err => {
errorMessage.value =
err instanceof Error
? err.message
: `A non-Error value thrown: ${err}`
return false
})
return () =>
errorMessage.value
? h('div', errorMessage.value)
: h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>oops</div>`)
})
// #3857
test('error handling w/ template optimization', async () => {
const Async = {
async setup() {
throw new Error('oops')
}
}
const Comp = {
template: `
<div v-if="errorMessage">{{ errorMessage }}</div>
<Suspense v-else>
<div>
<Async />
</div>
<template #fallback>
<div>fallback</div>
</template>
</Suspense>
`,
components: { Async },
setup() {
const errorMessage = ref<string | null>(null)
onErrorCaptured(err => {
errorMessage.value =
err instanceof Error
? err.message
: `A non-Error value thrown: ${err}`
return false
})
return { errorMessage }
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>oops</div>`)
})
it('combined usage (nested async + nested suspense + multiple deps)', async () => {
const msg = ref('nested msg')
const calls: number[] = []
const AsyncChildWithSuspense = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(0)
})
return () =>
h(Suspense, null, {
default: h(AsyncInsideNestedSuspense, { msg: props.msg }),
fallback: h('div', 'nested fallback')
})
}
})
const AsyncInsideNestedSuspense = defineAsyncComponent(
{
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(2)
})
return () => h('div', props.msg)
}
},
20
)
const AsyncChildParent = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(1)
})
return () => h(NestedAsyncChild, { msg: props.msg })
}
})
const NestedAsyncChild = defineAsyncComponent(
{
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(3)
})
return () => h('div', props.msg)
}
},
10
)
const MiddleComponent = {
setup() {
return () =>
h(AsyncChildWithSuspense, {
msg: msg.value
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h('div', [
h(MiddleComponent),
h(AsyncChildParent, {
msg: 'root async'
})
]),
fallback: h('div', 'root fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
expect(calls).toEqual([])
/**
* <Root>
* <Suspense>
* <MiddleComponent>
* <AsyncChildWithSuspense> (0: resolves on macrotask)
* <Suspense>
* <AsyncInsideNestedSuspense> (2: resolves on macrotask + 20ms)
* <AsyncChildParent> (1: resolves on macrotask)
* <NestedAsyncChild> (3: resolves on macrotask + 10ms)
*/
// both top level async deps resolved, but there is another nested dep
// so should still be in fallback state
await Promise.all([deps[0], deps[1]])
await nextTick()
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
expect(calls).toEqual([])
// root suspense all deps resolved. should show root content now
// with nested suspense showing fallback content
await deps[3]
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>nested fallback</div><div>root async</div></div>`
)
expect(calls).toEqual([0, 1, 3])
// change state for the nested component before it resolves
msg.value = 'nested changed'
// all deps resolved, nested suspense should resolve now
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>nested changed</div><div>root async</div></div>`
)
expect(calls).toEqual([0, 1, 3, 2])
// should update just fine after resolve
msg.value = 'nested changed again'
await nextTick()
expect(serializeInner(root)).toBe(
`<div><div>nested changed again</div><div>root async</div></div>`
)
})
test('switching branches', async () => {
const calls: string[] = []
const toggle = ref(true)
const Foo = defineAsyncComponent({
setup() {
onMounted(() => {
calls.push('foo mounted')
})
onUnmounted(() => {
calls.push('foo unmounted')
})
return () => h('div', ['foo', h(FooNested)])
}
})
const FooNested = defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push('foo nested mounted')
})
onUnmounted(() => {
calls.push('foo nested unmounted')
})
return () => h('div', 'foo nested')
}
},
10
)
const Bar = defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push('bar mounted')
})
onUnmounted(() => {
calls.push('bar unmounted')
})
return () => h('div', 'bar')
}
},
10
)
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Foo) : h(Bar),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(calls).toEqual([`foo mounted`, `foo nested mounted`])
expect(serializeInner(root)).toBe(`<div>foo<div>foo nested</div></div>`)
// toggle
toggle.value = false
await nextTick()
expect(deps.length).toBe(3)
// should remain on current view
expect(calls).toEqual([`foo mounted`, `foo nested mounted`])
expect(serializeInner(root)).toBe(`<div>foo<div>foo nested</div></div>`)
await Promise.all(deps)
await nextTick()
const tempCalls = [
`foo mounted`,
`foo nested mounted`,
`bar mounted`,
`foo nested unmounted`,
`foo unmounted`
]
expect(calls).toEqual(tempCalls)
expect(serializeInner(root)).toBe(`<div>bar</div>`)
// toggle back
toggle.value = true
await nextTick()
// should remain
expect(calls).toEqual(tempCalls)
expect(serializeInner(root)).toBe(`<div>bar</div>`)
await deps[3]
await nextTick()
// still pending...
expect(calls).toEqual(tempCalls)
expect(serializeInner(root)).toBe(`<div>bar</div>`)
await Promise.all(deps)
await nextTick()
expect(calls).toEqual([
...tempCalls,
`foo mounted`,
`foo nested mounted`,
`bar unmounted`
])
expect(serializeInner(root)).toBe(`<div>foo<div>foo nested</div></div>`)
})
test('branch switch to 3rd branch before resolve', async () => {
const calls: string[] = []
const makeComp = (name: string, delay = 0) =>
defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push(`${name} mounted`)
})
onUnmounted(() => {
calls.push(`${name} unmounted`)
})
return () => h('div', [name])
}
},
delay
)
const One = makeComp('one')
const Two = makeComp('two', 10)
const Three = makeComp('three', 20)
const view = shallowRef(One)
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(view.value),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
view.value = Two
await nextTick()
expect(deps.length).toBe(2)
// switch before two resovles
view.value = Three
await nextTick()
expect(deps.length).toBe(3)
// dep for two resolves
await deps[1]
await nextTick()
// should still be on view one
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
await deps[2]
await nextTick()
expect(serializeInner(root)).toBe(`<div>three</div>`)
expect(calls).toEqual([`one mounted`, `three mounted`, `one unmounted`])
})
test('branch switch back before resolve', async () => {
const calls: string[] = []
const makeComp = (name: string, delay = 0) =>
defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push(`${name} mounted`)
})
onUnmounted(() => {
calls.push(`${name} unmounted`)
})
return () => h('div', [name])
}
},
delay
)
const One = makeComp('one')
const Two = makeComp('two', 10)
const view = shallowRef(One)
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(view.value),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
view.value = Two
await nextTick()
expect(deps.length).toBe(2)
// switch back before two resovles
view.value = One
await nextTick()
expect(deps.length).toBe(2)
// dep for two resolves
await deps[1]
await nextTick()
// should still be on view one
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
})
test('branch switch timeout + fallback', async () => {
const calls: string[] = []
const makeComp = (name: string, delay = 0) =>
defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push(`${name} mounted`)
})
onUnmounted(() => {
calls.push(`${name} unmounted`)
})
return () => h('div', [name])
}
},
delay
)
const One = makeComp('one')
const Two = makeComp('two', 20)
const view = shallowRef(One)
const Comp = {
setup() {
return () =>
h(
Suspense,
{
timeout: 10
},
{
default: h(view.value),
fallback: h('div', 'fallback')
}
)
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
view.value = Two
await nextTick()
expect(serializeInner(root)).toBe(`<div>one</div>`)
expect(calls).toEqual([`one mounted`])
await new Promise(r => setTimeout(r, 10))
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([`one mounted`, `one unmounted`])
await deps[1]
await nextTick()
expect(serializeInner(root)).toBe(`<div>two</div>`)
expect(calls).toEqual([`one mounted`, `one unmounted`, `two mounted`])
})
// #2214
// Since suspense renders its own root like a component, it should not patch
// its content in optimized mode.
test('should not miss nested element updates when used in templates', async () => {
const n = ref(1)
const Comp = {
setup() {
return { n }
},
template: `
<Suspense>
<div><span>{{ n }}</span></div>
</Suspense>
`
}
const root = document.createElement('div')
createApp(Comp).mount(root)
expect(root.innerHTML).toBe(`<div><span>1</span></div>`)
n.value++
await nextTick()
expect(root.innerHTML).toBe(`<div><span>2</span></div>`)
})
// #2215
test('toggling nested async setup component inside already resolved suspense', async () => {
const toggle = ref(false)
const Child = {
async setup() {
return () => h('div', 'child')
}
}
const Parent = () => h('div', ['parent', toggle.value ? h(Child) : null])
const Comp = {
setup() {
return () => h(Suspense, () => h(Parent))
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>parent<!----></div>`)
toggle.value = true
// wait for flush
await nextTick()
// wait for child async setup resolve
await nextTick()
// child should be rendered now instead of stuck in limbo
expect(serializeInner(root)).toBe(`<div>parent<div>child</div></div>`)
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<div>parent<!----></div>`)
})
}) | the_stack |
/*!
* Copyright (c) 2020 Ron Buckton (rbuckton@chronicles.org)
*
* This file is licensed to you under the terms of the MIT License, found in the LICENSE file
* in the root of this repository or package.
*/
import { createHash } from "crypto";
import { Cancelable } from "@esfx/cancelable";
import { CancelToken } from "@esfx/async-canceltoken";
import { Diagnostics, DiagnosticMessages, Diagnostic, formatList, NullDiagnosticMessages } from "./diagnostics";
import { LineOffsetMap } from "./lineOffsetMap";
import { SyntaxKind, tokenToString } from "./tokens";
import { Symbol, SymbolKind } from "./symbols";
import { BindingTable } from "./binder";
import { StringWriter } from "./stringwriter";
import { CompilerOptions } from "./options";
import {
Node,
SourceFile,
UnicodeCharacterLiteral,
UnicodeCharacterRange,
Prose,
Identifier,
Parameter,
ParameterList,
OneOfList,
Terminal,
SymbolSet,
Assertion,
EmptyAssertion,
LookaheadAssertion,
NoSymbolHereAssertion,
LexicalGoalAssertion,
Constraints,
ProseAssertion,
ProseFragment,
ProseFragmentLiteral,
Argument,
ArgumentList,
Nonterminal,
OneOfSymbol,
LexicalSymbol,
OptionalSymbol,
ButNotSymbol,
SymbolSpan,
LinkReference,
RightHandSide,
RightHandSideList,
Production,
SourceElement,
Define,
PlaceholderSymbol,
HtmlTrivia,
Line,
Declaration,
TerminalLiteral,
} from "./nodes";
import { NodeNavigator } from "./navigator";
import { toCancelToken } from "./core";
import { Position, Range } from "./types";
import { RegionMap } from "./regionMap";
class NodeLinks {
hasResolvedSymbols?: boolean;
}
class SymbolLinks {
isReferenced?: boolean;
}
interface Defines {
readonly noStrictParametricProductions: boolean;
readonly noUnusedParameters: boolean;
}
interface DefineOverrides {
noStrictParametricProductions?: boolean | "default";
noUnusedParameters?: boolean | "default";
}
function equateDefines(a: DefineOverrides, b: DefineOverrides) {
return a.noStrictParametricProductions === b.noStrictParametricProductions
&& a.noUnusedParameters === b.noUnusedParameters;
}
/** {@docCategory Check} */
export class Checker {
private _options: CompilerOptions | undefined;
private _checkedFileSet = new Set<string>();
private _bindings!: BindingTable;
private _diagnostics!: DiagnosticMessages;
private _sourceFile!: SourceFile;
private _noChecks!: boolean;
private _productionParametersByName!: Map<Production, Set<string>>;
private _cancelToken?: CancelToken;
private _nodeLinks?: Map<Node, NodeLinks>;
private _symbolLinks?: Map<Symbol, SymbolLinks>;
private _lineOffsetMap: LineOffsetMap;
private _defines: Defines;
private _defineOverrideMap?: RegionMap<DefineOverrides>;
constructor(options?: CompilerOptions, lineOffsetMap = new LineOffsetMap()) {
this._options = options;
this._lineOffsetMap = lineOffsetMap;
this._defines = {
noStrictParametricProductions: this._options?.noStrictParametricProductions ?? false,
noUnusedParameters: this._options?.noUnusedParameters ?? false
};
}
public checkSourceFile(sourceFile: SourceFile, bindings: BindingTable, diagnostics: DiagnosticMessages, cancelable?: Cancelable): void {
const cancelToken = toCancelToken(cancelable);
cancelToken?.throwIfSignaled();
if (!this._checkedFileSet.has(sourceFile.filename)) {
const savedNoChecks = this._noChecks;
const savedCancellationToken = this._cancelToken;
const savedSourceFile = this._sourceFile;
const savedProductionParametersByName = this._productionParametersByName;
const savedBindings = this._bindings;
const savedDiagnostics = this._diagnostics;
try {
this._cancelToken = cancelToken;
this._sourceFile = sourceFile;
this._productionParametersByName = new Map();
this._noChecks = this._options?.noChecks ?? false;
this._bindings = new BindingTable();
this._bindings._copyFrom(bindings);
this._diagnostics = this._noChecks ? NullDiagnosticMessages.instance : new DiagnosticMessages();
this._diagnostics.setSourceFile(this._sourceFile);
for (const element of sourceFile.elements) {
this.preprocessSourceElement(element);
}
for (const element of sourceFile.elements) {
this.checkSourceElement(element);
}
diagnostics.copyFrom(this._diagnostics);
bindings._copyFrom(this._bindings);
this._checkedFileSet.add(sourceFile.filename);
}
finally {
this._noChecks = savedNoChecks;
this._cancelToken = savedCancellationToken;
this._sourceFile = savedSourceFile;
this._productionParametersByName = savedProductionParametersByName;
this._bindings = savedBindings;
this._diagnostics = savedDiagnostics;
}
}
}
private getDefine<K extends keyof DefineOverrides>(location: Node, key: K): NonNullable<Defines[K]>;
private getDefine<K extends keyof DefineOverrides>(location: Node, key: K) {
if (this._defineOverrideMap) {
const position = this._sourceFile.lineMap.positionAt(location.getStart(this._sourceFile))
for (const region of this._defineOverrideMap.regions(this._sourceFile, position.line)) {
const value = region.value[key];
if (value === "default") break;
if (value === undefined) continue;
return value;
}
}
return this._defines[key];
}
private preprocessSourceElement(node: SourceElement): void {
switch (node.kind) {
case SyntaxKind.Define:
this.preprocessDefine(<Define>node);
break;
case SyntaxKind.Line:
this.preprocessLine(<Line>node);
break;
}
}
private preprocessDefine(node: Define) {
if (!this.checkGrammarDefine(node)) {
const position = this._sourceFile.lineMap.positionAt(node.getStart(this._sourceFile));
const nodeKey = node.key;
const nodeKeyText = nodeKey.text;
this._defineOverrideMap ??= new RegionMap(equateDefines);
switch (nodeKeyText) {
case "noStrictParametricProductions":
this._defineOverrideMap.addRegion(this._sourceFile, position.line, {
noStrictParametricProductions:
node.valueToken!.kind === SyntaxKind.DefaultKeyword ? "default" :
node.valueToken!.kind === SyntaxKind.TrueKeyword
});
break;
case "noUnusedParameters":
this._defineOverrideMap.addRegion(this._sourceFile, position.line, {
noUnusedParameters:
node.valueToken!.kind === SyntaxKind.DefaultKeyword ? "default" :
node.valueToken!.kind === SyntaxKind.TrueKeyword
});
break;
default:
this.reportError(nodeKey, Diagnostics.Cannot_find_name_0_, nodeKeyText);
break;
}
}
}
private checkGrammarDefine(node: Define) {
if (node.key?.text === undefined) {
return this.reportGrammarError(node, node.defineKeyword.end, Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
if (!node.valueToken) {
return this.reportGrammarError(node, node.key.end, Diagnostics._0_expected, formatList([SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.DefaultKeyword]));
}
return false;
}
private preprocessLine(node: Line) {
if (!this.checkGrammarLine(node)) {
// @line re-numbering starts with the next line
const generatedLine = this._sourceFile.lineMap.positionAt(node.end).line + 1;
if (node.number?.kind === SyntaxKind.DefaultKeyword) {
this._lineOffsetMap.addLineOffset(this._sourceFile, generatedLine, "default");
}
else if (node.number?.kind === SyntaxKind.NumberLiteral) {
this._lineOffsetMap.addLineOffset(this._sourceFile, generatedLine, { line: +node.number.text! - 1, file: node.path?.text });
}
}
}
private checkGrammarLine(node: Line) {
if (!node.number || node.number.kind === SyntaxKind.NumberLiteral && node.number.text === undefined) {
return this.reportGrammarError(node, node.lineKeyword.end, Diagnostics._0_expected, formatList([SyntaxKind.NumberLiteral, SyntaxKind.DefaultKeyword]));
}
if (node.path && node.path.text === undefined) {
return this.reportGrammarError(node, node.number.end, Diagnostics._0_expected, formatList([SyntaxKind.StringLiteral]));
}
return false;
}
private checkSourceElement(node: SourceElement): void {
switch (node.kind) {
case SyntaxKind.Production:
this.checkProduction(<Production>node);
break;
}
}
private checkProduction(node: Production): void {
this.checkGrammarProduction(node);
if (this.getDefine(node, "noStrictParametricProductions")) {
this.checkProductionNonStrict(node);
}
else {
this.checkProductionStrict(node);
}
if (node.body) {
switch (node.body.kind) {
case SyntaxKind.OneOfList:
this.checkOneOfList(<OneOfList>node.body);
break;
case SyntaxKind.RightHandSideList:
this.checkRightHandSideList(<RightHandSideList>node.body);
break;
case SyntaxKind.RightHandSide:
this.checkRightHandSide(<RightHandSide>node.body);
break;
}
}
this.getNodeLinks(node, /*create*/ true).hasResolvedSymbols = true;
if (this.getDefine(node, "noUnusedParameters")) {
const symbol = this._bindings.getSymbol(node);
if (symbol) {
for (const decl of this._bindings.getDeclarations(symbol)) {
if (decl.kind === SyntaxKind.Production) {
this.resolveProduction(decl);
}
}
}
if (node.parameterList?.elements) {
for (const param of node.parameterList.elements) {
const symbol = this._bindings.getSymbol(param);
if (symbol && !this.getSymbolLinks(symbol)?.isReferenced) {
this.reportError(param, Diagnostics.Parameter_0_is_unused, param.name.text);
}
}
}
}
}
private resolveProduction(node: Production) {
if (!this.getNodeLinks(node)?.hasResolvedSymbols) {
this.getNodeLinks(node, /*create*/ true).hasResolvedSymbols = true;
}
const visitNode = (node: Node) => {
if (node.kind === SyntaxKind.Identifier) {
this.resolveIdentifier(node as Identifier);
}
node.forEachChild(visitNode);
};
node.forEachChild(visitNode);
}
private checkProductionNonStrict(node: Production) {
this.checkIdentifier(node.name);
if (node.parameterList) {
this.checkParameterList(node.parameterList);
}
}
private getProductionParametersByName(node: Production) {
let parametersByName = this._productionParametersByName.get(node);
if (parametersByName) return parametersByName;
this._productionParametersByName.set(node, parametersByName = new Set());
const parameterList = node.parameterList;
const parameters = parameterList?.elements;
if (parameters) {
for (let i = 0; i < parameters.length; i++) {
const parameterNameText = parameters[i]?.name?.text;
if (parameterNameText) {
parametersByName.add(parameterNameText);
}
}
}
return parametersByName;
}
private checkProductionStrict(thisProduction: Production) {
const thisProductionName = thisProduction.name;
const thisProductionNameText = thisProductionName.text;
const thisProductionSymbol = this.checkIdentifier(thisProductionName);
const thisProductionParameterList = thisProduction.parameterList;
const thisProductionParameters = thisProductionParameterList?.elements;
const thisProductionParameterCount = thisProductionParameters?.length ?? 0;
const firstProduction = <Production>this._bindings.getDeclarations(thisProductionSymbol)[0];
if (thisProductionParameterList && thisProductionParameters) {
this.checkParameterList(thisProductionParameterList);
}
if (firstProduction === thisProduction) {
return;
}
const thisProductionParameterNames = this.getProductionParametersByName(thisProduction);
const firstProductionParameterList = firstProduction.parameterList;
const firstProductionParameters = firstProductionParameterList?.elements;
const firstProductionParameterCount = firstProductionParameters?.length ?? 0;
const firstProductionParameterNames = this.getProductionParametersByName(firstProduction);
if (firstProductionParameters) {
for (let i = 0; i < firstProductionParameterCount; i++) {
const firstProductionParameter = firstProductionParameters[i];
const firstProductionParameterName = firstProductionParameter.name;
const firstProductionParameterNameText = firstProductionParameterName.text;
if (firstProductionParameterNameText && !thisProductionParameterNames.has(firstProductionParameterNameText)) {
this.reportError(thisProductionName, Diagnostics.Production_0_is_missing_parameter_1_All_definitions_of_production_0_must_specify_the_same_formal_parameters, thisProductionNameText, firstProductionParameterNameText);
}
}
}
if (thisProductionParameters) {
for (let i = 0; i < thisProductionParameterCount; i++) {
const thisProductionParameter = thisProductionParameters[i];
const thisProductionParameterName = thisProductionParameter.name;
const thisProductionParameterNameText = thisProductionParameterName.text;
if (thisProductionParameterNameText && !firstProductionParameterNames.has(thisProductionParameterNameText)) {
this.reportError(firstProduction, Diagnostics.Production_0_is_missing_parameter_1_All_definitions_of_production_0_must_specify_the_same_formal_parameters, thisProductionNameText, thisProductionParameterNameText);
}
}
}
}
private checkGrammarProduction(node: Production): boolean {
if (!node.colonToken) {
return this.reportGrammarError(node, node.parameterList?.end ?? node.name.end, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken));
}
if (!node.body) {
return this.reportGrammarError(node, node.colonToken.end, Diagnostics._0_expected, formatList([
SyntaxKind.OneOfList,
SyntaxKind.RightHandSide,
]));
}
switch (node.body.kind) {
case SyntaxKind.OneOfList:
case SyntaxKind.RightHandSide:
case SyntaxKind.RightHandSideList:
break;
default:
return this.reportGrammarError(node, node.colonToken.end, Diagnostics._0_expected, formatList([
SyntaxKind.OneOfList,
SyntaxKind.RightHandSide,
]));
}
return this.reportInvalidHtmlTrivia(node.name.trailingHtmlTrivia)
|| this.reportInvalidHtmlTrivia(node.colonToken.leadingHtmlTrivia)
|| this.reportInvalidHtmlTrivia(node.colonToken.trailingHtmlTrivia);
}
private checkParameterList(node: ParameterList): void {
this.checkGrammarParameterList(node);
if (node.elements) {
for (const element of node.elements) {
this.checkParameter(element);
}
}
}
private checkGrammarParameterList(node: ParameterList) {
if (!node.openBracketToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OpenBracketToken));
}
if ((node.elements?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.openBracketToken.end, Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
if (!node.closeBracketToken) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBracketToken));
}
return this.reportInvalidHtmlTrivia(node.leadingHtmlTrivia)
|| this.reportInvalidHtmlTrivia(node.trailingHtmlTrivia);
}
private checkParameter(node: Parameter): void {
this.reportInvalidHtmlTrivia(node.leadingHtmlTrivia) || this.reportInvalidHtmlTrivia(node.trailingHtmlTrivia);
this.checkIdentifier(node.name);
}
private checkOneOfList(node: OneOfList): void {
this.checkGrammarOneOfList(node);
if (node.terminals) {
const terminalSet = new Set<string>();
for (const terminal of node.terminals) {
const text = terminal.text;
if (text) {
if (terminalSet.has(text)) {
this.reportError(terminal, Diagnostics.Duplicate_terminal_0_, text);
}
else {
terminalSet.add(text);
this.checkTerminalLiteral(terminal);
}
}
}
}
}
private checkGrammarOneOfList(node: OneOfList): boolean {
if (!node.oneKeyword) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OneKeyword));
}
if (!node.ofKeyword) {
return this.reportGrammarError(node, node.oneKeyword.end, Diagnostics._0_expected, tokenToString(SyntaxKind.OfKeyword));
}
if ((node.terminals?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.ofKeyword.end, Diagnostics._0_expected, tokenToString(SyntaxKind.TerminalLiteral));
}
return false;
}
private checkRightHandSideList(node: RightHandSideList): void {
this.checkGrammarRightHandSideList(node);
if (node.elements) {
for (const element of node.elements) {
this.checkRightHandSide(element);
}
}
}
private checkGrammarRightHandSideList(node: RightHandSideList): boolean {
if (!node.elements || node.elements.length === 0) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.TerminalLiteral,
SyntaxKind.Identifier,
SyntaxKind.OpenBracketToken
]));
}
// if (!node.closeIndentToken) {
// return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.DedentToken));
// }
return false;
}
private checkRightHandSide(node: RightHandSide): void {
this.checkGrammarRightHandSide(node);
if (node.constraints) {
this.checkConstraints(node.constraints);
}
if (node.head) {
this.checkSymbolSpan(node.head);
}
if (node.reference) {
this.checkLinkReference(node.reference);
}
}
private checkGrammarRightHandSide(node: RightHandSide): boolean {
if (!node.head) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([SyntaxKind.GreaterThanToken, SyntaxKind.OpenBracketToken, SyntaxKind.Identifier, SyntaxKind.TerminalLiteral, SyntaxKind.UnicodeCharacterLiteral]));
}
return false;
}
private checkLinkReference(node: LinkReference) {
this.checkGrammarLinkReference(node);
}
private checkGrammarLinkReference(node: LinkReference): boolean {
if (!node.text) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, "string");
}
return false;
}
private checkConstraints(node: Constraints): void {
this.checkGrammarConstraints(node);
if (node.elements) {
for (const element of node.elements) {
this.checkArgument(element);
}
}
}
private checkGrammarConstraints(node: Constraints): boolean {
if ((node.elements?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.openBracketToken.end, Diagnostics._0_expected, formatList([SyntaxKind.TildeToken, SyntaxKind.PlusToken]));
}
if (!node.closeBracketToken) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBracketToken));
}
return false;
}
private checkSymbolSpan(node: SymbolSpan): void {
this.checkGrammarSymbolSpan(node);
this.checkSymbolSpanOrHigher(node.symbol);
if (node.next) {
this.checkSymbolSpanRest(node.next);
}
}
private checkGrammarSymbolSpan(node: SymbolSpan): boolean {
if (!node.symbol) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, formatList([
SyntaxKind.UnicodeCharacterLiteral,
SyntaxKind.TerminalLiteral,
SyntaxKind.Identifier,
SyntaxKind.OpenBracketToken,
SyntaxKind.Prose
]));
}
if (node.next && node.symbol.kind === SyntaxKind.Prose) {
return this.reportGrammarError(node, node.symbol.end, Diagnostics._0_expected, "«line terminator»");
}
return false;
}
private checkSymbolSpanOrHigher(node: LexicalSymbol): void {
if (node.kind === SyntaxKind.Prose) {
this.checkProse(<Prose>node);
return;
}
this.checkSymbolOrHigher(node);
}
private checkProse(node: Prose): void {
if (node.fragments) {
for (const fragment of node.fragments) {
this.checkProseFragment(fragment);
}
}
}
private checkSymbolSpanRest(node: SymbolSpan): void {
this.checkGrammarSymbolSpanRest(node);
this.checkSymbolOrHigher(node.symbol);
if (node.next) {
this.checkSymbolSpanRest(node.next);
}
}
private checkGrammarSymbolSpanRest(node: SymbolSpan): boolean {
if (!node.symbol) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, formatList([
SyntaxKind.UnicodeCharacterLiteral,
SyntaxKind.TerminalLiteral,
SyntaxKind.Identifier,
SyntaxKind.OpenBracketToken,
"«line terminator»"
]));
}
if (node.symbol.kind === SyntaxKind.Prose) {
return this.reportGrammarError(node, node.symbol.getStart(this._sourceFile), Diagnostics._0_expected, "«line terminator»");
}
if (node.next?.symbol.kind === SyntaxKind.Prose) {
return this.reportGrammarError(node, node.symbol.end, Diagnostics._0_expected, "«line terminator»");
}
return false;
}
private checkSymbolOrHigher(node: LexicalSymbol): void {
if (isAssertion(node)) {
this.checkAssertion(<Assertion>node);
return;
}
this.checkButNotSymbolOrHigher(node);
}
private checkAssertion(node: Assertion): void {
switch (node.kind) {
case SyntaxKind.EmptyAssertion:
this.checkEmptyAssertion(<EmptyAssertion>node);
break;
case SyntaxKind.LookaheadAssertion:
this.checkLookaheadAssertion(<LookaheadAssertion>node);
break;
case SyntaxKind.LexicalGoalAssertion:
this.checkLexicalGoalAssertion(<LexicalGoalAssertion>node);
break;
case SyntaxKind.NoSymbolHereAssertion:
this.checkNoSymbolHereAssertion(<NoSymbolHereAssertion>node);
break;
case SyntaxKind.ProseAssertion:
this.checkProseAssertion(<ProseAssertion>node);
break;
case SyntaxKind.InvalidAssertion:
this.reportInvalidAssertion(<Assertion>node);
break;
}
}
private checkGrammarAssertionHead(node: Assertion): boolean {
if (!node.openBracketToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OpenBracketToken));
}
return false;
}
private checkGrammarAssertionTail(node: Assertion): boolean {
if (!node.closeBracketToken) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBracketToken));
}
return false;
}
private checkEmptyAssertion(node: EmptyAssertion): void {
this.checkGrammarAssertionHead(node) || this.checkGrammarEmptyAssertion(node) || this.checkGrammarAssertionTail(node);
}
private checkGrammarEmptyAssertion(node: EmptyAssertion) {
if (!node.emptyKeyword) {
return this.reportGrammarError(node, node.openBracketToken.end, Diagnostics._0_expected, tokenToString(SyntaxKind.EmptyKeyword, /*quoted*/ true));
}
}
private checkLookaheadAssertion(node: LookaheadAssertion): void {
this.checkGrammarAssertionHead(node) || this.checkGrammarLookaheadAssertion(node) || this.checkGrammarAssertionTail(node);
if (node.lookahead) {
if (node.lookahead.kind === SyntaxKind.SymbolSet) {
this.checkSymbolSet(<SymbolSet>node.lookahead);
return;
}
this.checkSymbolSpanRest(<SymbolSpan>node.lookahead);
}
}
private checkGrammarLookaheadAssertion(node: LookaheadAssertion): boolean {
if (!node.lookaheadKeyword) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, tokenToString(SyntaxKind.LookaheadKeyword, /*quoted*/ true));
}
if (!node.operatorToken) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.EqualsToken,
SyntaxKind.EqualsEqualsToken,
SyntaxKind.ExclamationEqualsToken,
SyntaxKind.LessThanMinusToken,
SyntaxKind.LessThanExclamationToken
]));
}
switch (node.operatorToken.kind) {
case SyntaxKind.EqualsToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.NotEqualToToken:
case SyntaxKind.LessThanMinusToken:
case SyntaxKind.ElementOfToken:
case SyntaxKind.LessThanExclamationToken:
case SyntaxKind.NotAnElementOfToken:
break;
default:
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.EqualsToken,
SyntaxKind.EqualsEqualsToken,
SyntaxKind.ExclamationEqualsToken,
SyntaxKind.LessThanMinusToken,
SyntaxKind.LessThanExclamationToken
]));
}
if (!node.lookahead) {
switch (node.operatorToken.kind) {
case SyntaxKind.EqualsToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.NotEqualToToken:
return this.reportGrammarError(node, node.operatorToken.end, Diagnostics._0_expected, tokenToString(SyntaxKind.TerminalLiteral));
case SyntaxKind.LessThanMinusToken:
case SyntaxKind.ElementOfToken:
case SyntaxKind.LessThanExclamationToken:
case SyntaxKind.NotAnElementOfToken:
return this.reportGrammarError(node, node.operatorToken.end, Diagnostics._0_expected, formatList([SyntaxKind.OpenBraceToken, SyntaxKind.Nonterminal]));
}
}
switch (node.operatorToken.kind) {
case SyntaxKind.EqualsToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.NotEqualToToken:
if (!node.lookahead || !isTerminalSpan(node.lookahead)) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.TerminalLiteral,
SyntaxKind.UnicodeCharacterLiteral
]));
}
break;
case SyntaxKind.LessThanMinusToken:
case SyntaxKind.ElementOfToken:
case SyntaxKind.LessThanExclamationToken:
case SyntaxKind.NotAnElementOfToken:
if (!node.lookahead || !isNonterminalOrSymbolSet(node.lookahead)) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.OpenBraceToken,
SyntaxKind.Nonterminal
]));
}
break;
}
return false;
function isTerminalSpan(node: SymbolSpan | SymbolSet) {
while (node.kind === SyntaxKind.SymbolSpan) {
switch (node.symbol.kind) {
case SyntaxKind.Terminal:
if (!node.next) return true;
node = node.next;
break;
default:
return false;
}
}
return false;
}
function isNonterminalOrSymbolSet(node: SymbolSpan | SymbolSet) {
return node.kind === SyntaxKind.SymbolSpan
? node.symbol.kind === SyntaxKind.Nonterminal
: node.kind === SyntaxKind.SymbolSet;
}
}
private checkSymbolSet(node: SymbolSet): void {
this.checkGrammarSymbolSet(node);
if (node.elements) {
for (const element of node.elements) {
this.checkSymbolSpanRest(element);
}
}
}
private checkGrammarSymbolSet(node: SymbolSet): boolean {
if (!node.openBraceToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OpenBraceToken));
}
if ((node.elements?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.openBraceToken.end, Diagnostics._0_expected, formatList([
SyntaxKind.Identifier,
SyntaxKind.TerminalLiteral,
SyntaxKind.UnicodeCharacterLiteral
]));
}
if (!node.closeBraceToken) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
}
return false;
}
private checkLexicalGoalAssertion(node: LexicalGoalAssertion): void {
this.checkGrammarAssertionHead(node) || this.checkGrammarLexicalGoalAssertion(node) || this.checkGrammarAssertionTail(node);
if (node.symbol) {
this.checkIdentifier(node.symbol);
}
}
private checkGrammarLexicalGoalAssertion(node: LexicalGoalAssertion): boolean {
if (!node.lexicalKeyword) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.LexicalKeyword));
}
if (!node.goalKeyword) {
return this.reportGrammarError(node, node.lexicalKeyword.end, Diagnostics._0_expected, tokenToString(SyntaxKind.GoalKeyword));
}
if (!node.symbol) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
return false;
}
private checkNoSymbolHereAssertion(node: NoSymbolHereAssertion): void {
this.checkGrammarAssertionHead(node) || this.checkGrammarNoSymbolHereAssertion(node) || this.checkGrammarAssertionTail(node);
if (node.symbols) {
for (const symbol of node.symbols) {
this.checkPrimarySymbol(symbol);
}
}
}
private checkGrammarNoSymbolHereAssertion(node: NoSymbolHereAssertion): boolean {
if (!node.noKeyword) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.NoKeyword));
}
if ((node.symbols?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.noKeyword.end, Diagnostics._0_expected, formatList([
SyntaxKind.Identifier,
SyntaxKind.TerminalLiteral,
SyntaxKind.UnicodeCharacterLiteral
]));
}
if (!node.hereKeyword) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.HereKeyword));
}
return false;
}
private checkProseAssertion(node: ProseAssertion): void {
this.checkGrammarProseAssertionHead(node) || this.checkGrammarAssertionTail(node);
if (node.fragments) {
for (const fragment of node.fragments) {
this.checkProseFragment(fragment);
}
}
}
private checkGrammarProseAssertionHead(node: Assertion): boolean {
if (!node.openBracketToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OpenBracketGreaterThanToken));
}
return false;
}
private checkProseFragment(fragment: ProseFragment): void {
switch (fragment.kind) {
case SyntaxKind.Nonterminal:
this.checkNonterminal(<Nonterminal>fragment, /*allowOptional*/ false, /*allowArguments*/ false);
break;
case SyntaxKind.Terminal:
this.checkTerminal(<Terminal>fragment, /*allowOptional*/ false);
break;
case SyntaxKind.ProseFull:
case SyntaxKind.ProseHead:
case SyntaxKind.ProseMiddle:
case SyntaxKind.ProseTail:
this.checkProseFragmentLiteral(<ProseFragmentLiteral>fragment);
break;
}
}
private checkProseFragmentLiteral(node: ProseFragmentLiteral): void {
if (!node.text) {
this.reportGrammarErrorForNode(node, Diagnostics._0_expected, tokenToString(SyntaxKind.UnicodeCharacterLiteral));
}
}
private reportInvalidAssertion(node: Assertion): void {
if (this.checkGrammarAssertionHead(node)) {
return;
}
this.reportGrammarError(node, node.openBracketToken.end, Diagnostics._0_expected, formatList([
SyntaxKind.LookaheadKeyword,
SyntaxKind.LexicalKeyword,
SyntaxKind.NoKeyword,
SyntaxKind.TildeToken,
SyntaxKind.PlusToken
]));
}
private checkButNotSymbolOrHigher(node: LexicalSymbol) {
if (node.kind === SyntaxKind.ButNotSymbol) {
this.checkButNotSymbol(<ButNotSymbol>node);
return;
}
this.checkUnarySymbolOrHigher(node);
}
private checkButNotSymbol(node: ButNotSymbol): void {
this.checkGrammarButNotSymbol(node);
if (node.left) this.checkUnarySymbolOrHigher(node.left);
if (node.right) this.checkUnarySymbolOrHigher(node.right);
}
private checkGrammarButNotSymbol(node: ButNotSymbol): boolean {
if (!node.butKeyword) {
return this.reportGrammarErrorForNodeOrPos(node, node.notKeyword || node.right, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.ButKeyword));
}
if (!node.notKeyword) {
return this.reportGrammarErrorForNodeOrPos(node, node.right, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.NotKeyword));
}
if (!node.right) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, formatList([
SyntaxKind.Identifier,
SyntaxKind.TerminalLiteral,
SyntaxKind.UnicodeCharacterLiteral,
SyntaxKind.OneKeyword
]));
}
return false;
}
private checkUnarySymbolOrHigher(node: LexicalSymbol) {
if (node.kind === SyntaxKind.OneOfSymbol) {
this.checkOneOfSymbol(<OneOfSymbol>node);
return;
}
this.checkOptionalSymbolOrHigher(node);
}
private checkOneOfSymbol(node: OneOfSymbol): void {
this.checkGrammarOneOfSymbol(node);
if (node.symbols) {
for (const symbol of node.symbols) {
this.checkPrimarySymbol(symbol);
}
}
}
private checkGrammarOneOfSymbol(node: OneOfSymbol): boolean {
if (!node.oneKeyword) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OneKeyword));
}
if (!node.ofKeyword) {
return this.reportGrammarError(node, node.oneKeyword.end, Diagnostics._0_expected, tokenToString(SyntaxKind.OfKeyword));
}
if ((node.symbols?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, formatList([
SyntaxKind.Identifier,
SyntaxKind.TerminalLiteral,
SyntaxKind.UnicodeCharacterLiteral
]));
}
return false;
}
private checkOptionalSymbolOrHigher(node: LexicalSymbol): void {
this.checkPrimarySymbol(node, true);
}
private checkPrimarySymbol(node: LexicalSymbol, allowOptional?: boolean): void {
switch (node.kind) {
case SyntaxKind.Terminal:
this.checkTerminal(<Terminal>node, allowOptional);
break;
case SyntaxKind.UnicodeCharacterRange:
this.checkUnicodeCharacterRange(<UnicodeCharacterRange>node);
break;
case SyntaxKind.Nonterminal:
this.checkNonterminal(<Nonterminal>node, allowOptional, /*allowArguments*/ true);
break;
case SyntaxKind.PlaceholderSymbol:
this.checkPlaceholder(<PlaceholderSymbol>node);
break;
default:
this.reportInvalidSymbol(<LexicalSymbol>node);
break;
}
}
private checkGrammarNonTerminal(node: Nonterminal, allowOptional: boolean, allowArguments: boolean) {
if (this.checkGrammarOptionalSymbol(node, allowOptional)) {
return true;
}
if (!allowArguments && node.argumentList) {
return this.reportGrammarErrorForNode(node.argumentList, Diagnostics.Unexpected_token_0_, tokenToString(node.argumentList.openBracketToken.kind));
}
return false;
}
private checkGrammarOptionalSymbol(node: OptionalSymbol, allowOptional: boolean) {
if (node.questionToken) {
if (!allowOptional || node.questionToken.kind !== SyntaxKind.QuestionToken) {
return this.reportGrammarErrorForNode(node.questionToken, Diagnostics.Unexpected_token_0_, tokenToString(node.questionToken.kind));
}
}
return false;
}
private checkTerminal(node: Terminal, allowOptional: boolean = false): void {
this.checkGrammarOptionalSymbol(node, allowOptional);
switch (node.literal.kind) {
case SyntaxKind.TerminalLiteral:
this.checkTerminalLiteral(node.literal);
break;
case SyntaxKind.UnicodeCharacterLiteral:
this.checkUnicodeCharacterLiteral(node.literal);
break;
}
}
private checkTerminalLiteral(node: TerminalLiteral) {
this.checkGrammarTerminalLiteral(node);
}
private checkGrammarTerminalLiteral(node: TerminalLiteral): boolean {
if (!node.text) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, tokenToString(SyntaxKind.TerminalLiteral));
}
return false;
}
private checkGrammarUnicodeCharacterRange(node: UnicodeCharacterRange): boolean {
if (!node.left) {
return this.reportGrammarErrorForNode(node.throughKeyword || node.right || node, Diagnostics._0_expected, tokenToString(SyntaxKind.UnicodeCharacterLiteral));
}
if (!node.throughKeyword) {
return this.reportGrammarErrorForNode(node.right || node, Diagnostics._0_expected, tokenToString(SyntaxKind.ThroughKeyword));
}
if (!node.right) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.UnicodeCharacterLiteral));
}
return false;
}
private checkUnicodeCharacterRange(node: UnicodeCharacterRange): void {
this.checkGrammarUnicodeCharacterRange(node);
this.checkUnicodeCharacterLiteral(node.left);
this.checkUnicodeCharacterLiteral(node.right);
}
private checkUnicodeCharacterLiteral(node: UnicodeCharacterLiteral): void {
this.checkGrammarUnicodeCharacterLiteral(node);
}
private checkGrammarUnicodeCharacterLiteral(node: UnicodeCharacterLiteral): boolean {
if (!node.text) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, tokenToString(SyntaxKind.UnicodeCharacterLiteral));
}
return false;
}
private checkPlaceholder(node: PlaceholderSymbol): void {
}
private checkNonterminal(node: Nonterminal, allowOptional: boolean = false, allowArguments: boolean = true): void {
this.checkGrammarNonTerminal(node, allowOptional, allowArguments);
if (this.getDefine(node, "noStrictParametricProductions") || !allowArguments) {
this.checkNonterminalNonStrict(node);
}
else {
this.checkNonterminalStrict(node);
}
}
private checkNonterminalNonStrict(node: Nonterminal): void {
this.checkIdentifier(node.name);
if (node.argumentList) {
this.checkArgumentList(node.argumentList);
}
}
private checkNonterminalStrict(node: Nonterminal): void {
const nonterminalName = node.name;
const productionSymbol = this.checkIdentifier(nonterminalName);
if (productionSymbol) {
const production = <Production>this._bindings.getDeclarations(productionSymbol)[0];
const parameterListElements = production.parameterList?.elements;
const argumentListElements = node.argumentList?.elements;
const nameSet = new Set<string>();
// Check each argument has a matching parameter.
if (argumentListElements) {
for (let i = 0; i < argumentListElements.length; i++) {
const argumentName = argumentListElements[i].name;
if (argumentName) {
const argumentNameText = argumentName.text;
if (argumentNameText) {
if (nameSet.has(argumentNameText)) {
this.reportError(argumentName, Diagnostics.Argument_0_cannot_be_specified_multiple_times, argumentNameText);
}
else {
nameSet.add(argumentNameText);
const parameterSymbol = this.resolveSymbol(production, argumentNameText, SymbolKind.Parameter);
if (!parameterSymbol) {
this.reportError(argumentName, Diagnostics.Production_0_does_not_have_a_parameter_named_1_, productionSymbol.name, argumentNameText);
}
}
}
}
}
}
// Check each parameter has a matching argument.
if (parameterListElements) {
for (let i = 0; i < parameterListElements.length; i++) {
const parameterNameText = parameterListElements[i].name?.text;
if (parameterNameText && !nameSet.has(parameterNameText)) {
this.reportError(nonterminalName, Diagnostics.There_is_no_argument_given_for_parameter_0_, parameterNameText);
}
}
}
}
if (node.argumentList) {
this.checkArgumentList(node.argumentList);
}
}
private checkArgumentList(node: ArgumentList): void {
this.checkGrammarArgumentList(node);
if (node.elements) {
for (const element of node.elements) {
this.checkArgument(element);
}
}
}
private checkGrammarArgumentList(node: ArgumentList): boolean {
if (!node.openBracketToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.OpenBracketToken));
}
if ((node.elements?.length ?? 0) <= 0) {
return this.reportGrammarError(node, node.openBracketToken.end, Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
if (!node.closeBracketToken) {
return this.reportGrammarError(node, node.end, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBracketToken));
}
return false;
}
private checkArgument(node: Argument): void {
this.checkGrammarArgument(node);
if (node.name) this.checkIdentifier(node.name);
}
private checkGrammarArgument(node: Argument): boolean {
const parent = this._bindings.getParent(node);
if (parent?.kind === SyntaxKind.Constraints) {
if (!node.operatorToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, formatList([SyntaxKind.PlusToken, SyntaxKind.TildeToken]));
}
if (node.operatorToken.kind !== SyntaxKind.PlusToken
&& node.operatorToken.kind !== SyntaxKind.TildeToken) {
return this.reportGrammarErrorForNode(node.operatorToken, Diagnostics.Unexpected_token_0_, tokenToString(node.operatorToken.kind));
}
}
else {
if (node.operatorToken
&& node.operatorToken.kind !== SyntaxKind.QuestionToken
&& node.operatorToken.kind !== SyntaxKind.PlusToken
&& node.operatorToken.kind !== SyntaxKind.TildeToken) {
return this.reportGrammarErrorForNode(node.operatorToken, Diagnostics.Unexpected_token_0_, tokenToString(node.operatorToken.kind));
}
if (!node.operatorToken) {
return this.reportGrammarError(node, node.getStart(this._sourceFile), Diagnostics._0_expected, formatList([SyntaxKind.QuestionToken, SyntaxKind.PlusToken, SyntaxKind.TildeToken]));
}
}
if (!node.name) {
return this.reportGrammarError(node, node.operatorToken ? node.operatorToken.end : node.getStart(this._sourceFile), Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
return false;
}
private reportInvalidSymbol(node: LexicalSymbol): void {
this.reportGrammarErrorForNode(node, Diagnostics._0_expected, formatList([
SyntaxKind.TerminalLiteral,
SyntaxKind.Identifier,
SyntaxKind.OpenBracketToken,
SyntaxKind.OneKeyword
]));
}
private markSymbolAsReferenced(symbol: Symbol | undefined) {
if (symbol) {
this.getSymbolLinks(symbol, /*create*/ true).isReferenced = true;
}
}
private resolveIdentifier(node: Identifier, reportErrors?: boolean): Symbol | undefined {
let symbol = reportErrors ? undefined : this._bindings.getSymbol(node);
if (!symbol && node.text) {
const parent = this._bindings.getParent(node);
if (parent) {
switch (parent.kind) {
case SyntaxKind.Parameter:
symbol ??= this.resolveSymbol(node, node.text, SymbolKind.Parameter);
if (reportErrors) {
let declarationSymbol = this._bindings.getSymbol(parent);
if (declarationSymbol !== symbol) {
this.reportError(node, Diagnostics.Duplicate_identifier_0_, node.text);
}
}
this._bindings._setSymbol(node, symbol);
return symbol;
case SyntaxKind.Production:
symbol = this._bindings.getSymbol(parent);
this._bindings._setSymbol(node, symbol);
return symbol;
case SyntaxKind.LookaheadAssertion:
case SyntaxKind.Nonterminal:
if (!symbol) {
symbol = this.resolveSymbol(node, node.text, SymbolKind.Production, reportErrors ? Diagnostics.Cannot_find_name_0_ : undefined);
this.markSymbolAsReferenced(symbol);
}
break;
case SyntaxKind.Argument:
const argument = <Argument>parent;
if (argument.operatorToken?.kind === SyntaxKind.QuestionToken) {
symbol ??= this.resolveSymbol(node, node.text, SymbolKind.Parameter);
if (!symbol && reportErrors) {
const production = <Production>this._bindings.getAncestor(argument, SyntaxKind.Production);
this.reportError(node, Diagnostics.Production_0_does_not_have_a_parameter_named_1_, production.name.text, node.text);
}
this.markSymbolAsReferenced(symbol);
}
else {
// get the symbol of the parameter of the target production
const nonterminal = <Nonterminal | undefined>this._bindings.getAncestor(parent, SyntaxKind.Nonterminal);
if (nonterminal?.name?.text) {
const productionSymbol = this.resolveSymbol(node, nonterminal.name.text, SymbolKind.Production);
if (productionSymbol) {
const production = <Production>this._bindings.getDeclarations(productionSymbol)[0];
symbol ??= this.resolveSymbol(production, node.text, SymbolKind.Parameter);
if (!symbol && reportErrors) {
this.reportError(node, Diagnostics.Production_0_does_not_have_a_parameter_named_1_, production.name.text, node.text);
}
}
}
else {
const constraints = <Constraints | undefined>this._bindings.getAncestor(parent, SyntaxKind.Constraints);
if (constraints) {
const production = <Production>this._bindings.getAncestor(constraints, SyntaxKind.Production);
if (!symbol) {
symbol = this.resolveSymbol(production, node.text, SymbolKind.Parameter);
this.markSymbolAsReferenced(symbol);
}
if (!symbol && reportErrors) {
this.reportError(node, Diagnostics.Production_0_does_not_have_a_parameter_named_1_, production.name.text, node.text);
}
}
}
}
break;
}
this._bindings._setSymbol(node, symbol);
}
}
return symbol;
}
private checkIdentifier(node: Identifier): Symbol | undefined {
this.checkGrammarIdentifier(node);
return this.resolveIdentifier(node, /*reportErrors*/ true);
}
private checkGrammarIdentifier(node: Identifier) {
if (!node.text) {
return this.reportGrammarErrorForNode(node, Diagnostics._0_expected, tokenToString(SyntaxKind.Identifier));
}
return false;
}
private getNodeLinks(node: Node, create: true): NodeLinks;
private getNodeLinks(node: Node, create?: boolean): NodeLinks | undefined;
private getNodeLinks(node: Node, create?: boolean) {
let links = this._nodeLinks?.get(node);
if (!links && create) (this._nodeLinks ??= new Map()).set(node, links = new NodeLinks());
return links;
}
private getSymbolLinks(symbol: Symbol, create: true): SymbolLinks;
private getSymbolLinks(symbol: Symbol, create?: boolean): SymbolLinks | undefined;
private getSymbolLinks(symbol: Symbol, create?: boolean) {
let links = this._symbolLinks?.get(symbol);
if (!links && create) (this._symbolLinks ??= new Map()).set(symbol, links = new SymbolLinks());
return links;
}
private resolveSymbol(location: Node, name: string, meaning: SymbolKind, diagnosticMessage?: Diagnostic): Symbol | undefined {
const result = this._bindings.resolveSymbol(location, name, meaning);
if (!result && diagnosticMessage) {
this.reportError(location, diagnosticMessage, name);
}
return result;
}
private reportError(location: Node, diagnosticMessage: Diagnostic, arg0?: any, arg1?: any, arg2?: any) {
const sourceFile = this._bindings.getSourceFile(location) ?? this._sourceFile;
if (sourceFile !== this._sourceFile) {
this._diagnostics.setSourceFile(sourceFile);
this._diagnostics.reportNode(sourceFile, location, diagnosticMessage, arg0, arg1, arg2);
this._diagnostics.setSourceFile(this._sourceFile);
}
else {
this._diagnostics.reportNode(sourceFile, location, diagnosticMessage, arg0, arg1, arg2);
}
}
private reportGrammarError(context: Node, pos: number, diagnosticMessage: Diagnostic, arg0?: any, arg1?: any, arg2?: any) {
const sourceFile = this._bindings.getSourceFile(context) ?? this._sourceFile;
if (sourceFile !== this._sourceFile) {
this._diagnostics.setSourceFile(sourceFile);
this._diagnostics.report(pos, diagnosticMessage, arg0, arg1, arg2);
this._diagnostics.setSourceFile(this._sourceFile);
}
else {
this._diagnostics.report(pos, diagnosticMessage, arg0, arg1, arg2);
}
return true;
}
private reportGrammarErrorForNode(location: Node, diagnosticMessage: Diagnostic, arg0?: any, arg1?: any, arg2?: any) {
this.reportError(location, diagnosticMessage, arg0, arg1, arg2);
return true;
}
private reportGrammarErrorForNodeOrPos(context: Node, location: Node | undefined, pos: number, diagnosticMessage: Diagnostic, arg0?: any, arg1?: any, arg2?: any) {
return location
? this.reportGrammarErrorForNode(location, diagnosticMessage, arg0, arg1, arg2)
: this.reportGrammarError(context, pos, diagnosticMessage, arg0, arg1, arg2);
}
private reportInvalidHtmlTrivia(nodes: HtmlTrivia[] | undefined) {
if (nodes?.length) {
return this.reportGrammarErrorForNode(nodes[0], Diagnostics.HTML_trivia_not_allowed_here);
}
return false;
}
}
/** {@docCategory Check} */
export class Resolver {
public readonly bindings: BindingTable;
private _lineOffsetMap: LineOffsetMap | undefined;
constructor(bindings: BindingTable, lineOffsetMap?: LineOffsetMap) {
this.bindings = bindings;
this._lineOffsetMap = lineOffsetMap;
}
/**
* Gets the effective filename of a raw position within a source file, taking into account `@line` directives.
*/
public getEffectiveFilenameAtPosition(sourceFile: SourceFile, position: Position) {
return this._lineOffsetMap?.getEffectiveFilenameAtPosition(sourceFile, position) ?? sourceFile.filename;
}
/**
* Gets the effective position of a raw position within a source file, taking into account `@line` directives.
*/
public getEffectivePosition(sourceFile: SourceFile, position: Position) {
return this._lineOffsetMap?.getEffectivePosition(sourceFile, position) ?? position;
}
/**
* Gets the effective range of a raw range within a source file, taking into account `@line` directives.
*/
public getEffectiveRange(sourceFile: SourceFile, range: Range) {
return this._lineOffsetMap?.getEffectiveRange(sourceFile, range) ?? range;
}
/**
* Gets the filename of a parsed grammarkdown file for the provided effective filename and position, taking into account `@line` directives.
*/
public getRawFilenameAtEffectivePosition(filename: string, position: Position) {
return this._lineOffsetMap?.getRawFilenameAtEffectivePosition(filename, position);
}
/**
* Gets the position in a parsed grammarkdown file for the provided effective filename and position, taking into account `@line` directives.
*/
public getRawPositionFromEffectivePosition(filename: string, position: Position) {
return this._lineOffsetMap?.getRawPositionFromEffectivePosition(filename, position);
}
/**
* Gets the range in a parsed grammarkdown file for the provided effective filename and position, taking into account `@line` directives.
*/
public getRawRangeFromEffectiveRange(filename: string, range: Range) {
return this._lineOffsetMap?.getRawRangeFromEffectiveRange(filename, range);
}
/**
* Gets the parent `Node` for `node`.
*/
public getParent(node: Node): Node | undefined {
return this.bindings.getParent(node);
}
/**
* Creates a `NodeNavigator` pointing at `node`. Returns `undefined` if `node` does not have a `SourceFile` as an ancestor.
*/
public createNavigator(node: Node): NodeNavigator | undefined {
if (node.kind === SyntaxKind.SourceFile) {
return new NodeNavigator(<SourceFile>node);
}
else {
const parent = this.bindings.getParent(node);
if (parent) {
const navigator = this.createNavigator(parent);
if (navigator?.moveToFirstChild(child => child === node)) {
return navigator;
}
}
}
return undefined;
}
/**
* Gets the `SourceFile` of `node`, if it belongs to one.
*/
public getSourceFileOfNode(node: Node) {
return this.bindings.getAncestor(node, SyntaxKind.SourceFile) as SourceFile | undefined;
}
/**
* Gets the `Symbol` for `node`, if it has one.
*/
public getSymbolOfNode(node: Node | undefined) {
return this.bindings.getSymbol(node);
}
/**
* Resolves a `Symbol` for the provided `name` at the given `location` that has the provided `meaning`.
*/
public resolveSymbol(location: Node, name: string, meaning: SymbolKind): Symbol | undefined {
return this.bindings.resolveSymbol(location, name, meaning);
}
/**
* Gets the declarations for the provided identifier.
*/
public getDeclarations(node: Identifier): Declaration[];
/**
* Gets the declarations for `name` at the provided `location` that have the given `meaning`.
*/
public getDeclarations(name: string, meaning: SymbolKind.SourceFile, location: Node): SourceFile[];
/**
* Gets the declarations for `name` at the provided `location` that have the given `meaning`.
*/
public getDeclarations(name: string, meaning: SymbolKind.Production, location: Node): Production[];
/**
* Gets the declarations for `name` at the provided `location` that have the given `meaning`.
*/
public getDeclarations(name: string, meaning: SymbolKind.Parameter, location: Node): Parameter[];
/**
* Gets the declarations for `name` at the provided `location` that have the given `meaning`.
*/
public getDeclarations(name: string, meaning: SymbolKind, location: Node): Declaration[];
public getDeclarations(node: string | Identifier, meaning?: SymbolKind, location?: Node) {
let symbol: Symbol | undefined;
if (typeof node === "string") {
if (meaning === undefined) throw new TypeError("SymbolKind expected: meaning");
if (location === undefined) throw new TypeError("Node expected: location");
symbol = this.bindings.resolveSymbol(location, node, meaning);
}
else {
const parent = this.bindings.getParent(node);
symbol = this.bindings.getSymbol(node);
if (!symbol && node.text) {
symbol = this.bindings.resolveSymbol(node, node.text, getSymbolMeaning(parent));
}
}
if (symbol) {
return this.bindings.getDeclarations(symbol);
}
return [];
}
/**
* Gets the references to the provided identifier.
*/
public getReferences(node: Identifier): Node[];
/**
* Gets the references to `name` at the provided `location` that have the given `meaning`.
*/
public getReferences(name: string, meaning: SymbolKind, location: Node): Node[];
public getReferences(node: string | Identifier, meaning?: SymbolKind, location?: Node) {
let symbol: Symbol | undefined;
if (typeof node === "string") {
if (meaning === undefined) throw new TypeError("SymbolKind expected: meaning");
if (location === undefined) throw new TypeError("Node expected: location");
symbol = this.bindings.resolveSymbol(location, node, meaning);
}
else {
const parent = this.bindings.getParent(node);
if (parent) {
symbol = parent.kind === SyntaxKind.Parameter
? this.bindings.resolveSymbol(node, node.text, SymbolKind.Parameter)
: this.bindings.resolveSymbol(node, node.text, SymbolKind.Production);
}
}
if (symbol) {
return this.bindings.getReferences(symbol);
}
return [];
}
/**
* Get the link id for the `Production` to which the provided `node` resolves.
*/
public getProductionLinkId(node: Identifier): string | undefined {
const symbol = this.bindings.resolveSymbol(node, node.text, SymbolKind.Production);
return symbol?.name;
}
/**
* Gets the right-hand-side link id for the provided `RightHandSide`.
* @param includePrefix When `true`, prepends the production link id.
*/
public getRightHandSideLinkId(node: RightHandSide, includePrefix: boolean): string {
let linkId: string;
if (node.reference?.text) {
linkId = node.reference.text.replace(/[^a-z0-9]+/g, '-');
}
else {
const digest = new RightHandSideDigest();
linkId = digest.computeHash(node).toLowerCase();
}
if (includePrefix) {
const production = <Production>this.bindings.getAncestor(node, SyntaxKind.Production);
const productionId = this.getProductionLinkId(production.name);
return productionId + "-" + linkId;
}
return linkId;
}
}
class RightHandSideDigest {
private spaceRequested: boolean = false;
private writer!: StringWriter;
public computeHash(node: RightHandSide): string {
this.writer = new StringWriter("\n");
this.writeNode(node.constraints);
this.writeNode(node.head);
const hash = createHash("sha1");
hash.update(this.writer.toString(), "utf8");
const digest = hash.digest().toString("base64");
const digestUrlSafe = digest.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
return digestUrlSafe.slice(0, 8);
}
private writeNode(node: Node | undefined) {
if (!node) {
return;
}
switch (node.kind) {
case SyntaxKind.Constraints: this.writeConstraints(<Constraints>node); break;
case SyntaxKind.TerminalLiteral: this.writeTerminalLiteral(<TerminalLiteral>node); break;
case SyntaxKind.UnicodeCharacterLiteral: this.writeUnicodeCharacterLiteral(<UnicodeCharacterLiteral>node); break;
case SyntaxKind.Prose: this.writeProse(<Prose>node); break;
case SyntaxKind.Nonterminal: this.writeNonterminal(<Nonterminal>node); break;
case SyntaxKind.Terminal: this.writeTerminal(<Terminal>node); break;
case SyntaxKind.EmptyAssertion: this.writeEmptyAssertion(<EmptyAssertion>node); break;
case SyntaxKind.LexicalGoalAssertion: this.writeLexicalGoalAssertion(<LexicalGoalAssertion>node); break;
case SyntaxKind.LookaheadAssertion: this.writeLookaheadAssertion(<LookaheadAssertion>node); break;
case SyntaxKind.NoSymbolHereAssertion: this.writeNoSymbolHereAssertion(<NoSymbolHereAssertion>node); break;
case SyntaxKind.ProseAssertion: this.writeProseAssertion(<ProseAssertion>node); break;
case SyntaxKind.ProseFull: this.writeProseFragmentLiteral(<ProseFragmentLiteral>node); break;
case SyntaxKind.ProseHead: this.writeProseFragmentLiteral(<ProseFragmentLiteral>node); break;
case SyntaxKind.ProseMiddle: this.writeProseFragmentLiteral(<ProseFragmentLiteral>node); break;
case SyntaxKind.ProseTail: this.writeProseFragmentLiteral(<ProseFragmentLiteral>node); break;
case SyntaxKind.UnicodeCharacterRange: this.writeUnicodeCharacterRange(<UnicodeCharacterRange>node); break;
case SyntaxKind.ButNotSymbol: this.writeButNotSymbol(<ButNotSymbol>node); break;
case SyntaxKind.OneOfSymbol: this.writeOneOfSymbol(<OneOfSymbol>node); break;
case SyntaxKind.SymbolSpan: this.writeSymbolSpan(<SymbolSpan>node); break;
case SyntaxKind.SymbolSet: this.writeSymbolSet(<SymbolSet>node); break;
case SyntaxKind.ArgumentList: this.writeArgumentList(<ArgumentList>node); break;
case SyntaxKind.Argument: this.writeArgument(<Argument>node); break;
case SyntaxKind.Identifier: this.writeIdentifier(<Identifier>node); break;
default:
if ((node.kind >= SyntaxKind.FirstKeyword && node.kind <= SyntaxKind.LastKeyword) ||
(node.kind >= SyntaxKind.FirstPunctuation && node.kind <= SyntaxKind.LastPunctuation)) {
this.writeToken(node);
break;
}
else {
for (const child of node.children()) {
this.writeNode(child);
}
break;
}
}
}
private write(text: string | undefined) {
if (text) {
if (this.spaceRequested && this.writer.size > 0) {
this.spaceRequested = false;
this.writer.write(" ");
}
this.writer.write(text);
}
}
private writeToken(node: Node | undefined) {
if (node) {
this.write(tokenToString(node.kind));
this.spaceRequested = true;
}
}
private writeConstraints(node: Constraints) {
this.write("[");
if (node.elements) {
for (let i = 0; i < node.elements.length; ++i) {
if (i > 0) {
this.write(", ");
}
this.writeNode(node.elements[i]);
}
}
this.write("]");
this.spaceRequested = true;
}
private writeTerminal(node: Terminal) {
this.writeNode(node.literal);
this.spaceRequested = false;
this.writeNode(node.questionToken);
this.spaceRequested = true;
}
private writeTerminalLiteral(node: TerminalLiteral) {
this.write("`");
this.write(node.text);
this.write("`");
this.spaceRequested = true;
}
private writeUnicodeCharacterLiteral(node: UnicodeCharacterLiteral) {
this.write("<");
this.write(node.text);
this.write(">");
this.spaceRequested = true;
}
private writeProse(node: Prose) {
this.write("> ");
if (node.fragments) {
for (const fragment of node.fragments) {
this.writeNode(fragment);
}
}
}
private writeNonterminal(node: Nonterminal) {
this.writeNode(node.name);
this.writeNode(node.argumentList);
this.writeNode(node.questionToken);
this.spaceRequested = true;
}
private writeArgumentList(node: ArgumentList) {
this.write("[");
if (node.elements) {
for (let i = 0; i < node.elements.length; ++i) {
if (i > 0) {
this.write(", ");
}
this.writeNode(node.elements[i]);
}
}
this.write("]");
}
private writeArgument(node: Argument) {
this.writeNode(node.operatorToken);
this.writeNode(node.name);
}
private writeEmptyAssertion(node: EmptyAssertion) {
this.write("[empty]");
this.spaceRequested = true;
}
private writeLexicalGoalAssertion(node: LexicalGoalAssertion) {
this.write("[lexical goal ");
this.writeNode(node.symbol);
this.spaceRequested = false;
this.write("]");
this.spaceRequested = true;
}
private writeLookaheadAssertion(node: LookaheadAssertion) {
this.write("[lookahead ");
this.writeNode(node.operatorToken);
this.writeNode(node.lookahead);
this.spaceRequested = false;
this.write("]");
this.spaceRequested = true;
}
private writeNoSymbolHereAssertion(node: NoSymbolHereAssertion) {
this.write("[no ");
if (node.symbols) {
for (let i = 0; i < node.symbols.length; ++i) {
if (i > 0) {
this.write(" or ");
}
this.writeNode(node.symbols[i]);
this.spaceRequested = false;
}
}
this.write(" here]");
}
private writeProseAssertion(node: ProseAssertion) {
this.write("[>");
this.spaceRequested = false;
if (node.fragments) {
for (const fragment of node.fragments) {
if (fragment.kind === SyntaxKind.Identifier) {
this.write("|");
this.writeNode(fragment);
this.spaceRequested = false;
this.write("|");
}
else {
this.writeNode(fragment);
}
}
}
this.write("]");
this.spaceRequested = true;
}
private writeProseFragmentLiteral(node: ProseFragmentLiteral) {
this.write(node.text);
}
private writeUnicodeCharacterRange(node: UnicodeCharacterRange) {
this.writeNode(node.left);
this.writeNode(node.throughKeyword);
this.writeNode(node.right);
this.spaceRequested = true;
}
private writeButNotSymbol(node: ButNotSymbol) {
this.writeNode(node.left);
this.writeNode(node.butKeyword);
this.writeNode(node.notKeyword);
this.writeNode(node.right);
this.spaceRequested = true;
}
private writeOneOfSymbol(node: OneOfSymbol) {
this.write("one of ");
if (node.symbols) {
for (let i = 0; i < node.symbols.length; ++i) {
if (i > 0) {
this.write(" or ");
}
this.writeNode(node.symbols[i]);
this.spaceRequested = false;
}
this.spaceRequested = true;
}
}
private writeSymbolSpan(node: SymbolSpan) {
this.writeNode(node.symbol);
this.writeNode(node.next);
}
private writeSymbolSet(node: SymbolSet) {
this.write("{ ");
if (node.elements) {
for (let i = 0; i < node.elements.length; ++i) {
if (i > 0) {
this.write(", ");
}
this.writeNode(node.elements[i]);
this.spaceRequested = false;
}
}
this.write(" }");
this.spaceRequested = true;
}
private writeIdentifier(node: Identifier) {
this.write(node.text);
}
}
function isAssertion(node: LexicalSymbol) {
if (node) {
switch (node.kind) {
case SyntaxKind.EmptyAssertion:
case SyntaxKind.LookaheadAssertion:
case SyntaxKind.LexicalGoalAssertion:
case SyntaxKind.NoSymbolHereAssertion:
case SyntaxKind.ProseAssertion:
case SyntaxKind.InvalidAssertion:
return true;
}
}
return false;
}
function getSymbolMeaning(node: Node | undefined) {
if (node) {
switch (node.kind) {
case SyntaxKind.Parameter:
case SyntaxKind.Argument:
case SyntaxKind.Constraints:
return SymbolKind.Parameter;
}
}
return SymbolKind.Production;
} | the_stack |
import * as fs from "fs/promises";
import * as path from "path";
import * as plist from "plist";
import * as vscode from "vscode";
import configuration from "../configuration";
import { SwiftOutputChannel } from "../ui/SwiftOutputChannel";
import { execFile, execSwift, pathExists } from "../utilities/utilities";
import { Version } from "../utilities/version";
/**
* Contents of **Info.plist** on Windows.
*/
interface InfoPlist {
DefaultProperties: {
XCTEST_VERSION: string | undefined;
};
}
/**
* Stripped layout of `swift -print-target-info` output.
*/
interface SwiftTargetInfo {
compilerVersion: string;
target?: {
triple: string;
[name: string]: string | string[];
};
paths: {
runtimeLibraryPaths: string[];
[name: string]: string | string[];
};
[name: string]: string | object | undefined;
}
export class SwiftToolchain {
constructor(
public toolchainPath: string,
public swiftVersionString: string,
public swiftVersion: Version,
public runtimePath?: string,
private defaultTarget?: string,
private defaultSDK?: string,
private customSDK?: string,
public xcTestPath?: string
) {}
static async create(): Promise<SwiftToolchain> {
const toolchainPath = await this.getToolchainPath();
const targetInfo = await this.getSwiftTargetInfo();
const swiftVersion = await this.getSwiftVersion(targetInfo);
const runtimePath = await this.getRuntimePath(targetInfo);
const defaultSDK = await this.getDefaultSDK();
const customSDK = this.getCustomSDK();
const xcTestPath = await this.getXCTestPath(
targetInfo,
swiftVersion,
runtimePath,
customSDK ?? defaultSDK
);
return new SwiftToolchain(
toolchainPath,
targetInfo.compilerVersion,
swiftVersion,
runtimePath,
targetInfo.target?.triple,
defaultSDK,
customSDK,
xcTestPath
);
}
logDiagnostics(channel: SwiftOutputChannel) {
channel.logDiagnostic(`Toolchain Path: ${this.toolchainPath}`);
if (this.runtimePath) {
channel.logDiagnostic(`Runtime Library Path: ${this.runtimePath}`);
}
if (this.defaultTarget) {
channel.logDiagnostic(`Default Target: ${this.defaultTarget}`);
}
if (this.defaultSDK) {
channel.logDiagnostic(`Default SDK: ${this.defaultSDK}`);
}
if (this.customSDK) {
channel.logDiagnostic(`Custom SDK: ${this.customSDK}`);
}
if (this.xcTestPath) {
channel.logDiagnostic(`XCTest Path: ${this.xcTestPath}`);
}
}
/**
* @returns path to Toolchain folder
*/
private static async getToolchainPath(): Promise<string> {
if (configuration.path !== "") {
return path.dirname(path.dirname(configuration.path));
}
switch (process.platform) {
case "darwin": {
const { stdout } = await execFile("xcrun", ["--find", "swiftc"]);
const swiftc = stdout.trimEnd();
return path.dirname(path.dirname(path.dirname(swiftc)));
}
case "win32": {
const { stdout } = await execFile("where", ["swiftc"]);
const swiftc = stdout.trimEnd();
return path.dirname(path.dirname(path.dirname(swiftc)));
}
default: {
// use `type swift` to find `swift`. Run inside /bin/sh to ensure
// we get consistent output as different shells output a different
// format. Tried running with `-p` but that is not available in /bin/sh
const { stdout } = await execFile("/bin/sh", ["-c", "type swift"]);
const swiftMatch = /^swift is (.*)$/.exec(stdout.trimEnd());
if (swiftMatch) {
const swift = swiftMatch[1];
// swift may be a symbolic link
const realSwift = await fs.realpath(swift);
return path.dirname(path.dirname(path.dirname(realSwift)));
}
throw Error("Failed to find swift executable");
}
}
}
/**
* @param targetInfo swift target info
* @returns path to Swift runtime
*/
private static async getRuntimePath(targetInfo: SwiftTargetInfo): Promise<string | undefined> {
if (configuration.runtimePath !== "") {
return configuration.runtimePath;
} else if (process.platform === "win32") {
const { stdout } = await execFile("where", ["swiftCore.dll"]);
const swiftCore = stdout.trimEnd();
return swiftCore.length > 0 ? path.dirname(swiftCore) : undefined;
} else {
return targetInfo.paths.runtimeLibraryPaths.length > 0
? targetInfo.paths.runtimeLibraryPaths.join(":")
: undefined;
}
}
/**
* @returns path to default SDK
*/
private static async getDefaultSDK(): Promise<string | undefined> {
switch (process.platform) {
case "darwin": {
if (process.env.SDKROOT) {
return process.env.SDKROOT;
}
const { stdout } = await execFile("xcrun", ["--sdk", "macosx", "--show-sdk-path"]);
return path.join(stdout.trimEnd());
}
case "win32": {
return process.env.SDKROOT;
}
}
return undefined;
}
/**
* @returns path to custom SDK
*/
private static getCustomSDK(): string | undefined {
return configuration.sdk !== "" ? configuration.sdk : undefined;
}
/**
* @param targetInfo swift target info
* @param swiftVersion parsed swift version
* @param runtimePath path to Swift runtime
* @param sdkroot path to swift SDK
* @returns path to folder where xctest can be found
*/
private static async getXCTestPath(
targetInfo: SwiftTargetInfo,
swiftVersion: Version,
runtimePath: string | undefined,
sdkroot: string | undefined
): Promise<string | undefined> {
switch (process.platform) {
case "darwin": {
const { stdout } = await execFile("xcode-select", ["-p"]);
return path.join(stdout.trimEnd(), "usr", "bin");
}
case "win32": {
// look up runtime library directory for XCTest alternatively
const fallbackPath =
runtimePath !== undefined &&
(await pathExists(path.join(runtimePath, "XCTest.dll")))
? runtimePath
: undefined;
if (!sdkroot) {
return fallbackPath;
}
const platformPath = path.dirname(path.dirname(path.dirname(sdkroot)));
const platformManifest = path.join(platformPath, "Info.plist");
if ((await pathExists(platformManifest)) !== true) {
if (fallbackPath) {
return fallbackPath;
}
vscode.window.showWarningMessage(
"XCTest not found due to non-standardized library layout. Tests explorer won't work as expected."
);
return undefined;
}
const data = await fs.readFile(platformManifest, "utf8");
const infoPlist = plist.parse(data) as unknown as InfoPlist;
const version = infoPlist.DefaultProperties.XCTEST_VERSION;
if (!version) {
throw Error("Info.plist is missing the XCTEST_VERSION key.");
}
if (swiftVersion >= new Version(5, 7, 0)) {
let bindir: string;
const arch = targetInfo.target?.triple.split("-", 1)[0];
switch (arch) {
case "x86_64":
bindir = "bin64";
break;
case "i686":
bindir = "bin32";
break;
case "aarch64":
bindir = "bin64a";
break;
default:
throw Error(`unsupported architecture ${arch}`);
}
return path.join(
platformPath,
"Developer",
"Library",
`XCTest-${version}`,
"usr",
bindir
);
} else {
return path.join(
platformPath,
"Developer",
"Library",
`XCTest-${version}`,
"usr",
"bin"
);
}
}
}
return undefined;
}
/** @returns swift target info */
private static async getSwiftTargetInfo(): Promise<SwiftTargetInfo> {
try {
const { stdout } = await execSwift(["-print-target-info"]);
return JSON.parse(stdout.trimEnd()) as SwiftTargetInfo;
} catch {
throw Error("Cannot parse swift target info output.");
}
}
/**
* @param targetInfo swift target info
* @returns swift version object
*/
private static getSwiftVersion(targetInfo: SwiftTargetInfo): Version {
const match = targetInfo.compilerVersion.match(/Swift version ([\S]+)/);
let version: Version | undefined;
if (match) {
version = Version.fromString(match[1]);
}
return version ?? new Version(0, 0, 0);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
SyncMember,
SyncMembersListBySyncGroupOptionalParams,
SyncFullSchemaProperties,
SyncMembersListMemberSchemasOptionalParams,
SyncMembersGetOptionalParams,
SyncMembersGetResponse,
SyncMembersCreateOrUpdateOptionalParams,
SyncMembersCreateOrUpdateResponse,
SyncMembersDeleteOptionalParams,
SyncMembersUpdateOptionalParams,
SyncMembersUpdateResponse,
SyncMembersRefreshMemberSchemaOptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a SyncMembers. */
export interface SyncMembers {
/**
* Lists sync members in the given sync group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group.
* @param options The options parameters.
*/
listBySyncGroup(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
options?: SyncMembersListBySyncGroupOptionalParams
): PagedAsyncIterableIterator<SyncMember>;
/**
* Gets a sync member database schema.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
listMemberSchemas(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersListMemberSchemasOptionalParams
): PagedAsyncIterableIterator<SyncFullSchemaProperties>;
/**
* Gets a sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersGetOptionalParams
): Promise<SyncMembersGetResponse>;
/**
* Creates or updates a sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param parameters The requested sync member resource state.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
parameters: SyncMember,
options?: SyncMembersCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<SyncMembersCreateOrUpdateResponse>,
SyncMembersCreateOrUpdateResponse
>
>;
/**
* Creates or updates a sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param parameters The requested sync member resource state.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
parameters: SyncMember,
options?: SyncMembersCreateOrUpdateOptionalParams
): Promise<SyncMembersCreateOrUpdateResponse>;
/**
* Deletes a sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes a sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersDeleteOptionalParams
): Promise<void>;
/**
* Updates an existing sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param parameters The requested sync member resource state.
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
parameters: SyncMember,
options?: SyncMembersUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<SyncMembersUpdateResponse>,
SyncMembersUpdateResponse
>
>;
/**
* Updates an existing sync member.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param parameters The requested sync member resource state.
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
parameters: SyncMember,
options?: SyncMembersUpdateOptionalParams
): Promise<SyncMembersUpdateResponse>;
/**
* Refreshes a sync member database schema.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
beginRefreshMemberSchema(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersRefreshMemberSchemaOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Refreshes a sync member database schema.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param databaseName The name of the database on which the sync group is hosted.
* @param syncGroupName The name of the sync group on which the sync member is hosted.
* @param syncMemberName The name of the sync member.
* @param options The options parameters.
*/
beginRefreshMemberSchemaAndWait(
resourceGroupName: string,
serverName: string,
databaseName: string,
syncGroupName: string,
syncMemberName: string,
options?: SyncMembersRefreshMemberSchemaOptionalParams
): Promise<void>;
} | the_stack |
import { TypeData, TypeElement } from '@idraw/types';
import util from '@idraw/util';
import { LoaderEvent, TypeLoadData, TypeLoaderEventArgMap } from './loader-event';
import { filterScript } from './../util/filter';
const { loadImage, loadSVG, loadHTML } = util.loader;
const { deepClone } = util.data;
type Options = {
maxParallelNum: number
}
enum LoaderStatus {
FREE = 'free',
LOADING = 'loading',
COMPLETE = 'complete',
}
export default class Loader {
private _opts: Options;
private _event: LoaderEvent;
// private _patternMap: {[uuid: string]: CanvasPattern} = {}
private _currentLoadData: TypeLoadData = {};
private _currentUUIDQueue: string[] = [];
private _storageLoadData: TypeLoadData = {};
private _status: LoaderStatus = LoaderStatus.FREE;
private _waitingLoadQueue: Array<{
uuidQueue: string[],
loadData: TypeLoadData,
}> = [];
constructor(opts: Options) {
this._opts = opts;
this._event = new LoaderEvent();
this._waitingLoadQueue = [];
}
load(data: TypeData, changeResourceUUIDs: string[]): void {
const [uuidQueue, loadData] = this._resetLoadData(data, changeResourceUUIDs);
if (this._status === LoaderStatus.FREE || this._status === LoaderStatus.COMPLETE) {
this._currentUUIDQueue = uuidQueue;
this._currentLoadData = loadData;
this._loadTask();
} else if (this._status === LoaderStatus.LOADING && uuidQueue.length > 0) {
this._waitingLoadQueue.push({
uuidQueue,
loadData,
});
}
}
on<T extends keyof TypeLoaderEventArgMap>(
name: T,
callback: (arg: TypeLoaderEventArgMap[T]
) => void) {
this._event.on(name, callback);
}
off<T extends keyof TypeLoaderEventArgMap>(
name: T,
callback: (arg: TypeLoaderEventArgMap[T]
) => void) {
this._event.off(name, callback);
}
isComplete() {
return this._status === LoaderStatus.COMPLETE;
}
getContent(uuid: string): null | HTMLImageElement | HTMLCanvasElement {
if (this._storageLoadData[uuid]?.status === 'loaded') {
return this._storageLoadData[uuid].content;
}
return null;
}
// getPattern(
// elem: TypeElement<keyof TypeElemDesc>,
// opts?: {
// forceUpdate: boolean
// }
// ): null | CanvasPattern {
// if (this._patternMap[elem.uuid] ) {
// if (!(opts && opts.forceUpdate === true)) {
// return this._patternMap[elem.uuid];
// }
// }
// const item = this._currentLoadData[elem.uuid];
// if (item?.status === 'loaded') {
// const board = this._opts.board;
// const tempCanvas = board.createCanvas();
// const tempCtx = board.createContext(tempCanvas);
// const image = this.getContent(elem.uuid);
// tempCtx.drawImage(image, elem.x, elem.y, elem.w, elem.h);
// const canvas = board.createCanvas();
// const ctx = board.createContext(canvas);
// const pattern = ctx.createPattern(tempCanvas, 'no-repeat');
// if (pattern) this._patternMap[elem.uuid] = pattern;
// return pattern;
// }
// return null;
// }
private _resetLoadData(data: TypeData, changeResourceUUIDs: string[]): [string[], TypeLoadData] {
const loadData: TypeLoadData = {};
const uuidQueue: string[] = [];
const storageLoadData = this._storageLoadData;
// const currentUUIDs: string[] = []
// add new load-data
for (let i = data.elements.length - 1; i >= 0; i --) {
const elem = data.elements[i] as TypeElement<'image' | 'svg' | 'html'>;
// currentUUIDs.push(elem.uuid);
if (['image', 'svg', 'html', ].includes(elem.type)) {
if (!storageLoadData[elem.uuid]) {
loadData[elem.uuid] = this._createEmptyLoadItem(elem);
uuidQueue.push(elem.uuid);
} else {
if (changeResourceUUIDs.includes(elem.uuid)) {
loadData[elem.uuid] = this._createEmptyLoadItem(elem);
uuidQueue.push(elem.uuid);
}
// if (elem.type === 'image') {
// const _ele = elem as TypeElement<'image'>;
// if (_ele.desc.src !== storageLoadData[elem.uuid].source) {
// loadData[elem.uuid] = this._createEmptyLoadItem(elem);
// uuidQueue.push(elem.uuid);
// }
// } else if (elem.type === 'svg') {
// const _ele = elem as TypeElement<'svg'>;
// if (_ele.desc.svg !== storageLoadData[elem.uuid].source) {
// loadData[elem.uuid] = this._createEmptyLoadItem(elem);
// uuidQueue.push(elem.uuid);
// }
// } else if (elem.type === 'html') {
// const _ele = elem as TypeElement<'html'>;
// if (filterScript(_ele.desc.html) !== storageLoadData[elem.uuid].source) {
// loadData[elem.uuid] = this._createEmptyLoadItem(elem);
// uuidQueue.push(elem.uuid);
// }
// }
}
}
}
// const loadDataUUIDs = Object.keys(loadData);
// // clear unuse load-data
// loadDataUUIDs.forEach((loadUUID) => {
// if (currentUUIDs.includes(loadUUID) !== true) {
// delete loadData[loadUUID];
// }
// });
return [uuidQueue, loadData];
}
private _createEmptyLoadItem(elem: TypeElement<'image' | 'svg' | 'html'>): TypeLoadData[string] {
let source = '';
const type: TypeLoadData[string]['type'] = elem.type as TypeLoadData[string]['type'];
let elemW: number = elem.w;
let elemH: number = elem.h;
if (elem.type === 'image') {
const _elem = elem as TypeElement<'image'>;
source = _elem.desc.src || '';
} else if (elem.type === 'svg') {
const _elem = elem as TypeElement<'svg'>;
source = _elem.desc.svg || '';
} else if (elem.type === 'html') {
const _elem = elem as TypeElement<'html'>;
source = filterScript(_elem.desc.html || '');
elemW = _elem.desc.width || elem.w;
elemH = _elem.desc.height || elem.h;
}
return {
uuid: elem.uuid,
type: type,
status: 'null',
content: null,
source,
elemW,
elemH,
element: deepClone(elem),
};
}
private _loadTask() {
if (this._status === LoaderStatus.LOADING) {
return;
}
this._status = LoaderStatus.LOADING;
if (this._currentUUIDQueue.length === 0) {
if (this._waitingLoadQueue.length === 0) {
this._status = LoaderStatus.COMPLETE;
this._event.trigger('complete', undefined);
return;
} else {
const waitingItem = this._waitingLoadQueue.shift();
if (waitingItem) {
const { uuidQueue, loadData } = waitingItem;
this._currentLoadData = loadData;
this._currentUUIDQueue = uuidQueue;
}
}
}
const { maxParallelNum } = this._opts;
const uuids = this._currentUUIDQueue.splice(0, maxParallelNum);
const uuidMap: {[uuid: string]: number} = {};
uuids.forEach((url, i) => {
uuidMap[url] = i;
});
const loadUUIDList: string[] = [];
const _loadAction = () => {
if (loadUUIDList.length >= maxParallelNum) {
return false;
}
if (uuids.length === 0) {
return true;
}
for (let i = loadUUIDList.length; i < maxParallelNum; i++) {
const uuid = uuids.shift();
if (uuid === undefined) {
break;
}
loadUUIDList.push(uuid);
this._loadElementSource(this._currentLoadData[uuid]).then((image) => {
loadUUIDList.splice(loadUUIDList.indexOf(uuid), 1);
const status = _loadAction();
this._storageLoadData[uuid] = {
uuid,
type: this._currentLoadData[uuid].type,
status: 'loaded',
content: image,
source: this._currentLoadData[uuid].source,
elemW: this._currentLoadData[uuid].elemW,
elemH: this._currentLoadData[uuid].elemH,
element: this._currentLoadData[uuid].element,
};
if (loadUUIDList.length === 0 && uuids.length === 0 && status === true) {
this._status = LoaderStatus.FREE;
this._loadTask();
}
this._event.trigger('load', {
uuid: this._storageLoadData[uuid]?.uuid,
type: this._storageLoadData[uuid].type,
status: this._storageLoadData[uuid].status,
content: this._storageLoadData[uuid].content,
source: this._storageLoadData[uuid].source,
elemW: this._storageLoadData[uuid].elemW,
elemH: this._storageLoadData[uuid].elemH,
element: this._storageLoadData[uuid]?.element,
});
}).catch((err) => {
console.warn(err);
loadUUIDList.splice(loadUUIDList.indexOf(uuid), 1);
const status = _loadAction();
if (this._currentLoadData[uuid]) {
this._storageLoadData[uuid] = {
uuid,
type: this._currentLoadData[uuid]?.type,
status: 'fail',
content: null,
error: err,
source: this._currentLoadData[uuid]?.source,
elemW: this._currentLoadData[uuid]?.elemW,
elemH: this._currentLoadData[uuid]?.elemH,
element: this._currentLoadData[uuid]?.element,
};
}
if (loadUUIDList.length === 0 && uuids.length === 0 && status === true) {
this._status = LoaderStatus.FREE;
this._loadTask();
}
if (this._currentLoadData[uuid]) {
this._event.trigger('error', {
uuid: uuid,
type: this._storageLoadData[uuid]?.type,
status: this._storageLoadData[uuid]?.status,
content: this._storageLoadData[uuid]?.content,
source: this._storageLoadData[uuid]?.source,
elemW: this._storageLoadData[uuid]?.elemW,
elemH: this._storageLoadData[uuid]?.elemH,
element: this._storageLoadData[uuid]?.element,
});
}
});
}
return false;
};
_loadAction();
}
private async _loadElementSource(
params: TypeLoadData[string]
): Promise<HTMLImageElement> {
if (params && params.type === 'image') {
const image = await loadImage(params.source);
return image;
} else if (params && params.type === 'svg') {
const image = await loadSVG(
params.source
);
return image;
} else if (params && params.type === 'html') {
const image = await loadHTML(
params.source, {
width: params.elemW, height: params.elemH
}
);
return image;
}
throw Error('Element\'s source is not support!');
}
} | the_stack |
import App from "../app";
import uuid from "uuid";
import {pubsub} from "../helpers/subscriptionManager";
import * as Classes from "../classes";
const sendUpdate = sys => {
if (!sys) return;
if (sys.type === "Engine") pubsub.publish("engineUpdate", sys);
if (sys.type === "Transporters") pubsub.publish("transporterUpdate", sys);
if (sys.type === "Shield")
pubsub.publish(
"shieldsUpdate",
App.systems.filter(sys => sys.type === "Shield"),
);
if (sys.type === "Sensors") {
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
}
if (sys.type === "LongRangeComm")
pubsub.publish(
"longRangeCommunicationsUpdate",
App.systems.filter(s => s.type === "LongRangeComm"),
);
if (sys.type === "InternalComm")
pubsub.publish(
"internalCommUpdate",
App.systems.filter(s => s.type === "InternalComm"),
);
if (sys.type === "Navigation")
pubsub.publish(
"navigationUpdate",
App.systems.filter(s => s.type === "Navigation"),
);
if (sys.type === "ShortRangeComm")
pubsub.publish(
"shortRangeCommUpdate",
App.systems.filter(s => s.type === "ShortRangeComm"),
);
if (sys.type === "TractorBeam")
pubsub.publish(
"tractorBeamUpdate",
App.systems.filter(s => s.type === "TractorBeam"),
);
if (sys.type === "Phasers")
pubsub.publish(
"phasersUpdate",
App.systems.filter(s => s.type === "Phasers"),
);
if (sys.type === "Targeting")
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
if (sys.type === "Torpedo")
pubsub.publish(
"torpedosUpdate",
App.systems.filter(s => s.type === "Torpedo"),
);
if (sys.type === "Probes")
pubsub.publish(
"probesUpdate",
App.systems.filter(s => s.type === "Probes"),
);
if (sys.type === "SignalJammer")
pubsub.publish(
"signalJammersUpdate",
App.systems.filter(s => s.type === "SignalJammer"),
);
if (sys.type === "StealthField")
pubsub.publish(
"stealthFieldUpdate",
App.systems.filter(s => s.type === "StealthField"),
);
if (sys.type === "Railgun")
pubsub.publish(
"railgunUpdate",
App.systems.filter(s => s.id === sys.id),
);
if (sys.type === "JumpDrive")
pubsub.publish(
"jumpDriveUpdate",
App.systems.filter(s => s.id === sys.id),
);
if (sys.type === "Transwarp")
pubsub.publish(
"transwarpUpdate",
App.systems.filter(s => s.id === sys.id),
);
if (sys.class === "DockingPort")
pubsub.publish("dockingUpdate", App.dockingPorts);
if (sys.class === "ComputerCore")
pubsub.publish(
"computerCoreUpdate",
App.systems.filter(s => s.class === "ComputerCore"),
);
if (sys.class === "Crm") pubsub.publish("crmUpdate", sys);
pubsub.publish("systemsUpdate", App.systems);
};
App.on("addSystemToSimulator", ({simulatorId, className, params, cb}) => {
const init = JSON.parse(params);
init.simulatorId = simulatorId;
const ClassObj = Classes[className];
const obj = new ClassObj(init);
App.systems.push(obj);
pubsub.publish("systemsUpdate", App.systems);
cb && cb(obj.id);
});
App.on("removeSystemFromSimulator", ({systemId, simulatorId, type, cb}) => {
if (systemId) {
App.systems = App.systems.filter(s => s.id !== systemId);
} else if (simulatorId && type) {
const sys = App.systems.find(
s => s.simulatorId === simulatorId && s.type === type,
);
App.systems = App.systems.filter(s => s.id !== sys.id);
}
pubsub.publish("systemsUpdate", App.systems);
cb && cb();
});
App.on("updateSystemName", ({systemId, name, displayName, upgradeName}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.updateName({name, displayName, upgradeName});
sendUpdate(sys);
});
App.on("updateSystemUpgradeMacros", ({systemId, upgradeMacros}) => {
const sys = App.systems.find(t => t.id === systemId);
sys && sys.setUpgradeMacros(upgradeMacros);
sendUpdate(sys);
});
App.on("updateSystemUpgradeBoard", ({systemId, upgradeBoard}) => {
const sys = App.systems.find(t => t.id === systemId);
sys && sys.setUpgradeBoard(upgradeBoard);
sendUpdate(sys);
});
App.on("upgradeSystem", ({systemId}) => {
const sys = App.systems.find(t => t.id === systemId);
if (sys) {
sys.upgrade();
// Execute the macros
if (sys.upgradeMacros && sys.upgradeMacros.length > 0)
App.handleEvent(
{simulatorId: sys.simulatorId, macros: sys.upgradeMacros},
"triggerMacros",
);
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
type: "System",
station: "Core",
title: `${sys.displayName} Upgraded`,
body: sys.name,
color: "info",
});
App.handleEvent(
{
simulatorId: sys.simulatorId,
title: `${sys.displayName} Upgraded`,
body: sys.name,
color: "info",
},
"addCoreFeed",
);
sendUpdate(sys);
}
});
App.on("systemSetWing", ({systemId, wing}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) return;
sys.setWing(wing);
sendUpdate(sys);
});
App.on("damageSystem", ({systemId, report, destroyed, which = "default"}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
if (!sys) return;
}
sys.break(report, destroyed, which);
sendUpdate(sys);
});
App.on("damageReport", ({systemId, report}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
sys.damageReport(report);
sendUpdate(sys);
});
App.on("repairSystem", ({systemId}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
App.handleEvent(
{
simulatorId: sys.simulatorId,
contents: `${sys.displayName} ${
sys.damage.which === "default"
? "Repaired"
: sys.damage.which === "rnd"
? "R&D Report Complete"
: "Engineering Report Complete"
}`,
category: "Systems",
},
"recordsCreate",
);
sys.repair();
const taskReports = App.taskReports.filter(
t => t.systemId === systemId && t.type === "default" && t.cleared === false,
);
taskReports.forEach(t => App.handleEvent({id: t.id}, "clearTaskReport"));
sendUpdate(sys);
});
App.on("updateCurrentDamageStep", ({systemId, step}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
sys.updateCurrentStep(step);
sendUpdate(sys);
});
App.on("systemReactivationCode", ({systemId, station, code}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
type: "Reactivation Code",
station: "Core",
title: `Reactivation Code`,
body: sys.name,
color: "info",
});
App.handleEvent(
{
simulatorId: sys.simulatorId,
component: "ReactivationCore",
title: `Reactivation Code`,
body: sys.name,
color: "info",
},
"addCoreFeed",
);
sys.reactivationCode(code, station);
sendUpdate(sys);
});
App.on("changePower", ({systemId, power}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.setPower(power);
sendUpdate(sys);
});
App.on("changeSystemPowerLevels", ({systemId, powerLevels}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.setPowerLevels(powerLevels);
sendUpdate(sys);
});
App.on("requestDamageReport", ({systemId}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
App.handleEvent(
{
simulatorId: sys.simulatorId,
component: "DamageReportsCore",
title: `Damage Report Request`,
body: sys.name,
color: "info",
},
"addCoreFeed",
);
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
type: "Damage Reports",
station: "Core",
title: `Damage Report Request`,
body: sys.name,
color: "info",
});
sys.requestReport();
sendUpdate(sys);
});
App.on("systemReactivationCodeResponse", ({systemId, response}) => {
let sys = App.systems.find(s => s.id === systemId);
if (!sys) {
sys =
App.dockingPorts.find(s => s.id === systemId) ||
App.exocomps.find(s => s.id === systemId);
}
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
station: sys.damage.reactivationRequester,
title: "Reactivation Code",
body: `Reactivation Code for ${sys.displayName || sys.name} was ${
response ? "Accepted" : "Denied"
}`,
color: response ? "success" : "danger",
});
sys.reactivationCodeResponse(response);
// If the responses is true, repair the system with an event
if (response) {
App.handleEvent({systemId}, "repairSystem");
}
sendUpdate(sys);
});
App.on("setCoolant", ({systemId, coolant}) => {
const sys = App.systems.find(s => s.id === systemId);
if (sys.setCoolant) sys.setCoolant(coolant);
sendUpdate(sys);
});
App.on("updateSystemRooms", ({systemId, locations}) => {
const sys = App.systems.find(s => s.id === systemId);
if (sys.updateLocations) sys.updateLocations(locations);
sendUpdate(sys);
});
App.on("addSystemDamageStep", ({systemId, step, cb}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.addDamageStep(step);
sendUpdate(sys);
cb && cb();
});
App.on("updateSystemDamageStep", ({systemId, step, cb, context}) => {
let sys = App.systems.find(s => s.id === systemId);
sys && sys.updateDamageStep(step);
sendUpdate(sys);
cb && cb();
});
App.on("removeSystemDamageStep", ({systemId, step, cb}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.removeDamageStep(step);
sendUpdate(sys);
cb && cb();
});
App.on("addSystemDamageTask", ({systemId, task}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.addDamageTask(task);
sendUpdate(sys);
});
App.on("updateSystemDamageTask", ({systemId, task}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.updateDamageTask(task);
sendUpdate(sys);
});
App.on("removeSystemDamageTask", ({systemId, taskId}) => {
const sys = App.systems.find(s => s.id === systemId);
sys.removeDamageTask(taskId);
sendUpdate(sys);
});
App.on("breakSystem", ({simulatorId, type, name}) => {
const systems = App.systems.filter(
s =>
s.simulatorId === simulatorId &&
s.type === type &&
(name ? s.name === name : true),
);
const sys = systems.find(s => s.damage.damaged === false);
if (sys) {
sys.break();
} else if (name) {
// If the system doesn't exist and the name arg is set, create a new system
const args = {
simulatorId,
name,
extra: true,
damage: {damaged: true},
};
const ClassObj = Classes.System;
const obj = new ClassObj(args);
App.systems.push(obj);
}
sendUpdate(sys);
});
App.on("fixSystem", ({simulatorId, type, name}) => {
const systems = App.systems.filter(
s =>
s.simulatorId === simulatorId &&
s.type === type &&
(name ? s.name === name : true),
);
const sys = systems.find(s => s.damage.damaged === true);
sys && sys.repair();
sendUpdate(sys);
});
App.on("generateDamageReport", ({systemId, steps, cb}) => {
let sys = App.systems.find(s => s.id === systemId);
cb(sys.generateDamageReport(steps));
});
App.on("trainingMode", ({simulatorId}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.trainingMode(true);
const hasCommReview = !!sim.stations.find(s =>
s.cards.find(c => c.component === "CommReview"),
);
const systems = App.systems.filter(s => s.simulatorId === simulatorId);
systems.forEach(s => {
// The arguments are named and provide extra data to some of the training
// mode methods.
s.trainingMode({hasCommReview});
sendUpdate(s);
});
// Create a training system to damage
const ClassObj = Classes.System;
const obj = new ClassObj({
name: "Training",
extra: true,
simulatorId,
damage: {damaged: true},
});
obj.damageReport(`Step 1:
This is a training damage report. There will be several steps which you must follow to repair systems on your ship.
Go through the steps in this report to see what some of the things you will be expected to do are.
Step 2:
We should inform the closest starbase of our situation. You need to prepare a message using your long range message composer, or ask the Comm officer to send this message:
Destination: Starbase 4
Message: We have taken damage to our Training system. We might need assistance if the damage worsens. What ships are near our position?
Step 3:
If you followed the steps properly, the system has been repaired. Enter the following reactivation code to reactivate the system: #REACTIVATIONCODE
`);
App.systems.push(obj);
pubsub.publish("systemsUpdate", App.systems);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setDamageStepValidation", ({id, validation}) => {
let sys = App.systems.find(s => s.id === id);
const sim = App.simulators.find(s => s.id === sys.simulatorId);
sys.damage.validate = validation;
if (validation === false) {
// Send an update to every station with the
// damage step widget and card
const stations = sim.stations
.filter(s => {
return s.cards.find(c =>
["DamageControl", "EngineeringReports", "RnDReports"].includes(
c.component,
),
);
})
.concat(sim.stations.filter(s => s.widgets.indexOf("damageReport") > -1))
.map(s => s.name)
.filter((s, i, a) => a.indexOf(s) === i);
stations.forEach(s =>
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
station: s,
title: `Damage report step validation rejected`,
body: sys.name,
color: "danger",
relevantCards: ["DamageControl", "EngineeringReports", "RnDReports"],
}),
);
} else {
// Add the core feed
App.handleEvent(
{
simulatorId: sys.simulatorId,
component: "DamageReportsCore",
title: `Damage Step Verify Request`,
body: sys.name,
color: "info",
},
"addCoreFeed",
);
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
type: "Damage Reports",
station: "Core",
title: `Damage Validation Request`,
body: sys.name,
color: "warning",
});
}
sendUpdate(sys);
});
App.on("validateDamageStep", ({id}) => {
// The step is good. Increase the current step.
let sys = App.systems.find(s => s.id === id);
const sim = App.simulators.find(s => s.id === sys.simulatorId);
sys.updateCurrentStep(sys.damage.currentStep + 1);
sys.damage.validate = false;
// Send an update to every station with the
// damage step widget and card
const stations = sim.stations
.filter(s => {
return s.cards.find(c =>
["DamageControl", "EngineeringReports", "RnDReports"].includes(
c.component,
),
);
})
.concat(sim.stations.filter(s => s.widgets.indexOf("damageReport") > -1))
.map(s => s.name)
.filter((s, i, a) => a.indexOf(s) === i);
stations.forEach(s =>
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: sys.simulatorId,
station: s,
title: `Damage report step validation accepted`,
body: sys.name,
color: "success",
relevantCards: ["DamageControl", "EngineeringReports", "RnDReports"],
}),
);
sendUpdate(sys);
});
App.on("changeSystemDefaultPowerLevel", ({id, level}) => {
let sys = App.systems.find(s => s.id === id);
sys.setDefaultPowerLevel(level);
sendUpdate(sys);
});
App.on("fluxSystemPower", ({id, simulatorId, all, type, name}) => {
function randomFromList(list) {
if (!list) return;
const length = list.length;
const index = Math.floor(Math.random() * length);
return list[index];
}
function fluxPower(sys, all?: boolean) {
const level = Math.round(
(1 + Math.random()) * (Math.random() > 0.5 ? -1 : 1),
);
sys.setPower(Math.max(0, sys.power.power + level));
if (all) {
pubsub.publish("systemsUpdate", App.systems);
} else {
sendUpdate(sys);
}
}
const system = App.systems.find(
s =>
s.id === id ||
(s.simulatorId === simulatorId &&
(s.type === type || s.name === name || s.displayName === name)),
);
if (system) {
// Get a number between -2 and 2
fluxPower(system);
} else if (simulatorId) {
const systems = App.systems.filter(
s => s.simulatorId === simulatorId && s?.power?.powerLevels?.length > 0,
);
if (!all) {
const sys = randomFromList(systems);
fluxPower(sys, true);
} else {
systems.forEach(s => fluxPower(s));
}
}
}); | the_stack |
import { logger, PrefixedLogger } from '../../logger';
import * as utils from "../../utils";
import {
CryptoStore,
IDeviceData,
IProblem,
ISession,
ISessionInfo,
IWithheld,
Mode,
OutgoingRoomKeyRequest,
} from "./base";
import { IRoomKeyRequestBody } from "../index";
import { ICrossSigningKey } from "../../client";
import { IOlmDevice } from "../algorithms/megolm";
import { IRoomEncryption } from "../RoomList";
import { InboundGroupSessionData } from "../OlmDevice";
import { IEncryptedPayload } from "../aes";
export const VERSION = 10;
const PROFILE_TRANSACTIONS = false;
/**
* Implementation of a CryptoStore which is backed by an existing
* IndexedDB connection. Generally you want IndexedDBCryptoStore
* which connects to the database and defers to one of these.
*
* @implements {module:crypto/store/base~CryptoStore}
*/
export class Backend implements CryptoStore {
private nextTxnId = 0;
/**
* @param {IDBDatabase} db
*/
constructor(private db: IDBDatabase) {
// make sure we close the db on `onversionchange` - otherwise
// attempts to delete the database will block (and subsequent
// attempts to re-create it will also block).
db.onversionchange = () => {
logger.log(`versionchange for indexeddb ${this.db.name}: closing`);
db.close();
};
}
public async startup(): Promise<CryptoStore> {
// No work to do, as the startup is done by the caller (e.g IndexedDBCryptoStore)
// by passing us a ready IDBDatabase instance
return this;
}
public async deleteAllData(): Promise<void> {
throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.");
}
/**
* Look for an existing outgoing room key request, and if none is found,
* add a new one
*
* @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
*
* @returns {Promise} resolves to
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
* same instance as passed in, or the existing one.
*/
public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise<OutgoingRoomKeyRequest> {
const requestBody = request.requestBody;
return new Promise((resolve, reject) => {
const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite");
txn.onerror = reject;
// first see if we already have an entry for this request.
this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {
if (existing) {
// this entry matches the request - return it.
logger.log(
`already have key request outstanding for ` +
`${requestBody.room_id} / ${requestBody.session_id}: ` +
`not sending another`,
);
resolve(existing);
return;
}
// we got to the end of the list without finding a match
// - add the new request.
logger.log(
`enqueueing key request for ${requestBody.room_id} / ` +
requestBody.session_id,
);
txn.oncomplete = () => {resolve(request);};
const store = txn.objectStore("outgoingRoomKeyRequests");
store.add(request);
});
});
}
/**
* Look for an existing room key request
*
* @param {module:crypto~RoomKeyRequestBody} requestBody
* existing request to look for
*
* @return {Promise} resolves to the matching
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
* not found
*/
public getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise<OutgoingRoomKeyRequest | null> {
return new Promise((resolve, reject) => {
const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly");
txn.onerror = reject;
this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {
resolve(existing);
});
});
}
/**
* look for an existing room key request in the db
*
* @private
* @param {IDBTransaction} txn database transaction
* @param {module:crypto~RoomKeyRequestBody} requestBody
* existing request to look for
* @param {Function} callback function to call with the results of the
* search. Either passed a matching
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
* not found.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
private _getOutgoingRoomKeyRequest(
txn: IDBTransaction,
requestBody: IRoomKeyRequestBody,
callback: (req: OutgoingRoomKeyRequest | null) => void,
): void {
const store = txn.objectStore("outgoingRoomKeyRequests");
const idx = store.index("session");
const cursorReq = idx.openCursor([
requestBody.room_id,
requestBody.session_id,
]);
cursorReq.onsuccess = () => {
const cursor = cursorReq.result;
if (!cursor) {
// no match found
callback(null);
return;
}
const existing = cursor.value;
if (utils.deepCompare(existing.requestBody, requestBody)) {
// got a match
callback(existing);
return;
}
// look at the next entry in the index
cursor.continue();
};
}
/**
* Look for room key requests by state
*
* @param {Array<Number>} wantedStates list of acceptable states
*
* @return {Promise} resolves to the a
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
* there are no pending requests in those states. If there are multiple
* requests in those states, an arbitrary one is chosen.
*/
public getOutgoingRoomKeyRequestByState(wantedStates: number[]): Promise<OutgoingRoomKeyRequest | null> {
if (wantedStates.length === 0) {
return Promise.resolve(null);
}
// this is a bit tortuous because we need to make sure we do the lookup
// in a single transaction, to avoid having a race with the insertion
// code.
// index into the wantedStates array
let stateIndex = 0;
let result: OutgoingRoomKeyRequest;
function onsuccess(this: IDBRequest<IDBCursorWithValue>) {
const cursor = this.result;
if (cursor) {
// got a match
result = cursor.value;
return;
}
// try the next state in the list
stateIndex++;
if (stateIndex >= wantedStates.length) {
// no matches
return;
}
const wantedState = wantedStates[stateIndex];
const cursorReq = (this.source as IDBIndex).openCursor(wantedState);
cursorReq.onsuccess = onsuccess;
}
const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly");
const store = txn.objectStore("outgoingRoomKeyRequests");
const wantedState = wantedStates[stateIndex];
const cursorReq = store.index("state").openCursor(wantedState);
cursorReq.onsuccess = onsuccess;
return promiseifyTxn(txn).then(() => result);
}
/**
*
* @param {Number} wantedState
* @return {Promise<Array<*>>} All elements in a given state
*/
public getAllOutgoingRoomKeyRequestsByState(wantedState: number): Promise<OutgoingRoomKeyRequest[]> {
return new Promise((resolve, reject) => {
const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly");
const store = txn.objectStore("outgoingRoomKeyRequests");
const index = store.index("state");
const request = index.getAll(wantedState);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
public getOutgoingRoomKeyRequestsByTarget(
userId: string,
deviceId: string,
wantedStates: number[],
): Promise<OutgoingRoomKeyRequest[]> {
let stateIndex = 0;
const results: OutgoingRoomKeyRequest[] = [];
function onsuccess(this: IDBRequest<IDBCursorWithValue>) {
const cursor = this.result;
if (cursor) {
const keyReq = cursor.value;
if (keyReq.recipients.includes({ userId, deviceId })) {
results.push(keyReq);
}
cursor.continue();
} else {
// try the next state in the list
stateIndex++;
if (stateIndex >= wantedStates.length) {
// no matches
return;
}
const wantedState = wantedStates[stateIndex];
const cursorReq = (this.source as IDBIndex).openCursor(wantedState);
cursorReq.onsuccess = onsuccess;
}
}
const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly");
const store = txn.objectStore("outgoingRoomKeyRequests");
const wantedState = wantedStates[stateIndex];
const cursorReq = store.index("state").openCursor(wantedState);
cursorReq.onsuccess = onsuccess;
return promiseifyTxn(txn).then(() => results);
}
/**
* Look for an existing room key request by id and state, and update it if
* found
*
* @param {string} requestId ID of request to update
* @param {number} expectedState state we expect to find the request in
* @param {Object} updates name/value map of updates to apply
*
* @returns {Promise} resolves to
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}
* updated request, or null if no matching row was found
*/
public updateOutgoingRoomKeyRequest(
requestId: string,
expectedState: number,
updates: Partial<OutgoingRoomKeyRequest>,
): Promise<OutgoingRoomKeyRequest | null> {
let result: OutgoingRoomKeyRequest = null;
function onsuccess(this: IDBRequest<IDBCursorWithValue>) {
const cursor = this.result;
if (!cursor) {
return;
}
const data = cursor.value;
if (data.state != expectedState) {
logger.warn(
`Cannot update room key request from ${expectedState} ` +
`as it was already updated to ${data.state}`,
);
return;
}
Object.assign(data, updates);
cursor.update(data);
result = data;
}
const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite");
const cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId);
cursorReq.onsuccess = onsuccess;
return promiseifyTxn(txn).then(() => result);
}
/**
* Look for an existing room key request by id and state, and delete it if
* found
*
* @param {string} requestId ID of request to update
* @param {number} expectedState state we expect to find the request in
*
* @returns {Promise} resolves once the operation is completed
*/
public deleteOutgoingRoomKeyRequest(
requestId: string,
expectedState: number,
): Promise<OutgoingRoomKeyRequest | null> {
const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite");
const cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId);
cursorReq.onsuccess = () => {
const cursor = cursorReq.result;
if (!cursor) {
return;
}
const data = cursor.value;
if (data.state != expectedState) {
logger.warn(
`Cannot delete room key request in state ${data.state} `
+ `(expected ${expectedState})`,
);
return;
}
cursor.delete();
};
return promiseifyTxn<OutgoingRoomKeyRequest | null>(txn);
}
// Olm Account
public getAccount(txn: IDBTransaction, func: (accountPickle: string) => void): void {
const objectStore = txn.objectStore("account");
const getReq = objectStore.get("-");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
public storeAccount(txn: IDBTransaction, accountPickle: string): void {
const objectStore = txn.objectStore("account");
objectStore.put(accountPickle, "-");
}
public getCrossSigningKeys(txn: IDBTransaction, func: (keys: Record<string, ICrossSigningKey>) => void): void {
const objectStore = txn.objectStore("account");
const getReq = objectStore.get("crossSigningKeys");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
public getSecretStorePrivateKey(
txn: IDBTransaction,
func: (key: IEncryptedPayload | null) => void,
type: string,
): void {
const objectStore = txn.objectStore("account");
const getReq = objectStore.get(`ssss_cache:${type}`);
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
public storeCrossSigningKeys(txn: IDBTransaction, keys: Record<string, ICrossSigningKey>): void {
const objectStore = txn.objectStore("account");
objectStore.put(keys, "crossSigningKeys");
}
public storeSecretStorePrivateKey(txn: IDBTransaction, type: string, key: IEncryptedPayload): void {
const objectStore = txn.objectStore("account");
objectStore.put(key, `ssss_cache:${type}`);
}
// Olm Sessions
public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {
const objectStore = txn.objectStore("sessions");
const countReq = objectStore.count();
countReq.onsuccess = function() {
try {
func(countReq.result);
} catch (e) {
abortWithException(txn, e);
}
};
}
public getEndToEndSessions(
deviceKey: string,
txn: IDBTransaction,
func: (sessions: { [sessionId: string]: ISessionInfo }) => void,
): void {
const objectStore = txn.objectStore("sessions");
const idx = objectStore.index("deviceKey");
const getReq = idx.openCursor(deviceKey);
const results: Parameters<Parameters<Backend["getEndToEndSessions"]>[2]>[0] = {};
getReq.onsuccess = function() {
const cursor = getReq.result;
if (cursor) {
results[cursor.value.sessionId] = {
session: cursor.value.session,
lastReceivedMessageTs: cursor.value.lastReceivedMessageTs,
};
cursor.continue();
} else {
try {
func(results);
} catch (e) {
abortWithException(txn, e);
}
}
};
}
public getEndToEndSession(
deviceKey: string,
sessionId: string,
txn: IDBTransaction,
func: (sessions: { [ sessionId: string ]: ISessionInfo }) => void,
): void {
const objectStore = txn.objectStore("sessions");
const getReq = objectStore.get([deviceKey, sessionId]);
getReq.onsuccess = function() {
try {
if (getReq.result) {
func({
session: getReq.result.session,
lastReceivedMessageTs: getReq.result.lastReceivedMessageTs,
});
} else {
func(null);
}
} catch (e) {
abortWithException(txn, e);
}
};
}
public getAllEndToEndSessions(txn: IDBTransaction, func: (session: ISessionInfo) => void): void {
const objectStore = txn.objectStore("sessions");
const getReq = objectStore.openCursor();
getReq.onsuccess = function() {
try {
const cursor = getReq.result;
if (cursor) {
func(cursor.value);
cursor.continue();
} else {
func(null);
}
} catch (e) {
abortWithException(txn, e);
}
};
}
public storeEndToEndSession(
deviceKey: string,
sessionId: string,
sessionInfo: ISessionInfo,
txn: IDBTransaction,
): void {
const objectStore = txn.objectStore("sessions");
objectStore.put({
deviceKey,
sessionId,
session: sessionInfo.session,
lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs,
});
}
public async storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise<void> {
const txn = this.db.transaction("session_problems", "readwrite");
const objectStore = txn.objectStore("session_problems");
objectStore.put({
deviceKey,
type,
fixed,
time: Date.now(),
});
return promiseifyTxn(txn);
}
public async getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise<IProblem | null> {
let result;
const txn = this.db.transaction("session_problems", "readwrite");
const objectStore = txn.objectStore("session_problems");
const index = objectStore.index("deviceKey");
const req = index.getAll(deviceKey);
req.onsuccess = () => {
const problems = req.result;
if (!problems.length) {
result = null;
return;
}
problems.sort((a, b) => {
return a.time - b.time;
});
const lastProblem = problems[problems.length - 1];
for (const problem of problems) {
if (problem.time > timestamp) {
result = Object.assign({}, problem, { fixed: lastProblem.fixed });
return;
}
}
if (lastProblem.fixed) {
result = null;
} else {
result = lastProblem;
}
};
await promiseifyTxn(txn);
return result;
}
// FIXME: we should probably prune this when devices get deleted
public async filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise<IOlmDevice[]> {
const txn = this.db.transaction("notified_error_devices", "readwrite");
const objectStore = txn.objectStore("notified_error_devices");
const ret: IOlmDevice[] = [];
await Promise.all(devices.map((device) => {
return new Promise<void>((resolve) => {
const { userId, deviceInfo } = device;
const getReq = objectStore.get([userId, deviceInfo.deviceId]);
getReq.onsuccess = function() {
if (!getReq.result) {
objectStore.put({ userId, deviceId: deviceInfo.deviceId });
ret.push(device);
}
resolve();
};
});
}));
return ret;
}
// Inbound group sessions
public getEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
txn: IDBTransaction,
func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,
): void {
let session: InboundGroupSessionData | boolean = false;
let withheld: IWithheld | boolean = false;
const objectStore = txn.objectStore("inbound_group_sessions");
const getReq = objectStore.get([senderCurve25519Key, sessionId]);
getReq.onsuccess = function() {
try {
if (getReq.result) {
session = getReq.result.session;
} else {
session = null;
}
if (withheld !== false) {
func(session as InboundGroupSessionData, withheld as IWithheld);
}
} catch (e) {
abortWithException(txn, e);
}
};
const withheldObjectStore = txn.objectStore("inbound_group_sessions_withheld");
const withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);
withheldGetReq.onsuccess = function() {
try {
if (withheldGetReq.result) {
withheld = withheldGetReq.result.session;
} else {
withheld = null;
}
if (session !== false) {
func(session as InboundGroupSessionData, withheld as IWithheld);
}
} catch (e) {
abortWithException(txn, e);
}
};
}
public getAllEndToEndInboundGroupSessions(txn: IDBTransaction, func: (session: ISession | null) => void): void {
const objectStore = txn.objectStore("inbound_group_sessions");
const getReq = objectStore.openCursor();
getReq.onsuccess = function() {
const cursor = getReq.result;
if (cursor) {
try {
func({
senderKey: cursor.value.senderCurve25519Key,
sessionId: cursor.value.sessionId,
sessionData: cursor.value.session,
});
} catch (e) {
abortWithException(txn, e);
}
cursor.continue();
} else {
try {
func(null);
} catch (e) {
abortWithException(txn, e);
}
}
};
}
public addEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
sessionData: InboundGroupSessionData,
txn: IDBTransaction,
): void {
const objectStore = txn.objectStore("inbound_group_sessions");
const addReq = objectStore.add({
senderCurve25519Key, sessionId, session: sessionData,
});
addReq.onerror = (ev) => {
if (addReq.error.name === 'ConstraintError') {
// This stops the error from triggering the txn's onerror
ev.stopPropagation();
// ...and this stops it from aborting the transaction
ev.preventDefault();
logger.log(
"Ignoring duplicate inbound group session: " +
senderCurve25519Key + " / " + sessionId,
);
} else {
abortWithException(txn, new Error(
"Failed to add inbound group session: " + addReq.error,
));
}
};
}
public storeEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
sessionData: InboundGroupSessionData,
txn: IDBTransaction,
): void {
const objectStore = txn.objectStore("inbound_group_sessions");
objectStore.put({
senderCurve25519Key, sessionId, session: sessionData,
});
}
public storeEndToEndInboundGroupSessionWithheld(
senderCurve25519Key: string,
sessionId: string,
sessionData: IWithheld,
txn: IDBTransaction,
): void {
const objectStore = txn.objectStore("inbound_group_sessions_withheld");
objectStore.put({
senderCurve25519Key, sessionId, session: sessionData,
});
}
public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {
const objectStore = txn.objectStore("device_data");
const getReq = objectStore.get("-");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
public storeEndToEndDeviceData(deviceData: IDeviceData, txn: IDBTransaction): void {
const objectStore = txn.objectStore("device_data");
objectStore.put(deviceData, "-");
}
public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: IDBTransaction): void {
const objectStore = txn.objectStore("rooms");
objectStore.put(roomInfo, roomId);
}
public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record<string, IRoomEncryption>) => void): void {
const rooms: Parameters<Parameters<Backend["getEndToEndRooms"]>[1]>[0] = {};
const objectStore = txn.objectStore("rooms");
const getReq = objectStore.openCursor();
getReq.onsuccess = function() {
const cursor = getReq.result;
if (cursor) {
rooms[cursor.key as string] = cursor.value;
cursor.continue();
} else {
try {
func(rooms);
} catch (e) {
abortWithException(txn, e);
}
}
};
}
// session backups
public getSessionsNeedingBackup(limit: number): Promise<ISession[]> {
return new Promise((resolve, reject) => {
const sessions: ISession[] = [];
const txn = this.db.transaction(
["sessions_needing_backup", "inbound_group_sessions"],
"readonly",
);
txn.onerror = reject;
txn.oncomplete = function() {
resolve(sessions);
};
const objectStore = txn.objectStore("sessions_needing_backup");
const sessionStore = txn.objectStore("inbound_group_sessions");
const getReq = objectStore.openCursor();
getReq.onsuccess = function() {
const cursor = getReq.result;
if (cursor) {
const sessionGetReq = sessionStore.get(cursor.key);
sessionGetReq.onsuccess = function() {
sessions.push({
senderKey: sessionGetReq.result.senderCurve25519Key,
sessionId: sessionGetReq.result.sessionId,
sessionData: sessionGetReq.result.session,
});
};
if (!limit || sessions.length < limit) {
cursor.continue();
}
}
};
});
}
public countSessionsNeedingBackup(txn?: IDBTransaction): Promise<number> {
if (!txn) {
txn = this.db.transaction("sessions_needing_backup", "readonly");
}
const objectStore = txn.objectStore("sessions_needing_backup");
return new Promise((resolve, reject) => {
const req = objectStore.count();
req.onerror = reject;
req.onsuccess = () => resolve(req.result);
});
}
public async unmarkSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {
if (!txn) {
txn = this.db.transaction("sessions_needing_backup", "readwrite");
}
const objectStore = txn.objectStore("sessions_needing_backup");
await Promise.all(sessions.map((session) => {
return new Promise((resolve, reject) => {
const req = objectStore.delete([session.senderKey, session.sessionId]);
req.onsuccess = resolve;
req.onerror = reject;
});
}));
}
public async markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {
if (!txn) {
txn = this.db.transaction("sessions_needing_backup", "readwrite");
}
const objectStore = txn.objectStore("sessions_needing_backup");
await Promise.all(sessions.map((session) => {
return new Promise((resolve, reject) => {
const req = objectStore.put({
senderCurve25519Key: session.senderKey,
sessionId: session.sessionId,
});
req.onsuccess = resolve;
req.onerror = reject;
});
}));
}
public addSharedHistoryInboundGroupSession(
roomId: string,
senderKey: string,
sessionId: string,
txn?: IDBTransaction,
): void {
if (!txn) {
txn = this.db.transaction(
"shared_history_inbound_group_sessions", "readwrite",
);
}
const objectStore = txn.objectStore("shared_history_inbound_group_sessions");
const req = objectStore.get([roomId]);
req.onsuccess = () => {
const { sessions } = req.result || { sessions: [] };
sessions.push([senderKey, sessionId]);
objectStore.put({ roomId, sessions });
};
}
public getSharedHistoryInboundGroupSessions(
roomId: string,
txn?: IDBTransaction,
): Promise<[senderKey: string, sessionId: string][]> {
if (!txn) {
txn = this.db.transaction(
"shared_history_inbound_group_sessions", "readonly",
);
}
const objectStore = txn.objectStore("shared_history_inbound_group_sessions");
const req = objectStore.get([roomId]);
return new Promise((resolve, reject) => {
req.onsuccess = () => {
const { sessions } = req.result || { sessions: [] };
resolve(sessions);
};
req.onerror = reject;
});
}
public doTxn<T>(
mode: Mode,
stores: Iterable<string>,
func: (txn: IDBTransaction) => T,
log: PrefixedLogger = logger,
): Promise<T> {
let startTime: number;
let description: string;
if (PROFILE_TRANSACTIONS) {
const txnId = this.nextTxnId++;
startTime = Date.now();
description = `${mode} crypto store transaction ${txnId} in ${stores}`;
log.debug(`Starting ${description}`);
}
const txn = this.db.transaction(stores, mode);
const promise = promiseifyTxn(txn);
const result = func(txn);
if (PROFILE_TRANSACTIONS) {
promise.then(() => {
const elapsedTime = Date.now() - startTime;
log.debug(`Finished ${description}, took ${elapsedTime} ms`);
}, () => {
const elapsedTime = Date.now() - startTime;
log.error(`Failed ${description}, took ${elapsedTime} ms`);
});
}
return promise.then(() => {
return result;
});
}
}
export function upgradeDatabase(db: IDBDatabase, oldVersion: number): void {
logger.log(
`Upgrading IndexedDBCryptoStore from version ${oldVersion}`
+ ` to ${VERSION}`,
);
if (oldVersion < 1) { // The database did not previously exist.
createDatabase(db);
}
if (oldVersion < 2) {
db.createObjectStore("account");
}
if (oldVersion < 3) {
const sessionsStore = db.createObjectStore("sessions", {
keyPath: ["deviceKey", "sessionId"],
});
sessionsStore.createIndex("deviceKey", "deviceKey");
}
if (oldVersion < 4) {
db.createObjectStore("inbound_group_sessions", {
keyPath: ["senderCurve25519Key", "sessionId"],
});
}
if (oldVersion < 5) {
db.createObjectStore("device_data");
}
if (oldVersion < 6) {
db.createObjectStore("rooms");
}
if (oldVersion < 7) {
db.createObjectStore("sessions_needing_backup", {
keyPath: ["senderCurve25519Key", "sessionId"],
});
}
if (oldVersion < 8) {
db.createObjectStore("inbound_group_sessions_withheld", {
keyPath: ["senderCurve25519Key", "sessionId"],
});
}
if (oldVersion < 9) {
const problemsStore = db.createObjectStore("session_problems", {
keyPath: ["deviceKey", "time"],
});
problemsStore.createIndex("deviceKey", "deviceKey");
db.createObjectStore("notified_error_devices", {
keyPath: ["userId", "deviceId"],
});
}
if (oldVersion < 10) {
db.createObjectStore("shared_history_inbound_group_sessions", {
keyPath: ["roomId"],
});
}
// Expand as needed.
}
function createDatabase(db: IDBDatabase): void {
const outgoingRoomKeyRequestsStore =
db.createObjectStore("outgoingRoomKeyRequests", { keyPath: "requestId" });
// we assume that the RoomKeyRequestBody will have room_id and session_id
// properties, to make the index efficient.
outgoingRoomKeyRequestsStore.createIndex("session",
["requestBody.room_id", "requestBody.session_id"],
);
outgoingRoomKeyRequestsStore.createIndex("state", "state");
}
interface IWrappedIDBTransaction extends IDBTransaction {
_mx_abortexception: Error; // eslint-disable-line camelcase
}
/*
* Aborts a transaction with a given exception
* The transaction promise will be rejected with this exception.
*/
function abortWithException(txn: IDBTransaction, e: Error) {
// We cheekily stick our exception onto the transaction object here
// We could alternatively make the thing we pass back to the app
// an object containing the transaction and exception.
(txn as IWrappedIDBTransaction)._mx_abortexception = e;
try {
txn.abort();
} catch (e) {
// sometimes we won't be able to abort the transaction
// (ie. if it's aborted or completed)
}
}
function promiseifyTxn<T>(txn: IDBTransaction): Promise<T> {
return new Promise((resolve, reject) => {
txn.oncomplete = () => {
if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {
reject((txn as IWrappedIDBTransaction)._mx_abortexception);
}
resolve(null);
};
txn.onerror = (event) => {
if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {
reject((txn as IWrappedIDBTransaction)._mx_abortexception);
} else {
logger.log("Error performing indexeddb txn", event);
reject(txn.error);
}
};
txn.onabort = (event) => {
if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {
reject((txn as IWrappedIDBTransaction)._mx_abortexception);
} else {
logger.log("Error performing indexeddb txn", event);
reject(txn.error);
}
};
});
} | the_stack |
module VORLON {
declare var Modernizr;
export class ModernizrReportClient extends ClientPlugin {
public supportedFeatures: FeatureSupported[] = [];
constructor() {
super("modernizrReport");
this._ready = true;
this._id = "MODERNIZR";
//this.debug = true;
}
public startClientSide(): void {
this.loadModernizrFeatures();
}
public loadModernizrFeatures(){
this.trace("loading modernizr script");
this._loadNewScriptAsync("modernizr.js", () => {
this.trace("modernizr script loaded");
this.checkSupportedFeatures();
}, true);
}
public checkSupportedFeatures() {
if (Modernizr) {
this.trace("checkin client features with Modernizr");
this.supportedFeatures = [];
this.supportedFeatures.push({ featureName: "Application cache", isSupported: Modernizr.applicationcache, type: "html" });
this.supportedFeatures.push({ featureName: "Audio tag", isSupported: Modernizr.audio, type: "html" });
this.supportedFeatures.push({ featureName: "background-size", isSupported: Modernizr.backgroundsize, type: "css" });
this.supportedFeatures.push({ featureName: "border-image", isSupported: Modernizr.borderimage, type: "css" });
this.supportedFeatures.push({ featureName: "border-radius", isSupported: Modernizr.borderradius, type: "css" });
this.supportedFeatures.push({ featureName: "box-shadow", isSupported: Modernizr.boxshadow, type: "css" });
this.supportedFeatures.push({ featureName: "canvas", isSupported: Modernizr.canvas, type: "html" });
this.supportedFeatures.push({ featureName: "canvas text", isSupported: Modernizr.canvastext, type: "html" });
this.supportedFeatures.push({ featureName: "CSS Animations", isSupported: Modernizr.cssanimations, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Columns", isSupported: Modernizr.csscolumns, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Gradients", isSupported: Modernizr.cssgradients, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Reflections", isSupported: Modernizr.cssreflections, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Transforms", isSupported: Modernizr.csstransforms, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Transforms 3d", isSupported: Modernizr.csstransforms3d, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Transitions", isSupported: Modernizr.csstransitions, type: "css" });
this.supportedFeatures.push({ featureName: "Drag'n'drop", isSupported: Modernizr.draganddrop, type: "html" });
this.supportedFeatures.push({ featureName: "Flexbox", isSupported: Modernizr.flexbox, type: "css" });
this.supportedFeatures.push({ featureName: "@font-face", isSupported: Modernizr.fontface, type: "css" });
this.supportedFeatures.push({ featureName: "CSS Generated Content (:before/:after)", isSupported: Modernizr.generatedcontent, type: "css" });
this.supportedFeatures.push({ featureName: "Geolocation API", isSupported: Modernizr.geolocation, type: "misc" });
this.supportedFeatures.push({ featureName: "hashchange Event", isSupported: Modernizr.hashchange, type: "html" });
this.supportedFeatures.push({ featureName: "History Management", isSupported: Modernizr.history, type: "html" });
this.supportedFeatures.push({ featureName: "Color Values hsla()", isSupported: Modernizr.hsla, type: "css" });
this.supportedFeatures.push({ featureName: "IndexedDB", isSupported: Modernizr.indexeddb, type: "html" });
this.supportedFeatures.push({ featureName: "Inline SVG in HTML5", isSupported: Modernizr.inlinesvg, type: "misc" });
this.supportedFeatures.push({ featureName: "Input Attribute autocomplete", isSupported: Modernizr.input.autocomplete, type: "html" });
/* TO DO: Inputs... */
this.supportedFeatures.push({ featureName: "localStorage", isSupported: Modernizr.localstorage, type: "html" });
this.supportedFeatures.push({ featureName: "Multiple backgrounds", isSupported: Modernizr.multiplebgs, type: "css" });
this.supportedFeatures.push({ featureName: "opacity", isSupported: Modernizr.opacity, type: "css" });
this.supportedFeatures.push({ featureName: "Cross-window Messaging", isSupported: Modernizr.postmessage, type: "html" });
this.supportedFeatures.push({ featureName: "Color Values rgba()", isSupported: Modernizr.rgba, type: "css" });
this.supportedFeatures.push({ featureName: "sessionStorage", isSupported: Modernizr.sessionstorage, type: "html" });
this.supportedFeatures.push({ featureName: "SVG SMIL animation", isSupported: Modernizr.smil, type: "misc" });
this.supportedFeatures.push({ featureName: "SVG", isSupported: Modernizr.svg, type: "misc" });
this.supportedFeatures.push({ featureName: "SVG Clipping Paths", isSupported: Modernizr.svgclippaths, type: "misc" });
this.supportedFeatures.push({ featureName: "text-shadow", isSupported: Modernizr.textshadow, type: "css" });
this.supportedFeatures.push({ featureName: "Touch Events", isSupported: Modernizr.touch, type: "misc" });
this.supportedFeatures.push({ featureName: "Video", isSupported: Modernizr.video, type: "html" });
this.supportedFeatures.push({ featureName: "WebGL", isSupported: Modernizr.webgl, type: "misc" });
this.supportedFeatures.push({ featureName: "Web Sockets", isSupported: ("WebSocket" in window), type: "html" });
this.supportedFeatures.push({ featureName: "Web SQL Database", isSupported: Modernizr.websqldatabase, type: "html" });
this.supportedFeatures.push({ featureName: "Web Workers", isSupported: Modernizr.webworkers, type: "html" });
this.supportedFeatures.push({ featureName: "A [download] attribute", isSupported: Modernizr.adownload, type: "noncore" });
this.supportedFeatures.push({ featureName: "Mozilla Audio Data API", isSupported: Modernizr.audiodata, type: "noncore" });
this.supportedFeatures.push({ featureName: "HTML5 Web Audio API", isSupported: Modernizr.webaudio, type: "noncore" });
this.supportedFeatures.push({ featureName: "Battery Status API", isSupported: Modernizr.battery, type: "noncore" });
this.supportedFeatures.push({ featureName: "Low Battery Level", isSupported: Modernizr.lowbattery, type: "noncore" });
this.supportedFeatures.push({ featureName: "Blob Constructor", isSupported: Modernizr.blobconstructor, type: "noncore" });
this.supportedFeatures.push({ featureName: "Canvas toDataURL image/jpeg", isSupported: Modernizr.todataurljpeg, type: "noncore" });
this.supportedFeatures.push({ featureName: "Canvas toDataURL image/png", isSupported: Modernizr.todataurlpng, type: "noncore" });
this.supportedFeatures.push({ featureName: "Canvas toDataURL image/webp", isSupported: Modernizr.todataurlwebp, type: "noncore" });
this.supportedFeatures.push({ featureName: "HTML5 Content Editable Attribute", isSupported: Modernizr.contenteditable, type: "noncore" });
this.supportedFeatures.push({ featureName: "Content Security Policy", isSupported: Modernizr.contentsecuritypolicy, type: "noncore" });
this.supportedFeatures.push({ featureName: "HTML5 Context Menu", isSupported: Modernizr.contextmenu, type: "noncore" });
this.supportedFeatures.push({ featureName: "Cookie", isSupported: Modernizr.cookies, type: "noncore" });
this.supportedFeatures.push({ featureName: "Cross-Origin Resource Sharing", isSupported: Modernizr.cors, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS background-position Shorthand", isSupported: Modernizr.bgpositionshorthand, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS background-position-x/y", isSupported: Modernizr.bgpositionxy, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS background-repeat: space", isSupported: Modernizr.bgrepeatspace, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS background-repeat: round", isSupported: Modernizr.bgrepeatround, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS background-size: cover", isSupported: Modernizr.bgsizecover, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS Box Sizing", isSupported: Modernizr.boxsizing, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS Calc", isSupported: Modernizr.csscalc, type: "noncore" });
this.supportedFeatures.push({ featureName: "CSS Cubic Bezier Range", isSupported: Modernizr.cubicbezierrange, type: "noncore" });
this.supportedFeatures.push({ featureName: "Gamepad", isSupported: Modernizr.gamepads, type: "noncore" });
//this.supportedFeatures.push({ featureName: "", isSupported: Modernizr.display-runin, type: "noncore" });
//this.supportedFeatures.push({ featureName: "", isSupported: Modernizr.display-table, type: "noncore" });
this.sendFeaturesToDashboard();
}
}
public sendFeaturesToDashboard() {
var message: any = {};
message.features = this.supportedFeatures || [];
this.trace("sending " + message.features.length + " features");
this.sendCommandToDashboard("clientfeatures", message);
}
public refresh(): void {
this.trace("refreshing Modernizr");
if (this.supportedFeatures && this.supportedFeatures.length){
this.sendFeaturesToDashboard();
}else{
this.loadModernizrFeatures();
}
}
}
ModernizrReportClient.prototype.ClientCommands = {
refresh: function(data: any) {
var plugin = <NetworkMonitorClient>this;
plugin.refresh();
}
};
// Register
Core.RegisterClientPlugin(new ModernizrReportClient());
} | the_stack |
import {afterAll, beforeAll, describe, expect, it} from "@jest/globals";
import {Helper} from "./helper";
import {ElementHandle} from "puppeteer";
describe("crawl some blog with smartphone", () => {
let c: Helper;
let captcha_key: string = "1234";
const start_url = "/testblog2/";
beforeAll(async () => {
c = new Helper();
await c.init();
await c.setSpUserAgent();
});
it("open blog top", async () => {
await c.openUrl(c.getBaseUrl() + start_url);
await c.getSS("blog_top_sp.png");
expect(await c.page.title()).toEqual("testblog2");
});
it("blog top - check cookie", async () => {
const cookies = await c.page.cookies();
// ここがコケるということは、テスト無しにクッキーが追加されているかも
expect(cookies.length).toEqual(1);
const [session_cookie] = cookies.filter((elm) => elm.name === "dojima");
// console.log(session_cookie);
expect(session_cookie.domain).toEqual("localhost");
expect(session_cookie.path).toEqual("/");
expect(session_cookie.expires).toEqual(-1);
expect(session_cookie.httpOnly).toEqual(true);
expect(session_cookie.secure).toEqual(false);
expect(session_cookie.session).toEqual(true);
expect(session_cookie.sameSite).toEqual("Lax");
});
it("blog top - check fuzzy display contents", async () => {
const title_text = await c.getTextBySelector("h1 a");
expect(title_text).toEqual("testblog2");
const entry_bodies = await c.page.$$eval("ul#entry_list strong", (elm_list) => {
let bodies = [];
elm_list.forEach((elm) => bodies.push(elm.textContent));
return bodies;
});
// console.log(entry_bodies);
expect(entry_bodies[0].match(/3rd/)).toBeTruthy();
expect(entry_bodies[1].match(/2nd/)).toBeTruthy();
expect(entry_bodies[2].match(/テスト記事1/)).toBeTruthy();
});
it("blog top - click first entry", async () => {
const response = await c.clickBySelector("ul#entry_list a");
await c.getSS("entry_sp.png");
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html");
expect(await c.page.title()).toEqual("3rd - testblog2");
const entry_h2_title = await c.getTextBySelector("div.entry_title h2");
expect(entry_h2_title.match(/3rd/)).toBeTruthy();
const entry_body = await c.getTextBySelector("div.entry_body");
expect(entry_body.match(/3rd/)).toBeTruthy();
});
it("entry page - click next page", async () => {
const response = await c.clickBySelector("a.nextpage");
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-2.html");
expect(await c.page.title()).toEqual("2nd - testblog2");
const entry_h2_title = await c.getTextBySelector("div.entry_title h2");
expect(entry_h2_title.match(/2nd/)).toBeTruthy();
const entry_body = await c.getTextBySelector("div.entry_body");
expect(entry_body.match(/2nd/)).toBeTruthy();
});
it("entry page - click prev page", async () => {
const response = await c.clickBySelector("a.prevpage");
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html");
expect(await c.page.title()).toEqual("3rd - testblog2");
const entry_h2_title = await c.getTextBySelector("div.entry_title h2");
expect(entry_h2_title.match(/3rd/)).toBeTruthy();
const entry_body = await c.getTextBySelector("div.entry_body");
expect(entry_body.match(/3rd/)).toBeTruthy();
});
let posted_comment_num;
it("entry page - open comment form", async () => {
const response = await c.clickBySelector("#entry > ul > li:nth-child(1) > a");
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html?m2=form");
expect(await c.page.title()).toEqual("3rd - testblog2");
});
let post_comment_title;
it("user template comment form - fill comment", async () => {
// generate uniq title
post_comment_title = "テストタイトル_" + Math.floor(Math.random() * 1000000).toString();
// console.log(post_comment_title);
await c.getSS("comment_before_fill_sp");
await fillCommentForm(
c.page,
"テスト太郎",
post_comment_title,
"test@example.jp",
"http://example.jp",
"これはテスト投稿です\nこれはテスト投稿です!",
"pass_is_pass"
)
await c.getSS("comment_after_fill_sp");
const response = await c.clickBySelector("#comment_post > form > div > a");
await c.getSS("comment_confirm_sp");
expect(response.url()).toEqual(c.getBaseUrl() + start_url);
});
it("comment form - failed with wrong captcha", async () => {
// input wrong captcha
await c.page.type("input[name=token]", "0000"); // wrong key
const response = await c.clickBySelector("#sys-comment-form > fieldset > div > input");
await c.getSS("comment_wrong_captcha_sp");
expect(response.url()).toEqual(c.getBaseUrl() + start_url);
// 特定しやすいセレクタがない
const is_captcha_failed = await c.page.$$eval("p", (elms) => {
let isOk = false;
elms.forEach((elm) => {
if (elm.textContent.match(/認証に失敗しました/)) {
isOk = true;
}
});
return isOk;
});
expect(is_captcha_failed).toBeTruthy();
});
it("comment form - comment success", async () => {
await c.page.type("input[name=token]", captcha_key);
await c.getSS("comment_correct_token_sp");
const response = await c.clickBySelector("#sys-comment-form input[type=submit]");
const exp = new RegExp(
c.getBaseUrl() + start_url + 'index.php\\?mode=entries&process=view&id=[0-9]{1,100}'
);
expect(response.url().match(exp)).not.toBeNull();
const comment_a_text = await c.getTextBySelector("#entry > ul > li:nth-child(2) > a");
await c.getSS("comment_success_sp");
posted_comment_num = parseInt(comment_a_text.match(/コメント\(([0-9]{1,3})\)/)[1]);
});
it("entry page - open comment list", async () => {
const response = await c.clickBySelector("#entry > ul > li:nth-child(2) > a");
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html?m2=res");
expect(await c.page.title()).toEqual("3rd - testblog2");
});
it("comment list - open comment form", async () => {
const response = await c.clickElement(await getEditLinkByTitle(post_comment_title));
expect(response.url()).toEqual(expect.stringContaining(c.getBaseUrl() + start_url + "index.php?mode=entries&process=comment_edit&id="));
expect(await c.page.title()).toEqual("コメントの編集 - testblog2");
await c.getSS("comment_edit_before_sp");
});
it("user template comment form - comment edit", async () => {
await fillEditForm(
c.page,
"テスト太郎2",
"edited_" + post_comment_title,
"test2@example.jp",
"http://example.jp/2",
"これは編集済み",
"pass_is_pass"
)
await c.getSS("comment_edit_filled_sp");
// comment formへ遷移
let response = await c.clickBySelector("#comment_post > form > div > input[type=submit]:nth-child(1)");
await c.getSS("comment_edit_confirm_sp");
expect(response.status()).toEqual(200);
await c.page.type("input[name=token]", captcha_key);
// 送信
response = await c.clickBySelector("#sys-comment-form > fieldset > div > input");
await c.getSS("comment_edit_success_sp");
expect(response.status()).toEqual(200);
});
it("comment list - test to fail delete", async () => {
const response = await c.clickElement(await c.page.$("#entry > ul > li:nth-child(2) > a"));
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html?m2=res");
expect(await c.page.title()).toEqual("3rd - testblog2");
await c.getSS("comment_list_delete_before_sp");
});
it("comment list - test to fail delete", async () => {
await c.getSS("comment_form_delete_before1_sp");
const response = await c.clickElement(await getEditLinkByTitle("edited_" + post_comment_title));
await c.getSS("comment_form_delete_before2_sp");
expect(response.status()).toEqual(200);
expect(response.url()).toEqual(expect.stringContaining(c.getBaseUrl() + start_url + "index.php?mode=entries&process=comment_edit&id="));
expect(await c.page.title()).toEqual("コメントの編集 - testblog2");
});
it("user template comment form - delete fail by wrong password", async () => {
const delete_button = await c.page.$(
"#comment_post > form > div > input[type=submit]:nth-child(2)"
);
const [response] = await Promise.all([
c.waitLoad(),
await delete_button.click()
]);
expect(response.status()).toEqual(200);
expect(response.url()).toEqual(c.getBaseUrl() + start_url);
const wrong_password_error_text = await c.page.$eval("#comment_post > form > dl > dd:nth-child(12) > p", elm => elm.textContent);
expect(/必ず入力してください/.exec(wrong_password_error_text)).toBeTruthy();
});
it("entry page - open comment list to delete", async () => {
await c.openUrl(c.getBaseUrl() + start_url + "blog-entry-3.html");
const response = await c.clickElement(await c.page.$("#entry > ul > li:nth-child(2) > a"));
expect(response.status()).toEqual(200);
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html?m2=res");
expect(await c.page.title()).toEqual("3rd - testblog2");
await c.getSS("comment_list_delete_before_sp");
});
it("comment list - open comment form to delete", async () => {
await c.getSS("comment_form_delete_before1_sp");
const response = await c.clickElement(await getEditLinkByTitle("edited_" + post_comment_title));
await c.getSS("comment_form_delete_before2_sp");
expect(response.status()).toEqual(200);
expect(response.url()).toEqual(expect.stringContaining(c.getBaseUrl() + start_url + "index.php?mode=entries&process=comment_edit&id="));
expect(await c.page.title()).toEqual("コメントの編集 - testblog2");
});
it("user template comment form - comment delete success", async () => {
// do delete.
await c.page.type("#comment_post > form > dl > dd:nth-child(12) > input[type=password]", "pass_is_pass");
const response = await c.clickBySelector("#comment_post > form > div > input[type=submit]:nth-child(2)")
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "index.php?mode=entries&process=view&id=3&sp");
});
it("entry page - open entry check delete complete", async () => {
await c.openUrl(c.getBaseUrl() + start_url);
const response = await c.clickElement(await c.page.$("#entry_list > li:nth-child(1) > a"));
expect(response.status()).toEqual(200);
expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html");
expect(await c.page.title()).toEqual("3rd - testblog2");
});
it("entry page - check comment count", async () => {
const comment_a_text = await c.page.$eval("#entry > ul > li:nth-child(2) > a", elm => elm.textContent);
const comment_num = parseInt(comment_a_text.match(/コメント\(([0-9]{1,3})\)/)[1]);
// expect(comment_num).toEqual(posted_comment_num-1); // パラレルでテストが実行されるので、数を数えても正しくできない
});
afterAll(async () => {
await c.browser.close();
});
// ========================
async function getEditLinkByTitle(title): Promise<ElementHandle> {
// 該当するタイトルの編集リンクを探す
// SPのコメント一覧専用
const dt_elm_list = await c.page.$$("#comment dt");
let idx = -1;
for (let i = 0; i < dt_elm_list.length; i++) {
let txt = await (await dt_elm_list[i].getProperty('innerHTML')).jsonValue();
// console.log(txt);
if (txt == title) {
idx = i;
break;
}
}
if (idx == -1) {
throw new Error("notfound target title");
}
const dd_elm_list = await c.page.$$("#comment dd");
const target_dd = dd_elm_list[idx];
// console.log(await target_dd.jsonValue());
return await target_dd.$("a[title='コメントの編集']")
}
async function fillCommentForm(
page,
name,
title,
email,
url,
body,
pass = "",
) {
await page.$eval(
"form[name=form1] input[name='comment[name]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] input[name='comment[name]']",
name
);
await page.$eval(
"form[name=form1] input[name='comment[title]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] input[name='comment[title]']",
title
);
await page.$eval(
"form[name=form1] input[name='comment[mail]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] input[name='comment[mail]']",
email
);
await page.$eval(
"form[name=form1] input[name='comment[url]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] input[name='comment[url]']",
url
);
await page.$eval(
"form[name=form1] textarea[name='comment[body]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] textarea[name='comment[body]']",
body
);
await page.$eval(
"form[name=form1] input[name='comment[pass]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"form[name=form1] input[name='comment[pass]']",
pass
);
}
async function fillEditForm(
page,
name,
title,
email,
url,
body,
pass = "",
) {
await page.$eval(
"#comment_post input[name='edit[name]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post input[name='edit[name]']",
name
);
await page.$eval(
"#comment_post input[name='edit[title]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post input[name='edit[title]']",
title
);
await page.$eval(
"#comment_post input[name='edit[mail]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post input[name='edit[mail]']",
email
);
await page.$eval(
"#comment_post input[name='edit[url]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post input[name='edit[url]']",
url
);
await page.$eval(
"#comment_post textarea[name='edit[body]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post textarea[name='edit[body]']",
body
);
await page.$eval(
"#comment_post input[name='edit[pass]']",
(elm: HTMLInputElement) => (elm.value = "")
);
await page.type(
"#comment_post input[name='edit[pass]']",
pass
);
}
}); | the_stack |
import { getSnapshot, types, Instance } from "mobx-state-tree";
import { Field, Form, converters } from "../src";
test("FormState can be saved", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string, {}),
});
async function save(node: Instance<typeof M>) {
if (node.foo === "") {
return {
errorValidations: [
{ id: "dummy", messages: [{ path: "/foo", message: "Wrong" }] },
],
};
}
return null;
}
const state = form.state(o, { backend: { save } });
const field = state.field("foo");
// do something not allowed
field.setRaw("");
// we don't see any client-side validation errors
expect(field.error).toBeUndefined();
expect(o.foo).toEqual("");
// now communicate with the server by doing the save
const saveResult0 = await state.save();
expect(saveResult0).toBe(false);
expect(field.error).toEqual("Wrong");
// correct things
field.setRaw("BAR");
expect(o.foo).toEqual("BAR");
// editing does not wipe out external errors
expect(field.error).toEqual("Wrong");
const saveResult1 = await state.save();
expect(saveResult1).toBe(true);
expect(field.error).toBeUndefined();
});
test("save argument can be snapshotted", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string, {}),
});
let snapshot;
async function save(node: Instance<typeof M>) {
snapshot = getSnapshot(node);
return null;
}
const state = form.state(o, { backend: { save } });
await state.save();
expect(snapshot).toEqual({ foo: "FOO" });
});
test("inline save argument can be snapshotted", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string, {}),
});
let snapshot;
const state = form.state(o, {
backend: {
save: async (node) => {
snapshot = getSnapshot(node);
return null;
},
},
});
await state.save();
expect(snapshot).toEqual({ foo: "FOO" });
});
test("required with save", async () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string, {
required: true,
}),
});
const o = M.create({ foo: "" });
const state = form.state(o, { backend: { save: async () => null } });
const field = state.field("foo");
expect(field.raw).toEqual("");
expect(field.error).toBeUndefined();
await state.save();
expect(field.error).toEqual("Required");
});
test("dynamic required with save", async () => {
const M = types.model("M", {
foo: types.string,
bar: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
bar: new Field(converters.string),
});
const o = M.create({ foo: "", bar: "" });
const state = form.state(o, {
isRequired: () => true,
backend: { save: async () => null },
});
const fooField = state.field("foo");
const barField = state.field("bar");
expect(fooField.raw).toEqual("");
expect(fooField.error).toBeUndefined();
expect(barField.error).toBeUndefined();
await state.save();
expect(fooField.error).toEqual("Required");
expect(barField.error).toEqual("Required");
});
test("no validation before save", async () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string, {
validators: [(value) => value !== "correct" && "Wrong"],
}),
});
const o = M.create({ foo: "FOO" });
const state = form.state(o, {
validation: { beforeSave: "no" },
backend: { save: async () => null },
});
const field = state.field("foo");
// no validation messages before save
expect(field.raw).toEqual("FOO");
field.setRaw("incorrect");
expect(field.raw).toEqual("incorrect");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("FOO");
field.setRaw("correct");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
field.setRaw("incorrect");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
const isSaved = await state.save();
// immediate validation after save
expect(field.error).toEqual("Wrong");
expect(isSaved).toBeFalsy();
field.setRaw("correct");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
field.setRaw("incorrect");
expect(field.error).toEqual("Wrong");
});
test("no validation after save either", async () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string, {
validators: [
(value) => value !== "correct" && value !== "clientcorrect" && "Wrong",
],
}),
});
const o = M.create({ foo: "FOO" });
const state = form.state(o, {
backend: {
save: async (node) => {
if (node.foo !== "correct") {
return {
errorValidations: [
{
id: "dummy",
messages: [{ path: "/foo", message: "Server wrong" }],
},
],
};
}
return null;
},
},
validation: {
beforeSave: "no",
afterSave: "no",
},
});
const field = state.field("foo");
// no validation messages before save
expect(field.raw).toEqual("FOO");
field.setRaw("incorrect");
expect(field.raw).toEqual("incorrect");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("FOO");
field.setRaw("correct");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
field.setRaw("incorrect");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
let isSaved = await state.save();
expect(state.saveStatus).toEqual("rightAfter");
// only a single validation after save
expect(field.error).toEqual("Wrong");
expect(isSaved).toBeFalsy();
// after this we don't see inline errors anymore
field.setRaw("correct");
expect(field.error).toBeUndefined();
expect(field.value).toEqual("correct");
field.setRaw("incorrect");
expect(field.error).toBeUndefined();
// we save again, and this time get a server-side error
field.setRaw("clientcorrect"); // no client-side problems
isSaved = await state.save();
expect(isSaved).toBeFalsy();
expect(field.error).toEqual("Server wrong");
});
test("a form with a dynamic required field", async () => {
const M = types.model("M", {
foo: types.string,
bar: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
bar: new Field(converters.string),
});
const o = M.create({ foo: "FOO", bar: "BAR" });
let touched = false;
async function save(data: any) {
touched = true;
if (data.foo === "") {
return {
errorValidations: [
{
id: "dummy",
messages: [{ path: "/foo", message: "Required by save" }],
},
],
};
}
return null;
}
const state = form.state(o, {
isRequired: (accessor) => accessor.path.startsWith("/foo"),
backend: { save },
});
const fooField = state.field("foo");
const barField = state.field("bar");
expect(fooField.required).toBeTruthy();
expect(barField.required).toBeFalsy();
// do something not allowed
fooField.setRaw("");
// we should see a problem immediately
expect(fooField.error).toEqual("Required");
// now communicate with the server by doing the save
const saved = await state.save();
expect(touched).toBeFalsy();
// cannot save as we didn't validate
expect(saved).toBe(false);
// still same client-side validation errors
expect(fooField.error).toEqual("Required");
// correct things
fooField.setRaw("BAR");
// editing always wipes out the errors
expect(fooField.error).toBeUndefined();
const saved2 = await state.save();
expect(fooField.error).toBeUndefined();
expect(saved2).toBeTruthy();
expect(touched).toBeTruthy();
});
test("string is trimmed and save", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: " FOO" });
const form = new Form(M, {
foo: new Field(converters.string),
});
let saved = null;
async function save(data: any) {
saved = data;
return null;
}
const state = form.state(o, { backend: { save } });
const field = state.field("foo");
await state.save();
expect(field.value).toEqual("FOO");
expect(saved).toEqual({ foo: "FOO" });
});
test("stringArray required save empty", async () => {
const M = types.model("M", {
stringArray: types.array(types.string),
});
const form = new Form(M, {
stringArray: new Field(converters.stringArray, { required: true }),
});
const o = M.create({ stringArray: [] });
const state = form.state(o, {
isRequired: () => true,
backend: { save: async () => null },
});
const stringArrayField = state.field("stringArray");
expect(stringArrayField.raw).toEqual([]);
expect(stringArrayField.error).toBeUndefined();
await state.save();
expect(stringArrayField.error).toEqual("Required");
});
test("stringArray required save filled", async () => {
const M = types.model("M", {
stringArray: types.array(types.string),
});
const form = new Form(M, {
stringArray: new Field(converters.stringArray, { required: true }),
});
const o = M.create({ stringArray: ["Test", "Kees"] });
const state = form.state(o, {
isRequired: () => true,
backend: { save: async () => null },
});
const stringArrayField = state.field("stringArray");
expect(stringArrayField.raw).toEqual(["Test", "Kees"]);
expect(stringArrayField.error).toBeUndefined();
await state.save();
expect(stringArrayField.error).toBeUndefined();
});
test("stringArray not required save empty", async () => {
const M = types.model("M", {
stringArray: types.array(types.string),
});
const form = new Form(M, {
stringArray: new Field(converters.stringArray),
});
const o = M.create({ stringArray: [] });
const state = form.state(o, {
backend: { save: async () => null },
});
const stringArrayField = state.field("stringArray");
expect(stringArrayField.raw).toEqual([]);
expect(stringArrayField.error).toBeUndefined();
await state.save();
expect(stringArrayField.error).toBeUndefined();
});
test("stringArray not required save filled", async () => {
const M = types.model("M", {
stringArray: types.array(types.string),
});
const form = new Form(M, {
stringArray: new Field(converters.stringArray),
});
const o = M.create({ stringArray: ["Worst", "Kees", "Scenario"] });
const state = form.state(o, {
backend: { save: async () => null },
});
const stringArrayField = state.field("stringArray");
expect(stringArrayField.raw).toEqual(["Worst", "Kees", "Scenario"]);
expect(stringArrayField.error).toBeUndefined();
await state.save();
expect(stringArrayField.error).toBeUndefined();
});
test("textStringArray required save empty", async () => {
const M = types.model("M", {
textStringArray: types.array(types.string),
});
const form = new Form(M, {
textStringArray: new Field(converters.textStringArray, { required: true }),
});
const o = M.create({ textStringArray: [""] });
const state = form.state(o, {
isRequired: () => true,
backend: { save: async () => null },
});
const textStringArray = state.field("textStringArray");
expect(textStringArray.raw).toEqual("");
expect(textStringArray.error).toBeUndefined();
await state.save();
expect(textStringArray.error).toEqual("Required");
});
test("textStringArray required save filled", async () => {
const M = types.model("M", {
textStringArray: types.array(types.string),
});
const form = new Form(M, {
textStringArray: new Field(converters.textStringArray, { required: true }),
});
const o = M.create({ textStringArray: ["test"] });
const state = form.state(o, {
isRequired: () => true,
backend: { save: async () => null },
});
const textStringArray = state.field("textStringArray");
expect(textStringArray.raw).toEqual("test");
expect(textStringArray.error).toBeUndefined();
await state.save();
expect(textStringArray.error).toBeUndefined();
}); | the_stack |
import { TestBed, fakeAsync, ComponentFixture, tick, flush } from '@angular/core/testing';
import { Component, Type } from '@angular/core';
import { MdcRadioInputDirective, MdcRadioDirective } from './mdc.radio.directive';
import { hasRipple } from '../../testutils/page.test';
import { By } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
describe('MdcRadioDirective', () => {
it('should render the mdcRadio with ripple and label', fakeAsync(() => {
const { fixture } = setup();
const root = fixture.nativeElement.querySelector('.mdc-radio');
expect(root.children.length).toBe(3);
expect(root.children[0].classList).toContain('mdc-radio__native-control');
expect(root.children[1].classList).toContain('mdc-radio__background');
expect(root.children[2].classList).toContain('mdc-radio__ripple');
expect(hasRipple(root)).toBe(true, 'the ripple element should be attached');
}));
it('checked can be set programmatically', fakeAsync(() => {
const { fixture, testComponent, elements } = setup();
expect(testComponent.value).toBe(null);
for (let i in [0, 1, 2])
expect(elements[i].checked).toBe(false);
setAndCheck(fixture, 'r1', [true, false, false]);
setAndCheck(fixture, 'r2', [false, true, false]);
setAndCheck(fixture, 'r3', [false, false, true]);
setAndCheck(fixture, 'doesnotexist', [false, false, false]);
setAndCheck(fixture, null, [false, false, false]);
setAndCheck(fixture, '', [false, false, false]);
}));
it('checked can be set by user', fakeAsync(() => {
const { fixture, testComponent, elements, inputs } = setup();
elements[1].click();
tick(); fixture.detectChanges();
expect(elements.map(e => e.checked)).toEqual([false, true, false]);
expect(testComponent.value).toBe('r2');
}));
it('can be disabled', fakeAsync(() => {
const { fixture, testComponent, elements, inputs } = setup();
testComponent.disabled = true;
fixture.detectChanges();
for (let i in [0, 1, 2]) {
expect(elements[i].disabled).toBe(true);
expect(inputs[i].disabled).toBe(true);
}
expect(testComponent.disabled).toBe(true);
const radio = fixture.debugElement.query(By.directive(MdcRadioDirective)).injector.get(MdcRadioDirective);
expect(radio['isRippleSurfaceDisabled']()).toBe(true);
expect(radio['root'].nativeElement.classList).toContain('mdc-radio--disabled');
testComponent.disabled = false;
fixture.detectChanges();
for (let i in [0, 1, 2]) {
expect(elements[i].disabled).toBe(false);
expect(inputs[i].disabled).toBe(false);
}
expect(testComponent.disabled).toBe(false);
expect(radio['isRippleSurfaceDisabled']()).toBe(false);
expect(radio['root'].nativeElement.classList).not.toContain('mdc-radio--disabled');
}));
it('native input can be changed dynamically', fakeAsync(() => {
const { fixture, testComponent } = setup(TestComponentDynamicInput);
let elements = fixture.nativeElement.querySelectorAll('.mdc-radio__native-control');
// when no input is present the mdcRadio renders without an initialized foundation:
expect(elements.length).toBe(0);
let check = false;
for (let i = 0; i != 3; ++i) {
// render/include one of the inputs:
testComponent.input = i;
fixture.detectChanges();
// the input should be recognized, the foundation is (re)initialized,
// so we have a fully functional mdcRadio now:
elements = fixture.nativeElement.querySelectorAll('.mdc-radio__native-control');
expect(elements.length).toBe(1);
expect(elements[0].classList).toContain('mdc-radio__native-control');
expect(elements[0].id).toBe(`i${i}`);
// the value of the native input is correctly synced with the testcomponent:
expect(elements[0].checked).toBe(check);
// change the value for the next iteration:
check = !check;
testComponent.checked = check;
fixture.detectChanges();
expect(elements[0].checked).toBe(check);
}
// removing input should also work:
testComponent.input = null;
fixture.detectChanges();
elements = fixture.nativeElement.querySelectorAll('.mdc-radio__native-control');
// when no input is present the mdcRadio renders without an initialized foundation:
expect(elements.length).toBe(0);
expect(testComponent.checked).toBe(check);
}));
it('user interactions are registered in the absence of template bindings', fakeAsync(() => {
const { fixture, elements, inputs } = setup(TestComponentNoBinding);
expect(elements.map(e => e.checked)).toEqual([false, false, false]);
elements[1].click();
fixture.detectChanges();
expect(elements.map(e => e.checked)).toEqual([false, true, false]);
}));
function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any, expected: boolean[]) {
const testComponent = fixture.debugElement.injector.get(TestComponent);
const elements: HTMLInputElement[] = Array.from(fixture.nativeElement.querySelectorAll('.mdc-radio__native-control'));
testComponent.value = value;
fixture.detectChanges();
expect(elements.map(e => e.checked)).toEqual(expected);
}
@Component({
template: `
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r1" [checked]="value === 'r1'" (click)="value = 'r1'" [disabled]="disabled"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r2" [checked]="value === 'r2'" (click)="value = 'r2'" [disabled]="disabled"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r3" [checked]="value === 'r3'" (click)="value = 'r3'" [disabled]="disabled"/></div>
`
})
class TestComponent {
value: any = null;
disabled: any = null;
}
@Component({
template: `
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r1"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r2"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r3"/></div>
`
})
class TestComponentNoBinding {
}
@Component({
template: `
<div mdcRadio>
<input *ngIf="input === 0" id="i0" mdcRadioInput type="radio" [checked]="checked"/>
<input *ngIf="input === 1" id="i1" mdcRadioInput type="radio" [checked]="checked"/>
<input *ngIf="input === 2" id="i2" mdcRadioInput type="radio" [checked]="checked"/>
</div>
`
})
class TestComponentDynamicInput {
input: number = null;
checked: any = null;
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [MdcRadioInputDirective, MdcRadioDirective, compType]
}).createComponent(compType);
fixture.detectChanges();
const testComponent = fixture.debugElement.injector.get(compType);
const inputs = fixture.debugElement.queryAll(By.directive(MdcRadioInputDirective)).map(i => i.injector.get(MdcRadioInputDirective));
const elements: HTMLInputElement[] = Array.from(fixture.nativeElement.querySelectorAll('.mdc-radio__native-control'));
return { fixture, testComponent, inputs, elements };
}
});
describe('MdcRadioDirective with FormsModule', () => {
it('ngModel can be set programmatically', fakeAsync(() => {
const { fixture, testComponent, elements } = setup();
expect(testComponent.value).toBe(null);
for (let i in [0, 1, 2])
expect(elements[i].checked).toBe(false);
setAndCheck(fixture, 'r1', [true, false, false]);
setAndCheck(fixture, 'r2', [false, true, false]);
setAndCheck(fixture, 'r3', [false, false, true]);
setAndCheck(fixture, 'doesnotexist', [false, false, false]);
setAndCheck(fixture, null, [false, false, false]);
setAndCheck(fixture, '', [false, false, false]);
}));
it('ngModel can be changed by user', fakeAsync(() => {
const { fixture, testComponent, elements, inputs } = setup();
expect(elements.map(e => e.checked)).toEqual([false, false, false]);
expect(testComponent.value).toBe(null);
elements[0].click();
fixture.detectChanges();
expect(elements.map(e => e.checked)).toEqual([true, false, false]);
expect(testComponent.value).toBe('r1');
elements[2].click();
fixture.detectChanges();
expect(elements.map(e => e.checked)).toEqual([false, false, true]);
expect(testComponent.value).toBe('r3');
}));
function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any, expected: boolean[]) {
const testComponent = fixture.debugElement.injector.get(TestComponent);
const elements: HTMLInputElement[] = Array.from(fixture.nativeElement.querySelectorAll('.mdc-radio__native-control'));
testComponent.value = value;
fixture.detectChanges(); flush();
expect(elements.map(e => e.checked)).toEqual(expected);
}
@Component({
template: `
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r1" [(ngModel)]="value"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r2" [(ngModel)]="value"/></div>
<div mdcRadio><input mdcRadioInput type="radio" name="group" value="r3" [(ngModel)]="value"/></div>
`
})
class TestComponent {
value: any = null;
}
function setup() {
const fixture = TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [MdcRadioInputDirective, MdcRadioDirective, TestComponent]
}).createComponent(TestComponent);
fixture.detectChanges();
tick();
const testComponent = fixture.debugElement.injector.get(TestComponent);
const inputs = fixture.debugElement.queryAll(By.directive(MdcRadioInputDirective)).map(i => i.injector.get(MdcRadioInputDirective));
const elements: HTMLInputElement[] = Array.from(fixture.nativeElement.querySelectorAll('.mdc-radio__native-control'));
return { fixture, testComponent, inputs, elements };
}
}); | the_stack |
import { useModel } from '@@/plugin-model/useModel'
import {
Box,
Button,
ButtonGroup,
Checkbox,
HStack,
IconButton,
Input,
InputGroup,
InputLeftElement,
Spacer,
Spinner,
useColorMode,
VStack,
} from '@chakra-ui/react'
import ItemIcon from '@renderer/components/ItemIcon'
import { actions, agent } from '@renderer/core/agent'
import { PopupMenu } from '@renderer/core/PopupMenu'
import useOnBroadcast from '@renderer/core/useOnBroadcast'
import { HostsType } from '@root/common/data'
import events from '@root/common/events'
import {
IFindItem,
IFindPosition,
IFindShowSourceParam,
} from '@root/common/types'
import { useDebounce, useDebounceFn } from 'ahooks'
import clsx from 'clsx'
import lodash from 'lodash'
import React, { useEffect, useRef, useState } from 'react'
import {
IoArrowBackOutline,
IoArrowForwardOutline,
IoChevronDownOutline,
IoSearch,
} from 'react-icons/io5'
import AutoSizer from 'react-virtualized-auto-sizer'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import scrollIntoView from 'smooth-scroll-into-view-if-needed'
import styles from './find.less'
interface Props {}
interface IFindPositionShow extends IFindPosition {
item_id: string
item_title: string
item_type: HostsType
index: number
is_disabled?: boolean
is_readonly?: boolean
}
const find = (props: Props) => {
const { lang, i18n, setLocale } = useModel('useI18n')
const { configs, loadConfigs } = useModel('useConfigs')
const { colorMode, setColorMode } = useColorMode()
const [keyword, setKeyword] = useState('')
const [replace_to, setReplaceTo] = useState('')
const [is_regexp, setIsRegExp] = useState(false)
const [is_ignore_case, setIsIgnoreCase] = useState(false)
const [find_result, setFindResult] = useState<IFindItem[]>([])
const [find_positions, setFindPositions] = useState<IFindPositionShow[]>([])
const [is_searching, setIsSearching] = useState(false)
const [current_result_idx, setCurrentResultIdx] = useState(0)
const [last_scroll_result_idx, setlastScrollResultIdx] = useState(-1)
const debounced_keyword = useDebounce(keyword, { wait: 500 })
const ipt_kw = useRef<HTMLInputElement>(null)
const init = async () => {
if (!configs) return
setLocale(configs.locale)
let theme = configs.theme
let cls = document.body.className
document.body.className = cls.replace(/\btheme-\w+/gi, '')
document.body.classList.add(`platform-${agent.platform}`, `theme-${theme}`)
}
useEffect(() => {
if (!configs) return
init().catch((e) => console.error(e))
console.log(configs.theme)
if (colorMode !== configs.theme) {
setColorMode(configs.theme)
}
}, [configs])
useEffect(() => {
console.log(lang.find_and_replace)
document.title = lang.find_and_replace
}, [lang])
useEffect(() => {
doFind(debounced_keyword)
}, [debounced_keyword, is_regexp, is_ignore_case])
useEffect(() => {
const onFocus = () => {
if (ipt_kw.current) {
ipt_kw.current.focus()
}
}
window.addEventListener('focus', onFocus, false)
return () => window.removeEventListener('focus', onFocus, false)
}, [ipt_kw])
useOnBroadcast(events.config_updated, loadConfigs)
useOnBroadcast(events.close_find, () => {
console.log('on close find...')
setFindResult([])
setFindPositions([])
setKeyword('')
setReplaceTo('')
setIsRegExp(false)
setIsIgnoreCase(false)
setCurrentResultIdx(-1)
setlastScrollResultIdx(-1)
})
const parsePositionShow = (find_items: IFindItem[]) => {
let positions_show: IFindPositionShow[] = []
find_items.map((item) => {
let { item_id, item_title, item_type, positions } = item
positions.map((p, index) => {
positions_show.push({
item_id,
item_title,
item_type,
...p,
index,
is_readonly: item_type !== 'local',
})
})
})
setFindPositions(positions_show)
}
const { run: doFind } = useDebounceFn(
async (v: string) => {
console.log('find by:', v)
if (!v) {
setFindResult([])
return
}
setIsSearching(true)
let result = await actions.findBy(v, {
is_regexp,
is_ignore_case,
})
setCurrentResultIdx(0)
setlastScrollResultIdx(0)
setFindResult(result)
parsePositionShow(result)
setIsSearching(false)
await actions.findAddHistory({
value: v,
is_regexp,
is_ignore_case,
})
},
{ wait: 500 },
)
const toShowSource = async (result_item: IFindPositionShow) => {
// console.log(result_item)
await actions.cmdFocusMainWindow()
agent.broadcast(
events.show_source,
lodash.pick<IFindShowSourceParam>(result_item, [
'item_id',
'start',
'end',
'match',
'line',
'line_pos',
'end_line',
'end_line_pos',
]),
)
}
const replaceOne = async () => {
let pos: IFindPositionShow = find_positions[current_result_idx]
if (!pos) return
setFindPositions([
...find_positions.slice(0, current_result_idx),
{
...pos,
is_disabled: true,
},
...find_positions.slice(current_result_idx + 1),
])
if (replace_to) {
actions.findAddReplaceHistory(replace_to).catch((e) => console.error(e))
}
let r = find_result.find((i) => i.item_id === pos.item_id)
if (!r) return
let spliters = r.spliters
let sp = spliters[pos.index]
if (!sp) return
sp.replace = replace_to
const content = spliters
.map((sp) => `${sp.before}${sp.replace ?? sp.match}${sp.after}`)
.join('')
await actions.setHostsContent(pos.item_id, content)
agent.broadcast(events.hosts_refreshed_by_id, pos.item_id)
if (current_result_idx < find_positions.length - 1) {
setCurrentResultIdx(current_result_idx + 1)
}
}
const replaceAll = async () => {
for (let item of find_result) {
let { item_id, item_type, spliters } = item
if (item_type !== 'local') continue
const content = spliters
.map((sp) => `${sp.before}${replace_to}${sp.after}`)
.join('')
await actions.setHostsContent(item_id, content)
agent.broadcast(events.hosts_refreshed_by_id, item_id)
}
setFindPositions(
find_positions.map((pos) => ({
...pos,
is_disabled: !pos.is_readonly,
})),
)
if (replace_to) {
actions.findAddReplaceHistory(replace_to).catch((e) => console.error(e))
}
}
const ResultRow = (row_data: ListChildComponentProps) => {
const data = find_positions[row_data.index]
const el = useRef<HTMLDivElement>(null)
const is_selected = current_result_idx === row_data.index
useEffect(() => {
if (
el.current &&
is_selected &&
current_result_idx !== last_scroll_result_idx
) {
setlastScrollResultIdx(current_result_idx)
scrollIntoView(el.current, {
behavior: 'smooth',
scrollMode: 'if-needed',
}).catch((e) => console.error(e))
}
}, [el, current_result_idx, last_scroll_result_idx])
return (
<Box
style={row_data.style}
className={clsx(
styles.result_row,
is_selected && styles.selected,
data.is_disabled && styles.disabled,
data.is_readonly && styles.readonly,
)}
borderBottomWidth={1}
borderBottomColor={configs?.theme === 'dark' ? 'gray.600' : 'gray.200'}
onClick={() => {
setCurrentResultIdx(row_data.index)
}}
onDoubleClick={() => toShowSource(data)}
ref={el}
title={lang.to_show_source}
>
<div className={styles.result_content}>
{data.is_readonly ? (
<span className={styles.read_only}>{lang.read_only}</span>
) : null}
<span>{data.before}</span>
<span className={styles.highlight}>{data.match}</span>
<span>{data.after}</span>
</div>
<div className={styles.result_title}>
<ItemIcon type={data.item_type} />
<span>{data.item_title}</span>
</div>
<div className={styles.result_line}>{data.line}</div>
</Box>
)
}
const showKeywordHistory = async () => {
let history = await actions.findGetHistory()
if (history.length === 0) return
let menu = new PopupMenu(
history.reverse().map((i) => ({
label: i.value,
click() {
setKeyword(i.value)
setIsRegExp(i.is_regexp)
setIsIgnoreCase(i.is_ignore_case)
},
})),
)
menu.show()
}
const showReplaceHistory = async () => {
let history = await actions.findGetReplaceHistory()
if (history.length === 0) return
let menu = new PopupMenu(
history.reverse().map((v) => ({
label: v,
click() {
setReplaceTo(v)
},
})),
)
menu.show()
}
let can_replace = true
if (current_result_idx > -1) {
let pos = find_positions[current_result_idx]
if (pos?.is_disabled || pos?.is_readonly) {
can_replace = false
}
}
return (
<div className={styles.root}>
<VStack spacing={0} h="100%">
<InputGroup>
<InputLeftElement
// pointerEvents="none"
children={
<HStack spacing={0}>
<IoSearch />
<IoChevronDownOutline style={{ fontSize: 10 }} />
</HStack>
}
onClick={showKeywordHistory}
/>
<Input
autoFocus={true}
placeholder="keywords"
variant="flushed"
value={keyword}
onChange={(e) => {
setKeyword(e.target.value)
}}
ref={ipt_kw}
/>
</InputGroup>
<InputGroup>
<InputLeftElement
// pointerEvents="none"
children={
<HStack spacing={0}>
<IoSearch />
<IoChevronDownOutline style={{ fontSize: 10 }} />
</HStack>
}
onClick={showReplaceHistory}
/>
<Input
placeholder="replace to"
variant="flushed"
value={replace_to}
onChange={(e) => {
setReplaceTo(e.target.value)
}}
/>
</InputGroup>
<HStack
w="100%"
py={2}
px={4}
spacing={4}
// justifyContent="flex-start"
>
<Checkbox
checked={is_regexp}
onChange={(e) => setIsRegExp(e.target.checked)}
>
{lang.regexp}
</Checkbox>
<Checkbox
checked={is_ignore_case}
onChange={(e) => setIsIgnoreCase(e.target.checked)}
>
{lang.ignore_case}
</Checkbox>
</HStack>
<Box w="100%" borderTopWidth={1}>
<div className={styles.result_row}>
<div>{lang.match}</div>
<div>{lang.title}</div>
<div>{lang.line}</div>
</div>
</Box>
<Box
w="100%"
flex="1"
bgColor={configs?.theme === 'dark' ? 'gray.700' : 'gray.100'}
>
<AutoSizer>
{({ width, height }) => (
<List
width={width}
height={height}
itemCount={find_positions.length}
itemSize={28}
>
{ResultRow}
</List>
)}
</AutoSizer>
</Box>
<HStack
w="100%"
py={2}
px={4}
spacing={4}
// justifyContent="flex-end"
>
{is_searching ? (
<Spinner />
) : (
<span>
{i18n.trans(
find_positions.length > 1 ? 'items_found' : 'item_found',
[find_positions.length.toLocaleString()],
)}
</span>
)}
<Spacer />
<Button
size="sm"
variant="outline"
isDisabled={is_searching || find_positions.length === 0}
onClick={replaceAll}
>
{lang.replace_all}
</Button>
<Button
size="sm"
variant="solid"
colorScheme="blue"
isDisabled={
is_searching || find_positions.length === 0 || !can_replace
}
onClick={replaceOne}
>
{lang.replace}
</Button>
<ButtonGroup
size="sm"
isAttached
variant="outline"
isDisabled={is_searching || find_positions.length === 0}
>
<IconButton
aria-label="previous"
icon={<IoArrowBackOutline />}
onClick={() => {
let idx = current_result_idx - 1
if (idx < 0) idx = 0
setCurrentResultIdx(idx)
}}
isDisabled={current_result_idx <= 0}
/>
<IconButton
aria-label="next"
icon={<IoArrowForwardOutline />}
onClick={() => {
let idx = current_result_idx + 1
if (idx > find_positions.length - 1)
idx = find_positions.length - 1
setCurrentResultIdx(idx)
}}
isDisabled={current_result_idx >= find_positions.length - 1}
/>
</ButtonGroup>
</HStack>
</VStack>
</div>
)
}
export default find | the_stack |
import Long from "long";
import { grpc } from "@improbable-eng/grpc-web";
import _m0 from "protobufjs/minimal";
import { BrowserHeaders } from "browser-headers";
export const protobufPackage = "kubeappsapis.core.plugins.v1alpha1";
/**
* GetConfiguredPluginsRequest
*
* Request for GetConfiguredPlugins
*/
export interface GetConfiguredPluginsRequest {}
/**
* GetConfiguredPluginsResponse
*
* Response for GetConfiguredPlugins
*/
export interface GetConfiguredPluginsResponse {
/**
* Plugins
*
* List of Plugin
*/
plugins: Plugin[];
}
/**
* Plugin
*
* A plugin can implement multiple services and multiple versions of a service.
*/
export interface Plugin {
/**
* Plugin name
*
* The name of the plugin, such as `fluxv2.packages` or `kapp_controller.packages`.
*/
name: string;
/**
* Plugin version
*
* The version of the plugin, such as v1alpha1
*/
version: string;
}
const baseGetConfiguredPluginsRequest: object = {};
export const GetConfiguredPluginsRequest = {
encode(_: GetConfiguredPluginsRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): GetConfiguredPluginsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseGetConfiguredPluginsRequest,
} as GetConfiguredPluginsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): GetConfiguredPluginsRequest {
const message = {
...baseGetConfiguredPluginsRequest,
} as GetConfiguredPluginsRequest;
return message;
},
toJSON(_: GetConfiguredPluginsRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<GetConfiguredPluginsRequest>): GetConfiguredPluginsRequest {
const message = {
...baseGetConfiguredPluginsRequest,
} as GetConfiguredPluginsRequest;
return message;
},
};
const baseGetConfiguredPluginsResponse: object = {};
export const GetConfiguredPluginsResponse = {
encode(
message: GetConfiguredPluginsResponse,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
for (const v of message.plugins) {
Plugin.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): GetConfiguredPluginsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseGetConfiguredPluginsResponse,
} as GetConfiguredPluginsResponse;
message.plugins = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.plugins.push(Plugin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): GetConfiguredPluginsResponse {
const message = {
...baseGetConfiguredPluginsResponse,
} as GetConfiguredPluginsResponse;
message.plugins = [];
if (object.plugins !== undefined && object.plugins !== null) {
for (const e of object.plugins) {
message.plugins.push(Plugin.fromJSON(e));
}
}
return message;
},
toJSON(message: GetConfiguredPluginsResponse): unknown {
const obj: any = {};
if (message.plugins) {
obj.plugins = message.plugins.map(e => (e ? Plugin.toJSON(e) : undefined));
} else {
obj.plugins = [];
}
return obj;
},
fromPartial(object: DeepPartial<GetConfiguredPluginsResponse>): GetConfiguredPluginsResponse {
const message = {
...baseGetConfiguredPluginsResponse,
} as GetConfiguredPluginsResponse;
message.plugins = [];
if (object.plugins !== undefined && object.plugins !== null) {
for (const e of object.plugins) {
message.plugins.push(Plugin.fromPartial(e));
}
}
return message;
},
};
const basePlugin: object = { name: "", version: "" };
export const Plugin = {
encode(message: Plugin, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.name !== "") {
writer.uint32(10).string(message.name);
}
if (message.version !== "") {
writer.uint32(18).string(message.version);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Plugin {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePlugin } as Plugin;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.name = reader.string();
break;
case 2:
message.version = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Plugin {
const message = { ...basePlugin } as Plugin;
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.version !== undefined && object.version !== null) {
message.version = String(object.version);
} else {
message.version = "";
}
return message;
},
toJSON(message: Plugin): unknown {
const obj: any = {};
message.name !== undefined && (obj.name = message.name);
message.version !== undefined && (obj.version = message.version);
return obj;
},
fromPartial(object: DeepPartial<Plugin>): Plugin {
const message = { ...basePlugin } as Plugin;
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.version !== undefined && object.version !== null) {
message.version = object.version;
} else {
message.version = "";
}
return message;
},
};
export interface PluginsService {
/** GetConfiguredPlugins returns a map of short and longnames for the configured plugins. */
GetConfiguredPlugins(
request: DeepPartial<GetConfiguredPluginsRequest>,
metadata?: grpc.Metadata,
): Promise<GetConfiguredPluginsResponse>;
}
export class PluginsServiceClientImpl implements PluginsService {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
this.GetConfiguredPlugins = this.GetConfiguredPlugins.bind(this);
}
GetConfiguredPlugins(
request: DeepPartial<GetConfiguredPluginsRequest>,
metadata?: grpc.Metadata,
): Promise<GetConfiguredPluginsResponse> {
return this.rpc.unary(
PluginsServiceGetConfiguredPluginsDesc,
GetConfiguredPluginsRequest.fromPartial(request),
metadata,
);
}
}
export const PluginsServiceDesc = {
serviceName: "kubeappsapis.core.plugins.v1alpha1.PluginsService",
};
export const PluginsServiceGetConfiguredPluginsDesc: UnaryMethodDefinitionish = {
methodName: "GetConfiguredPlugins",
service: PluginsServiceDesc,
requestStream: false,
responseStream: false,
requestType: {
serializeBinary() {
return GetConfiguredPluginsRequest.encode(this).finish();
},
} as any,
responseType: {
deserializeBinary(data: Uint8Array) {
return {
...GetConfiguredPluginsResponse.decode(data),
toObject() {
return this;
},
};
},
} as any,
};
interface UnaryMethodDefinitionishR extends grpc.UnaryMethodDefinition<any, any> {
requestStream: any;
responseStream: any;
}
type UnaryMethodDefinitionish = UnaryMethodDefinitionishR;
interface Rpc {
unary<T extends UnaryMethodDefinitionish>(
methodDesc: T,
request: any,
metadata: grpc.Metadata | undefined,
): Promise<any>;
}
export class GrpcWebImpl {
private host: string;
private options: {
transport?: grpc.TransportFactory;
debug?: boolean;
metadata?: grpc.Metadata;
};
constructor(
host: string,
options: {
transport?: grpc.TransportFactory;
debug?: boolean;
metadata?: grpc.Metadata;
},
) {
this.host = host;
this.options = options;
}
unary<T extends UnaryMethodDefinitionish>(
methodDesc: T,
_request: any,
metadata: grpc.Metadata | undefined,
): Promise<any> {
const request = { ..._request, ...methodDesc.requestType };
const maybeCombinedMetadata =
metadata && this.options.metadata
? new BrowserHeaders({
...this.options?.metadata.headersMap,
...metadata?.headersMap,
})
: metadata || this.options.metadata;
return new Promise((resolve, reject) => {
grpc.unary(methodDesc, {
request,
host: this.host,
metadata: maybeCombinedMetadata,
transport: this.options.transport,
debug: this.options.debug,
onEnd: function (response) {
if (response.status === grpc.Code.OK) {
resolve(response.message);
} else {
const err = new Error(response.statusMessage) as any;
err.code = response.status;
err.metadata = response.trailers;
reject(err);
}
},
});
});
}
}
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
if (_m0.util.Long !== Long) {
_m0.util.Long = Long as any;
_m0.configure();
} | the_stack |
export interface FxError extends Error {
/**
* Custom error details.
*/
innerError?: any;
/**
* Source name of error. (plugin name, eg: tab-scaffhold-plugin)
*/
source: string;
/**
* Time of error.
*/
timestamp: Date;
userData?: any;
}
export interface ErrorOptionBase {
source?: string;
name?: string;
message?: string;
error?: Error;
userData?: any;
notificationMessage?: string;
}
export interface UserErrorOptions extends ErrorOptionBase {
helpLink?: string;
}
export interface SystemErrorOptions extends ErrorOptionBase {
issueLink?: string;
}
/**
* Users can recover by themselves, e.g., users input invalid app names.
*/
export class UserError extends Error implements FxError {
/**
* Custom error details .
*/
innerError?: any;
/**
* Source name of error. (plugin name, eg: tab-scaffold-plugin)
*/
source: string;
/**
* Time of error.
*/
timestamp: Date;
/**
* A wiki website that shows mapping relationship between error names, descriptions, and fix solutions.
*/
helpLink?: string;
/**
* data that only be reported to github issue manually by user and will not be reported as telemetry data
*/
userData?: string;
/**
* customized message instead of error message which will be shown in notification box
*/
notificationMessage?: string;
constructor(
error: Error,
source?: string,
name?: string,
helpLink?: string,
notificationMessage?: string
);
constructor(opt: UserErrorOptions);
constructor(
name: string,
message: string,
source: string,
stack?: string,
helpLink?: string,
innerError?: any,
notificationMessage?: string
);
constructor(
param1: string | Error | UserErrorOptions,
param2?: string,
param3?: string,
param4?: string,
param5?: string,
innerError?: any,
notificationMessage?: string
) {
let option: UserErrorOptions;
let stack: string | undefined;
if (typeof param1 === "string") {
option = {
name: param1,
message: param2,
source: param3,
helpLink: param5,
notificationMessage: notificationMessage,
error: innerError instanceof Error ? innerError : undefined,
};
if (innerError instanceof Error) {
stack = innerError.stack;
}
} else if (param1 instanceof Error) {
option = {
error: param1,
name: param3,
source: param2,
helpLink: param4,
notificationMessage: param5,
};
stack = param1.stack;
} else {
option = param1;
}
// message
const messages = new Set<string>();
if (option.message) messages.add(option.message);
if (option.error && option.error.message) messages.add(option.error.message);
const message = Array.from(messages).join(", ") || "";
super(message);
//name
this.name = option.name || (option.error && option.error.name) || new.target.name;
//source
this.source = option.source || "unknown";
//stack
if (stack) {
this.stack = stack;
} else {
Error.captureStackTrace(this, new.target);
}
//prototype
Object.setPrototypeOf(this, new.target.prototype);
//innerError
if (typeof param1 === "string") {
this.innerError = innerError;
} else if (param1 instanceof Error) {
this.innerError = param1;
}
//other fields
this.helpLink = option.helpLink;
this.userData = option.userData;
this.notificationMessage = option.notificationMessage;
this.timestamp = new Date();
}
}
/**
* Users cannot handle it by themselves.
*/
export class SystemError extends Error implements FxError {
/**
* Custom error details.
*/
innerError?: any;
/**
* Source name of error. (plugin name, eg: tab-scaffold-plugin)
*/
source: string;
/**
* Time of error.
*/
timestamp: Date;
/**
* A github issue page where users can submit a new issue.
*/
issueLink?: string;
/**
* data that only be reported to github issue manually by user and will not be reported as telemetry data
*/
userData?: string;
/**
* customized message instead of error message which will be shown in notification box
*/
notificationMessage?: string;
constructor(
error: Error,
source?: string,
name?: string,
issueLink?: string,
notificationMessage?: string
);
constructor(opt: SystemErrorOptions);
constructor(
name: string,
message: string,
source: string,
stack?: string,
issueLink?: string,
innerError?: any,
notificationMessage?: string
);
constructor(
param1: string | Error | SystemErrorOptions,
param2?: string,
param3?: string,
param4?: string,
param5?: string,
innerError?: any,
notificationMessage?: string
) {
let option: SystemErrorOptions;
let stack: string | undefined;
if (typeof param1 === "string") {
option = {
name: param1,
message: param2,
source: param3,
issueLink: param5,
notificationMessage: notificationMessage,
error: innerError instanceof Error ? innerError : undefined,
};
if (innerError instanceof Error) {
stack = innerError.stack;
}
} else if (param1 instanceof Error) {
option = {
error: param1,
name: param3,
source: param2,
issueLink: param4,
notificationMessage: param5,
};
stack = param1.stack;
} else {
option = param1;
}
// message
const messages = new Set<string>();
if (option.message) messages.add(option.message);
if (option.error && option.error.message) messages.add(option.error.message);
const message = Array.from(messages).join(", ") || "";
super(message);
//name
this.name = option.name || (option.error && option.error.name) || new.target.name;
//source
this.source = option.source || "unknown";
//stack
if (stack) {
this.stack = stack;
} else {
Error.captureStackTrace(this, new.target);
}
//prototype
Object.setPrototypeOf(this, new.target.prototype);
//innerError
if (typeof param1 === "string") {
this.innerError = innerError;
} else if (param1 instanceof Error) {
this.innerError = param1;
}
//other fields
this.issueLink = option.issueLink;
this.userData = option.userData;
this.notificationMessage = option.notificationMessage;
this.timestamp = new Date();
}
}
/**
*
* @param e Original error
* @param source Source name of error. (plugin name, eg: tab-scaffhold-plugin)
* @param name Name of error. (error name, eg: Dependency not found)
* @param helpLink A wiki website that shows mapping relationship between error names, descriptions, and fix solutions.
* @param innerError Custom error details.
*
* @returns UserError.
*/
export function returnUserError(
e: Error,
source: string,
name: string,
helpLink?: string,
innerError?: any
): UserError {
return new UserError(e, source, name, helpLink);
}
/**
*
* @param e Original error
* @param source Source name of error. (plugin name, eg: tab-scaffhold-plugin)
* @param name Name of error. (error name, eg: Dependency not found)
* @param issueLink A github issue page where users can submit a new issue.
* @param innerError Custom error details.
*
* @returns SystemError.
*/
export function returnSystemError(
e: Error,
source: string,
name: string,
issueLink?: string,
innerError?: any
): SystemError {
return new SystemError(e, source, name, issueLink);
}
export function assembleError(e: any, source?: string): FxError {
if (e instanceof UserError || e instanceof SystemError) return e;
if (!source) source = "unknown";
const type = typeof e;
if (type === "string") {
return new UnknownError(source, e as string);
} else if (e instanceof Error) {
const err = e as Error;
const fxError = new SystemError(err, source);
fxError.stack = err.stack;
return fxError;
} else {
return new UnknownError(source, JSON.stringify(e));
}
}
export class UnknownError extends SystemError {
constructor(source?: string, message?: string) {
super({ source: source || "API", message: message });
}
}
export const UserCancelError: UserError = new UserError("UserCancel", "UserCancel", "UI");
export class EmptyOptionError extends SystemError {
constructor(source?: string) {
super({ source: source || "API" });
}
}
export class PathAlreadyExistsError extends UserError {
constructor(source: string, path: string) {
super({ source: source, message: `Path ${path} already exists.` });
}
}
export class PathNotExistError extends UserError {
constructor(source: string, path: string) {
super({ source: source, message: `Path ${path} does not exist.` });
}
}
export class ObjectAlreadyExistsError extends UserError {
constructor(source: string, name: string) {
super({ source: source, message: `${name} already exists.` });
}
}
export class ObjectNotExistError extends UserError {
constructor(source: string, name: string) {
super({ source: source, message: `${name} does not exist.` });
}
}
export class UndefinedError extends SystemError {
constructor(source: string, name: string) {
super({ source: source, message: `${name} is undefined, which is not expected` });
}
}
export class NotImplementedError extends SystemError {
constructor(source: string, method: string) {
super({ source: source, message: `Method not implemented:${method}` });
}
}
export class WriteFileError extends SystemError {
constructor(source: string, e: Error) {
super({ source: source, error: e, name: "WriteFileError" });
}
}
export class ReadFileError extends SystemError {
constructor(source: string, e: Error) {
super({ source: source, error: e, name: "ReadFileError" });
}
}
export class NoProjectOpenedError extends UserError {
constructor(source: string) {
super({
source: source,
message: "No project opened, you can create a new project or open an existing one.",
});
}
}
export class ConcurrentError extends UserError {
constructor(source: string) {
super({
source: source,
message:
"Previous task is still running. Please wait util your previous task to finish and try again.",
});
}
}
export class InvalidInputError extends UserError {
constructor(source: string, name: string, reason?: string) {
super({ source: source, message: `Input '${name}' is invalid: ${reason}` });
}
}
export class InvalidProjectError extends UserError {
constructor(source: string, msg?: string) {
super({
source: source,
message: `The command only works for project created by Teams Toolkit. ${
msg ? ": " + msg : ""
}`,
});
}
}
export class InvalidObjectError extends UserError {
constructor(source: string, name: string, reason?: string) {
super({ source: source, message: `${name} is invalid: ${reason}` });
}
}
export class InvalidOperationError extends UserError {
constructor(source: string, name: string, reason?: string) {
super({ source: source, message: `Invalid operation: ${name} ${reason}` });
}
} | the_stack |
import {
AssertionKind,
BlockStatement,
ClassDeclaration,
CommonFlags,
FieldDeclaration,
MethodDeclaration,
NodeKind,
ParameterKind,
Range,
Statement,
Token,
TypeNode,
} from "./assemblyscript";
import { createGenericTypeParameter } from "./createGenericTypeParameter";
import { djb2Hash } from "./hash";
/**
* Create a prototype method called __aspectAddReflectedValueKeyValuePairs on a given
* ClassDeclaration dynamically.
*
* @param {ClassDeclaration} classDeclaration - The target classDeclaration
*/
export function createAddReflectedValueKeyValuePairsMember(
classDeclaration: ClassDeclaration,
): MethodDeclaration {
const range = classDeclaration.name.range;
// __aspectAddReflectedValueKeyValuePairs(reflectedValue: i32, seen: Map<usize, i32>, ignore: StaticArray<i64>): void
return TypeNode.createMethodDeclaration(
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
null,
CommonFlags.PUBLIC |
CommonFlags.INSTANCE |
(classDeclaration.isGeneric ? CommonFlags.GENERIC_CONTEXT : 0),
null,
TypeNode.createFunctionType(
[
// reflectedValue: i32
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("reflectedValue", range),
createGenericTypeParameter("i32", range),
null,
range,
),
// seen: Map<usize, i32>
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("seen", range),
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("Map", range),
[
createGenericTypeParameter("usize", range),
createGenericTypeParameter("i32", range),
],
false,
range,
),
null,
range,
),
// ignore: i64[]
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("ignore", range),
// Array<i64> -> i64[]
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("StaticArray", range),
[createGenericTypeParameter("i64", range)],
false,
range,
),
null,
range,
),
],
// : void
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("void", range),
[],
false,
range,
),
null,
false,
range,
),
createAddReflectedValueKeyValuePairsFunctionBody(classDeclaration),
range,
);
}
/**
* Iterate over a given ClassDeclaration and return a block statement that contains the
* body of a supposed function that reports the key value pairs of a given class.
*
* @param {ClassDeclaration} classDeclaration - The class declaration to be reported
*/
function createAddReflectedValueKeyValuePairsFunctionBody(
classDeclaration: ClassDeclaration,
): BlockStatement {
const body = new Array<Statement>();
const range = classDeclaration.name.range;
const nameHashes = new Array<number>();
// for each field declaration, generate a check
for (const member of classDeclaration.members) {
// if it's an instance member, regardless of access modifier
if (member.is(CommonFlags.INSTANCE)) {
switch (member.kind) {
// field declarations automatically get added
case NodeKind.FIELDDECLARATION: {
const fieldDeclaration = <FieldDeclaration>member;
const hashValue = djb2Hash(member.name.text);
pushKeyValueIfStatement(
body,
member.name.text,
hashValue,
fieldDeclaration.range,
);
nameHashes.push(hashValue);
break;
}
// function declarations can be getters, check the get flag
case NodeKind.METHODDECLARATION: {
if (member.is(CommonFlags.GET)) {
const methodDeclaration = <MethodDeclaration>member;
const hashValue = djb2Hash(member.name.text);
pushKeyValueIfStatement(
body,
member.name.text,
hashValue,
methodDeclaration.range,
);
nameHashes.push(hashValue);
}
break;
}
}
}
}
// call into super first after all the property checks have been added
body.unshift(createIsDefinedIfStatement(nameHashes, range));
return TypeNode.createBlockStatement(body, range);
}
/**
* Create an isDefined() function call with an if statement to prevent calls to
* super where they should not be made.
*
* @param {number[]} nameHashes - The array of property names to ignore in the children
* @param {Range} range - The reporting range of this statement
*/
function createIsDefinedIfStatement(
nameHashes: number[],
range: Range,
): Statement {
// if (isDefined(super.__aspectAddReflectedValueKeyValuePairs))
// super.__aspectAddReflectedValueKeyValuePairs(reflectedValue, seen, StaticArray.concat(ignore, [...] as StaticArray<i64>))
return TypeNode.createIfStatement(
// isDefined(super.__aspectAddReflectedValueKeyValuePairs)
TypeNode.createCallExpression(
TypeNode.createIdentifierExpression("isDefined", range),
null,
[
// super.__aspectAddReflectedValueKeyValuePairs
TypeNode.createPropertyAccessExpression(
TypeNode.createSuperExpression(range),
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
range,
),
],
range,
),
TypeNode.createBlockStatement(
[
TypeNode.createExpressionStatement(
// super.__aspectAddReflectedValueKeyValuePairs(reflectedValue, seen, StaticArray.concat(ignore, [...] as StaticArray<i64>))
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createSuperExpression(range),
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
range,
),
null,
[
// reflectedValue,
TypeNode.createIdentifierExpression("reflectedValue", range),
// seen,
TypeNode.createIdentifierExpression("seen", range),
// StaticArray.concat(ignore, [...])
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("StaticArray", range),
TypeNode.createIdentifierExpression("concat", range),
range,
),
null,
[
TypeNode.createIdentifierExpression("ignore", range),
// [...propNames]
TypeNode.createAssertionExpression(
AssertionKind.AS,
TypeNode.createArrayLiteralExpression(
nameHashes.map((e) =>
TypeNode.createIntegerLiteralExpression(
f64_as_i64(e),
range,
),
),
range,
),
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("StaticArray", range),
[
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("i64", range),
null,
false,
range,
),
],
false,
range,
),
range,
),
],
range,
),
],
range,
),
),
],
range,
),
null,
range,
);
}
/**
* For each key-value pair, we need to perform a runtime check to make sure that this property
* was not overridden in the parent of a given class.
*
* @param {Statement[]} body - The collection of statements for the function body
* @param {string} name - The name of the property
* @param {Range} range - The range for these statements
*/
function pushKeyValueIfStatement(
body: Statement[],
name: string,
hashValue: number,
range: Range,
): void {
body.push(
// if (!ignore.includes("propName")) { ... }
TypeNode.createIfStatement(
TypeNode.createUnaryPrefixExpression(
Token.EXCLAMATION,
// ignore.includes("propName")
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("ignore", range),
TypeNode.createIdentifierExpression("includes", range),
range,
),
null,
[
// hashValue
TypeNode.createIntegerLiteralExpression(
f64_as_i64(hashValue),
range,
),
],
range,
),
range,
),
TypeNode.createBlockStatement(
[
createPushReflectedObjectKeyStatement(name, range),
createPushReflectedObjectValueStatement(name, range),
],
range,
),
null,
range,
),
);
}
/**
* Create a function call to __aspectPushReflectedObjectKey to add a key to a given
* reflected value.
*
* @param {string} name - The name of the property
* @param {Range} range - The reange for this function call
*/
function createPushReflectedObjectKeyStatement(
name: string,
range: Range,
): Statement {
// __aspectPushReflectedObjectKey(reflectedValue, Reflect.toReflectedValue("propertyName", seen));
return TypeNode.createExpressionStatement(
TypeNode.createCallExpression(
TypeNode.createIdentifierExpression(
"__aspectPushReflectedObjectKey",
range,
),
null,
[
// reflectedValue
TypeNode.createIdentifierExpression("reflectedValue", range),
// Reflect.toReflectedValue("propertyName", seen)
TypeNode.createCallExpression(
// Reflect.toReflectedValue
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("Reflect", range),
TypeNode.createIdentifierExpression("toReflectedValue", range),
range,
),
null,
[
TypeNode.createStringLiteralExpression(name, range),
TypeNode.createIdentifierExpression("seen", range),
],
range,
),
],
range,
),
);
}
/**
* Create a function call to __aspectPushReflectedObjectValue to add a key to a given
* reflected value.
*
* @param {string} name - The name of the property
* @param {Range} range - The reange for this function call
*/
function createPushReflectedObjectValueStatement(
name: string,
range: Range,
): Statement {
// __aspectPushReflectedObjectValue(reflectedValue, Reflect.toReflectedValue(this.propertyName, seen, ignore.concat([...])));
return TypeNode.createExpressionStatement(
// __aspectPushReflectedObjectValue(reflectedValue, Reflect.toReflectedValue(this.propertyName, seen, ignore.concat([...])))
TypeNode.createCallExpression(
// __aspectPushReflectedObjectValue
TypeNode.createIdentifierExpression(
"__aspectPushReflectedObjectValue",
range,
),
null,
[
// reflectedValue
TypeNode.createIdentifierExpression("reflectedValue", range),
// Reflect.toReflectedValue(this.propertyName, seen))
TypeNode.createCallExpression(
// Reflect.toReflectedValue
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("Reflect", range),
TypeNode.createIdentifierExpression("toReflectedValue", range),
range,
),
null,
[
//this.propertyName
TypeNode.createPropertyAccessExpression(
TypeNode.createThisExpression(range),
TypeNode.createIdentifierExpression(name, range),
range,
),
// seen
TypeNode.createIdentifierExpression("seen", range),
],
range,
),
],
range,
),
);
} | the_stack |
import { AgModule, IconComponent } from 'agnostic-angular';
import {
moduleMetadata,
componentWrapperDecorator,
Meta,
} from '@storybook/angular';
export default {
title: 'AG—Angular (Beta)/Icon',
component: IconComponent,
decorators: [
// Cannot get preview.js or global decorator solutions to work.
// https://storybook.js.org/tutorials/intro-to-storybook/angular/en/composite-component/
componentWrapperDecorator(
(story) =>
`<div style="font-family: var(--agnostic-font-family-body)">${story}</div>`
),
moduleMetadata({
imports: [AgModule],
}),
],
} as Meta;
export const All = () => ({
template: `<section class="mbe32">
<p class="mbe24">The icon component is a light-weight bounding box around your SVG icon. You should be able to pass in
any well constructored icon set, but here are a few examples using popular ones.</p>
<h4>Material</h4>
<p class="mbe16">Material icons. If you'd like to control the sizing via CSS classes, you'll likely need to remove the
width and height attributes from the original SVGs.</p>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24">
<g>
<rect fill="none" height="24" width="24" />
</g>
<g>
<path d="M19,9.3V4h-3v2.6L12,3L2,12h3v8h6v-6h2v6h6v-8h3L19,9.3z M17,18h-2v-6H9v6H7v-7.81l5-4.5l5,4.5V18z" />
<path d="M10,10h4c0-1.1-0.9-2-2-2S10,8.9,10,10z" />
</g>
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M16 9v10H8V9h8m-1.5-6h-5l-1 1H5v2h14V4h-3.5l-1-1zM18 7H6v12c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7z" />
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5C2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3C19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</svg>
</ag-icon>
</section>
<section class="mbe32">
<h4>Octicons</h4>
<p class="mbe16">Octicons. If you'd like to control the sizing via CSS classes, you'll likely need to remove the width and height attributes.</p>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M16 1.75V3h5.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H8V1.75C8 .784 8.784 0 9.75 0h4.5C15.216 0 16 .784 16 1.75zm-6.5 0a.25.25 0 01.25-.25h4.5a.25.25 0 01.25.25V3h-5V1.75z" />
<path d="M4.997 6.178a.75.75 0 10-1.493.144L4.916 20.92a1.75 1.75 0 001.742 1.58h10.684a1.75 1.75 0 001.742-1.581l1.413-14.597a.75.75 0 00-1.494-.144l-1.412 14.596a.25.25 0 01-.249.226H6.658a.25.25 0 01-.249-.226L4.997 6.178z" />
<path d="M9.206 7.501a.75.75 0 01.793.705l.5 8.5A.75.75 0 119 16.794l-.5-8.5a.75.75 0 01.705-.793zm6.293.793A.75.75 0 1014 8.206l-.5 8.5a.75.75 0 001.498.088l.5-8.5z" />
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M6.736 4C4.657 4 2.5 5.88 2.5 8.514c0 3.107 2.324 5.96 4.861 8.12a29.66 29.66 0 004.566 3.175l.073.041.073-.04c.271-.153.661-.38 1.13-.674.94-.588 2.19-1.441 3.436-2.502 2.537-2.16 4.861-5.013 4.861-8.12C21.5 5.88 19.343 4 17.264 4c-2.106 0-3.801 1.389-4.553 3.643a.75.75 0 01-1.422 0C10.537 5.389 8.841 4 6.736 4zM12 20.703l.343.667a.75.75 0 01-.686 0l.343-.667zM1 8.513C1 5.053 3.829 2.5 6.736 2.5 9.03 2.5 10.881 3.726 12 5.605 13.12 3.726 14.97 2.5 17.264 2.5 20.17 2.5 23 5.052 23 8.514c0 3.818-2.801 7.06-5.389 9.262a31.146 31.146 0 01-5.233 3.576l-.025.013-.007.003-.002.001-.344-.666-.343.667-.003-.002-.007-.003-.025-.013A29.308 29.308 0 0110 20.408a31.147 31.147 0 01-3.611-2.632C3.8 15.573 1 12.332 1 8.514z" />
</svg>
</ag-icon>
</section>
<section class="mbe32">
<h4>Font Awesome</h4>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
<!-- Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<path d="M280.37 148.26L96 300.11V464a16 16 0 0 0 16 16l112.06-.29a16 16 0 0 0 15.92-16V368a16 16 0 0 1 16-16h64a16 16 0 0 1 16 16v95.64a16 16 0 0 0 16 16.05L464 480a16 16 0 0 0 16-16V300L295.67 148.26a12.19 12.19 0 0 0-15.3 0zM571.6 251.47L488 182.56V44.05a12 12 0 0 0-12-12h-56a12 12 0 0 0-12 12v72.61L318.47 43a48 48 0 0 0-61 0L4.34 251.47a12 12 0 0 0-1.6 16.9l25.5 31A12 12 0 0 0 45.15 301l235.22-193.74a12.19 12.19 0 0 1 15.3 0L530.9 301a12 12 0 0 0 16.9-1.6l25.5-31a12 12 0 0 0-1.7-16.93z" />
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
<!-- Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<path d="M268 416h24a12 12 0 0 0 12-12V188a12 12 0 0 0-12-12h-24a12 12 0 0 0-12 12v216a12 12 0 0 0 12 12zM432 80h-82.41l-34-56.7A48 48 0 0 0 274.41 0H173.59a48 48 0 0 0-41.16 23.3L98.41 80H16A16 16 0 0 0 0 96v16a16 16 0 0 0 16 16h16v336a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128h16a16 16 0 0 0 16-16V96a16 16 0 0 0-16-16zM171.84 50.91A6 6 0 0 1 177 48h94a6 6 0 0 1 5.15 2.91L293.61 80H154.39zM368 464H80V128h288zm-212-48h24a12 12 0 0 0 12-12V188a12 12 0 0 0-12-12h-24a12 12 0 0 0-12 12v216a12 12 0 0 0 12 12z" />
</svg>
</ag-icon>
<ag-icon size="16">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<path d="M458.4 64.3C400.6 15.7 311.3 23 256 79.3 200.7 23 111.4 15.6 53.6 64.3-21.6 127.6-10.6 230.8 43 285.5l175.4 178.7c10 10.2 23.4 15.9 37.6 15.9 14.3 0 27.6-5.6 37.6-15.8L469 285.6c53.5-54.7 64.7-157.9-10.6-221.3zm-23.6 187.5L259.4 430.5c-2.4 2.4-4.4 2.4-6.8 0L77.2 251.8c-36.5-37.2-43.9-107.6 7.3-150.7 38.9-32.7 98.9-27.8 136.5 10.5l35 35.7 35-35.7c37.8-38.5 97.8-43.2 136.5-10.6 51.1 43.1 43.5 113.9 7.3 150.8z" />
</svg>
</ag-icon>
</section>
<section class="mbe32">
<h4>Octicons Size 32</h4>
<ag-icon size="32">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="32">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M16 1.75V3h5.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H8V1.75C8 .784 8.784 0 9.75 0h4.5C15.216 0 16 .784 16 1.75zm-6.5 0a.25.25 0 01.25-.25h4.5a.25.25 0 01.25.25V3h-5V1.75z" />
<path d="M4.997 6.178a.75.75 0 10-1.493.144L4.916 20.92a1.75 1.75 0 001.742 1.58h10.684a1.75 1.75 0 001.742-1.581l1.413-14.597a.75.75 0 00-1.494-.144l-1.412 14.596a.25.25 0 01-.249.226H6.658a.25.25 0 01-.249-.226L4.997 6.178z" />
<path d="M9.206 7.501a.75.75 0 01.793.705l.5 8.5A.75.75 0 119 16.794l-.5-8.5a.75.75 0 01.705-.793zm6.293.793A.75.75 0 1014 8.206l-.5 8.5a.75.75 0 001.498.088l.5-8.5z" />
</svg>
</ag-icon>
<ag-icon size="32">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M6.736 4C4.657 4 2.5 5.88 2.5 8.514c0 3.107 2.324 5.96 4.861 8.12a29.66 29.66 0 004.566 3.175l.073.041.073-.04c.271-.153.661-.38 1.13-.674.94-.588 2.19-1.441 3.436-2.502 2.537-2.16 4.861-5.013 4.861-8.12C21.5 5.88 19.343 4 17.264 4c-2.106 0-3.801 1.389-4.553 3.643a.75.75 0 01-1.422 0C10.537 5.389 8.841 4 6.736 4zM12 20.703l.343.667a.75.75 0 01-.686 0l.343-.667zM1 8.513C1 5.053 3.829 2.5 6.736 2.5 9.03 2.5 10.881 3.726 12 5.605 13.12 3.726 14.97 2.5 17.264 2.5 20.17 2.5 23 5.052 23 8.514c0 3.818-2.801 7.06-5.389 9.262a31.146 31.146 0 01-5.233 3.576l-.025.013-.007.003-.002.001-.344-.666-.343.667-.003-.002-.007-.003-.025-.013A29.308 29.308 0 0110 20.408a31.147 31.147 0 01-3.611-2.632C3.8 15.573 1 12.332 1 8.514z" />
</svg>
</ag-icon>
</section>
<section class="mbe32">
<h4>Types</h4>
<ag-icon type="success" size="18">
<svg type="success" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon type="info" size="18">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M16 1.75V3h5.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H8V1.75C8 .784 8.784 0 9.75 0h4.5C15.216 0 16 .784 16 1.75zm-6.5 0a.25.25 0 01.25-.25h4.5a.25.25 0 01.25.25V3h-5V1.75z" />
<path d="M4.997 6.178a.75.75 0 10-1.493.144L4.916 20.92a1.75 1.75 0 001.742 1.58h10.684a1.75 1.75 0 001.742-1.581l1.413-14.597a.75.75 0 00-1.494-.144l-1.412 14.596a.25.25 0 01-.249.226H6.658a.25.25 0 01-.249-.226L4.997 6.178z" />
<path d="M9.206 7.501a.75.75 0 01.793.705l.5 8.5A.75.75 0 119 16.794l-.5-8.5a.75.75 0 01.705-.793zm6.293.793A.75.75 0 1014 8.206l-.5 8.5a.75.75 0 001.498.088l.5-8.5z" />
</svg>
</ag-icon>
<ag-icon type="warning" size="18">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M6.736 4C4.657 4 2.5 5.88 2.5 8.514c0 3.107 2.324 5.96 4.861 8.12a29.66 29.66 0 004.566 3.175l.073.041.073-.04c.271-.153.661-.38 1.13-.674.94-.588 2.19-1.441 3.436-2.502 2.537-2.16 4.861-5.013 4.861-8.12C21.5 5.88 19.343 4 17.264 4c-2.106 0-3.801 1.389-4.553 3.643a.75.75 0 01-1.422 0C10.537 5.389 8.841 4 6.736 4zM12 20.703l.343.667a.75.75 0 01-.686 0l.343-.667zM1 8.513C1 5.053 3.829 2.5 6.736 2.5 9.03 2.5 10.881 3.726 12 5.605 13.12 3.726 14.97 2.5 17.264 2.5 20.17 2.5 23 5.052 23 8.514c0 3.818-2.801 7.06-5.389 9.262a31.146 31.146 0 01-5.233 3.576l-.025.013-.007.003-.002.001-.344-.666-.343.667-.003-.002-.007-.003-.025-.013A29.308 29.308 0 0110 20.408a31.147 31.147 0 01-3.611-2.632C3.8 15.573 1 12.332 1 8.514z" />
</svg>
</ag-icon>
<ag-icon type="error" size="18">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M6.736 4C4.657 4 2.5 5.88 2.5 8.514c0 3.107 2.324 5.96 4.861 8.12a29.66 29.66 0 004.566 3.175l.073.041.073-.04c.271-.153.661-.38 1.13-.674.94-.588 2.19-1.441 3.436-2.502 2.537-2.16 4.861-5.013 4.861-8.12C21.5 5.88 19.343 4 17.264 4c-2.106 0-3.801 1.389-4.553 3.643a.75.75 0 01-1.422 0C10.537 5.389 8.841 4 6.736 4zM12 20.703l.343.667a.75.75 0 01-.686 0l.343-.667zM1 8.513C1 5.053 3.829 2.5 6.736 2.5 9.03 2.5 10.881 3.726 12 5.605 13.12 3.726 14.97 2.5 17.264 2.5 20.17 2.5 23 5.052 23 8.514c0 3.818-2.801 7.06-5.389 9.262a31.146 31.146 0 01-5.233 3.576l-.025.013-.007.003-.002.001-.344-.666-.343.667-.003-.002-.007-.003-.025-.013A29.308 29.308 0 0110 20.408a31.147 31.147 0 01-3.611-2.632C3.8 15.573 1 12.332 1 8.514z" />
</svg>
</ag-icon>
</section>
<section class="mbe32">
<h4>More Sizes</h4>
<ag-icon size="32">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="36">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="40">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="48">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="56">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
<ag-icon size="64">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M11.03 2.59a1.5 1.5 0 011.94 0l7.5 6.363a1.5 1.5 0 01.53 1.144V19.5a1.5 1.5 0 01-1.5 1.5h-5.75a.75.75 0 01-.75-.75V14h-2v6.25a.75.75 0 01-.75.75H4.5A1.5 1.5 0 013 19.5v-9.403c0-.44.194-.859.53-1.144l7.5-6.363zM12 3.734l-7.5 6.363V19.5h5v-6.25a.75.75 0 01.75-.75h3.5a.75.75 0 01.75.75v6.25h5v-9.403L12 3.734z" />
</svg>
</ag-icon>
</section>
`,
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { FirewallRules } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { DataLakeAnalyticsAccountManagementClient } from "../dataLakeAnalyticsAccountManagementClient";
import {
FirewallRule,
FirewallRulesListByAccountNextOptionalParams,
FirewallRulesListByAccountOptionalParams,
FirewallRulesListByAccountResponse,
CreateOrUpdateFirewallRuleParameters,
FirewallRulesCreateOrUpdateOptionalParams,
FirewallRulesCreateOrUpdateResponse,
FirewallRulesGetOptionalParams,
FirewallRulesGetResponse,
FirewallRulesUpdateOptionalParams,
FirewallRulesUpdateResponse,
FirewallRulesDeleteOptionalParams,
FirewallRulesListByAccountNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing FirewallRules operations. */
export class FirewallRulesImpl implements FirewallRules {
private readonly client: DataLakeAnalyticsAccountManagementClient;
/**
* Initialize a new instance of the class FirewallRules class.
* @param client Reference to the service client
*/
constructor(client: DataLakeAnalyticsAccountManagementClient) {
this.client = client;
}
/**
* Lists the Data Lake Analytics firewall rules within the specified Data Lake Analytics account.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param options The options parameters.
*/
public listByAccount(
resourceGroupName: string,
accountName: string,
options?: FirewallRulesListByAccountOptionalParams
): PagedAsyncIterableIterator<FirewallRule> {
const iter = this.listByAccountPagingAll(
resourceGroupName,
accountName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByAccountPagingPage(
resourceGroupName,
accountName,
options
);
}
};
}
private async *listByAccountPagingPage(
resourceGroupName: string,
accountName: string,
options?: FirewallRulesListByAccountOptionalParams
): AsyncIterableIterator<FirewallRule[]> {
let result = await this._listByAccount(
resourceGroupName,
accountName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByAccountNext(
resourceGroupName,
accountName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByAccountPagingAll(
resourceGroupName: string,
accountName: string,
options?: FirewallRulesListByAccountOptionalParams
): AsyncIterableIterator<FirewallRule> {
for await (const page of this.listByAccountPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Lists the Data Lake Analytics firewall rules within the specified Data Lake Analytics account.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param options The options parameters.
*/
private _listByAccount(
resourceGroupName: string,
accountName: string,
options?: FirewallRulesListByAccountOptionalParams
): Promise<FirewallRulesListByAccountResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listByAccountOperationSpec
);
}
/**
* Creates or updates the specified firewall rule. During update, the firewall rule with the specified
* name will be replaced with this new firewall rule.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param firewallRuleName The name of the firewall rule to create or update.
* @param parameters Parameters supplied to create or update the firewall rule.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
accountName: string,
firewallRuleName: string,
parameters: CreateOrUpdateFirewallRuleParameters,
options?: FirewallRulesCreateOrUpdateOptionalParams
): Promise<FirewallRulesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, firewallRuleName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Gets the specified Data Lake Analytics firewall rule.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param firewallRuleName The name of the firewall rule to retrieve.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
firewallRuleName: string,
options?: FirewallRulesGetOptionalParams
): Promise<FirewallRulesGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, firewallRuleName, options },
getOperationSpec
);
}
/**
* Updates the specified firewall rule.
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param firewallRuleName The name of the firewall rule to update.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
accountName: string,
firewallRuleName: string,
options?: FirewallRulesUpdateOptionalParams
): Promise<FirewallRulesUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, firewallRuleName, options },
updateOperationSpec
);
}
/**
* Deletes the specified firewall rule from the specified Data Lake Analytics account
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param firewallRuleName The name of the firewall rule to delete.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
accountName: string,
firewallRuleName: string,
options?: FirewallRulesDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, firewallRuleName, options },
deleteOperationSpec
);
}
/**
* ListByAccountNext
* @param resourceGroupName The name of the Azure resource group.
* @param accountName The name of the Data Lake Analytics account.
* @param nextLink The nextLink from the previous successful call to the ListByAccount method.
* @param options The options parameters.
*/
private _listByAccountNext(
resourceGroupName: string,
accountName: string,
nextLink: string,
options?: FirewallRulesListByAccountNextOptionalParams
): Promise<FirewallRulesListByAccountNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, nextLink, options },
listByAccountNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByAccountOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FirewallRuleListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.FirewallRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters8,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.firewallRuleName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FirewallRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.firewallRuleName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.FirewallRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters9,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.firewallRuleName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.firewallRuleName
],
headerParameters: [Parameters.accept],
serializer
};
const listByAccountNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FirewallRuleListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as Immutable from "immutable";
import * as _ from "lodash";
import { Base } from "./base";
import { Event } from "./event";
import { GroupedCollection, GroupingFunction } from "./groupedcollection";
import { Index, index } from "./index";
import { Key } from "./key";
import { SortedCollection } from "./sortedcollection";
import { time } from "./time";
import util from "./util";
import {
AggregationSpec,
AggregationTuple,
KeyedCollection,
Trigger,
WindowingOptions
} from "./types";
import {
avg,
first,
InterpolationType,
last,
max,
median,
min,
percentile,
stdev,
sum
} from "./functions";
/**
* A map of `SortedCollection`s indexed by a string key representing a window.
*/
export class WindowedCollection<T extends Key> extends Base {
protected collections: Immutable.Map<string, SortedCollection<T>>;
protected options: WindowingOptions;
protected group: string | string[] | GroupingFunction<T>;
private triggerThreshold: Date;
/**
* Builds a new grouping that is based on a window period. This is combined
* with any groupBy to divide the events among multiple `SortedCollection`s, one
* for each group and window combination.
*
* The main way to construct a `WindowedCollection` is to pass in a "window"
* defined as a `Period` and a "group", which can be a field to group by, or
* a function that can be called to do the grouping. Optionally, you may pass
* in a `SortedCollection` of initial `Event`s to group, as is the case when this is
* used in a batch context.
*
* As an `Event` is added via `addEvent()`, the windowing and grouping will be
* applied to it and it will be appended to the appropiate `SortedCollection`,
* or a new `SortedCollection` will be created.
*
* The other way to construct a `WindowedCollection` is by passing in a map
* of group name to `SortedCollection`. This is generally used if there are are
* events already grouped and you want to apply a window group on top of that.
* This is the case when calling `GroupedCollection.window()`.
*/
constructor(collectionMap: Immutable.Map<string, SortedCollection<T>>);
constructor(
windowing: WindowingOptions,
collectionMap: Immutable.Map<string, SortedCollection<T>>
);
constructor(windowing: WindowingOptions, collection?: SortedCollection<T>);
constructor(
windowing: WindowingOptions,
group: string | string[],
collection?: SortedCollection<T>
);
constructor(arg1: any, arg2?: any, arg3?: any) {
super();
if (Immutable.Map.isMap(arg1)) {
this.collections = arg1;
} else {
this.options = arg1 as WindowingOptions;
if (Immutable.Map.isMap(arg2)) {
const collections = arg2 as Immutable.Map<string, SortedCollection<T>>;
// Rekey all the events in the collections with a new key that
// combines their existing group with the windows they fall in.
// An event could fall into 0, 1 or many windows, depending on the
// window's period and duration, as supplied in the `WindowOptions`.
let remapped = Immutable.List();
collections.forEach((c, k) => {
c.forEach(e => {
const groups = this.options.window
.getIndexSet(time(e.timestamp()))
.toList();
groups.forEach(g => {
remapped = remapped.push([`${k}::${g.asString()}`, e]);
});
});
});
this.collections = remapped
.groupBy(e => e[0])
.map(eventList => eventList.map(kv => kv[1]))
.map(eventList => new SortedCollection<T>(eventList.toList()))
.toMap();
} else {
let collection;
if (_.isString(arg2) || _.isArray(arg2)) {
this.group = util.fieldAsArray(arg2 as string | string[]);
collection = arg3 as SortedCollection<T>;
} else {
collection = arg2 as SortedCollection<T>;
}
if (collection) {
throw new Error("Unimplemented");
} else {
this.collections = Immutable.Map<string, SortedCollection<T>>();
}
}
}
}
/**
* Fetch the `SortedCollection` of `Event`s contained in the windowed grouping
*/
get(key: string): SortedCollection<T> {
return this.collections.get(key);
}
/**
* Example:
* ```
* const rolledUp = collection
* .groupBy("team")
* .window(period("30m"))
* .aggregate({
* team: ["team", keep()],
* total: [ "score", sum() ],
* });
* ```
*/
aggregate(aggregationSpec: AggregationSpec<T>): GroupedCollection<Index> {
let eventMap = Immutable.Map<string, Immutable.List<Event<Index>>>();
this.collections.forEach((collection, group) => {
const d = {};
const [groupKey, windowKey] = group.split("::");
_.forEach(aggregationSpec, (src: AggregationTuple, dest: string) => {
const [srcField, reducer] = src;
d[dest] = collection.aggregate(reducer, srcField);
});
const eventKey = index(windowKey);
const indexedEvent = new Event<Index>(eventKey, Immutable.fromJS(d));
if (!eventMap.has(groupKey)) {
eventMap = eventMap.set(groupKey, Immutable.List());
}
eventMap = eventMap.set(groupKey, eventMap.get(groupKey).push(indexedEvent));
});
const mapping = eventMap.map(eventList => new SortedCollection<Index>(eventList));
return new GroupedCollection<Index>(mapping);
}
/**
* Collects all `Event`s from the groupings and returns them placed
* into a single `SortedCollection`.
*/
public flatten(): SortedCollection<T> {
let events = Immutable.List<Event<T>>();
this.collections.flatten().forEach(collection => {
events = events.concat(collection.eventList());
});
return new SortedCollection<T>(events);
}
/**
* Removes any grouping present, returning an Immutable.Map
* mapping just the window to the `SortedCollection`.
*/
public ungroup(): Immutable.Map<string, SortedCollection<T>> {
const result = Immutable.Map<string, SortedCollection<T>>();
this.collections.forEach((collection, key) => {
const newKey = key.split("::")[1];
result[newKey] = collection;
});
return result;
}
addEvent(event: Event<T>): Immutable.List<KeyedCollection<T>> {
let toBeEmitted = Immutable.List<KeyedCollection<T>>();
const discardWindows = true;
const emitOnDiscard = this.options.trigger === Trigger.onDiscardedWindow;
const emitEveryEvent = this.options.trigger === Trigger.perEvent;
const keys: Immutable.List<string> = this.getEventGroups(event);
// Add event to an existing collection(s) or a new collection(s)
keys.forEach(key => {
// Add event to collection referenced by this key
let targetCollection: SortedCollection<T>;
let createdCollection = false;
if (this.collections.has(key)) {
targetCollection = this.collections.get(key);
} else {
targetCollection = new SortedCollection<T>(Immutable.List());
createdCollection = true;
}
this.collections = this.collections.set(key, targetCollection.addEvent(event));
// Push onto the emit list
if (emitEveryEvent) {
toBeEmitted = toBeEmitted.push([key, this.collections.get(key)]);
}
});
// Discard past collections
let keep = Immutable.Map<string, SortedCollection<T>>();
let discard = Immutable.Map<string, SortedCollection<T>>();
this.collections.forEach((collection, collectionKey) => {
const [__, windowKey] =
collectionKey.split("::").length > 1
? collectionKey.split("::")
: [null, collectionKey];
if (+event.timestamp() < +util.timeRangeFromIndexString(windowKey).end()) {
keep = keep.set(collectionKey, collection);
} else {
discard = discard.set(collectionKey, collection);
}
});
if (emitOnDiscard) {
discard.forEach((collection, collectionKey) => {
toBeEmitted = toBeEmitted.push([collectionKey, collection]);
});
}
this.collections = keep;
return toBeEmitted;
}
private getEventGroups(event: Event<T>): Immutable.List<string> {
// Window the data
const windowKeyList = this.options.window.getIndexSet(time(event.timestamp())).toList();
let fn;
// Group the data
if (this.group) {
if (_.isFunction(this.group)) {
fn = this.group;
} else {
const fieldSpec = this.group as string | string[];
const fs = util.fieldAsArray(fieldSpec);
fn = e => e.get(fs);
}
}
const groupKey = fn ? fn(event) : null;
return windowKeyList.map(
windowKey => (groupKey ? `${groupKey}::${windowKey}` : `${windowKey}`)
);
}
}
function windowFactory<T extends Key>(collectionMap: Immutable.Map<string, SortedCollection<T>>);
function windowFactory<T extends Key>(
windowOptions: WindowingOptions,
collectionMap?: Immutable.Map<string, SortedCollection<T>>
);
function windowFactory<T extends Key>(
windowOptions: WindowingOptions,
initialCollection?: SortedCollection<T> // tslint:disable-line:unified-signatures
);
function windowFactory<T extends Key>(
windowOptions: WindowingOptions,
group: string | string[],
initialCollection?: SortedCollection<T>
);
function windowFactory<T extends Key>(arg1: any, arg2?: any) {
return new WindowedCollection<T>(arg1, arg2);
}
export { windowFactory as windowed }; | the_stack |
import {h, Component} from 'preact'
import {css} from 'aphrodite'
import {Flamechart} from '../lib/flamechart'
import {Rect, Vec2, AffineTransform, clamp} from '../lib/math'
import {FlamechartRenderer} from '../gl/flamechart-renderer'
import {getFlamechartStyle} from './flamechart-style'
import {FontFamily, FontSize, Sizes, commonStyle} from './style'
import {CanvasContext} from '../gl/canvas-context'
import {cachedMeasureTextWidth} from '../lib/text-utils'
import {Color} from '../lib/color'
import {Theme} from './themes/theme'
interface FlamechartMinimapViewProps {
theme: Theme
flamechart: Flamechart
configSpaceViewportRect: Rect
canvasContext: CanvasContext
flamechartRenderer: FlamechartRenderer
transformViewport: (transform: AffineTransform) => void
setConfigSpaceViewportRect: (rect: Rect) => void
}
enum DraggingMode {
DRAW_NEW_VIEWPORT,
TRANSLATE_VIEWPORT,
}
export class FlamechartMinimapView extends Component<FlamechartMinimapViewProps, {}> {
container: Element | null = null
containerRef = (element: Element | null) => {
this.container = element || null
}
overlayCanvas: HTMLCanvasElement | null = null
overlayCtx: CanvasRenderingContext2D | null = null
private physicalViewSize() {
return new Vec2(
this.overlayCanvas ? this.overlayCanvas.width : 0,
this.overlayCanvas ? this.overlayCanvas.height : 0,
)
}
private getStyle() {
return getFlamechartStyle(this.props.theme)
}
private minimapOrigin() {
return new Vec2(0, Sizes.FRAME_HEIGHT * window.devicePixelRatio)
}
private configSpaceSize() {
return new Vec2(
this.props.flamechart.getTotalWeight(),
this.props.flamechart.getLayers().length,
)
}
private configSpaceToPhysicalViewSpace() {
const minimapOrigin = this.minimapOrigin()
return AffineTransform.betweenRects(
new Rect(new Vec2(0, 0), this.configSpaceSize()),
new Rect(minimapOrigin, this.physicalViewSize().minus(minimapOrigin)),
)
}
private logicalToPhysicalViewSpace() {
return AffineTransform.withScale(new Vec2(window.devicePixelRatio, window.devicePixelRatio))
}
private windowToLogicalViewSpace() {
if (!this.container) return new AffineTransform()
const bounds = this.container.getBoundingClientRect()
return AffineTransform.withTranslation(new Vec2(-bounds.left, -bounds.top))
}
private renderRects() {
if (!this.container) return
// Hasn't resized yet -- no point in rendering yet
if (this.physicalViewSize().x < 2) return
this.props.canvasContext.renderBehind(this.container, () => {
this.props.flamechartRenderer.render({
configSpaceSrcRect: new Rect(new Vec2(0, 0), this.configSpaceSize()),
physicalSpaceDstRect: new Rect(
this.minimapOrigin(),
this.physicalViewSize().minus(this.minimapOrigin()),
),
renderOutlines: false,
})
this.props.canvasContext.viewportRectangleRenderer.render({
configSpaceViewportRect: this.props.configSpaceViewportRect,
configSpaceToPhysicalViewSpace: this.configSpaceToPhysicalViewSpace(),
})
})
}
private renderOverlays() {
const ctx = this.overlayCtx
if (!ctx) return
const physicalViewSize = this.physicalViewSize()
ctx.clearRect(0, 0, physicalViewSize.x, physicalViewSize.y)
const configToPhysical = this.configSpaceToPhysicalViewSpace()
const left = 0
const right = this.configSpaceSize().x
// TODO(jlfwong): There's a huge amount of code duplication here between
// this and the FlamechartView.renderOverlays(). Consolidate.
// We want about 10 gridlines to be visible, and want the unit to be
// 1eN, 2eN, or 5eN for some N
// Ideally, we want an interval every 100 logical screen pixels
const logicalToConfig = (
this.configSpaceToPhysicalViewSpace().inverted() || new AffineTransform()
).times(this.logicalToPhysicalViewSpace())
const targetInterval = logicalToConfig.transformVector(new Vec2(200, 1)).x
const physicalViewSpaceFrameHeight = Sizes.FRAME_HEIGHT * window.devicePixelRatio
const physicalViewSpaceFontSize = FontSize.LABEL * window.devicePixelRatio
const labelPaddingPx = (physicalViewSpaceFrameHeight - physicalViewSpaceFontSize) / 2
ctx.font = `${physicalViewSpaceFontSize}px/${physicalViewSpaceFrameHeight}px ${FontFamily.MONOSPACE}`
ctx.textBaseline = 'top'
const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)))
let interval = minInterval
if (targetInterval / interval > 5) {
interval *= 5
} else if (targetInterval / interval > 2) {
interval *= 2
}
const theme = this.props.theme
{
ctx.fillStyle = Color.fromCSSHex(theme.bgPrimaryColor).withAlpha(0.8).toCSS()
ctx.fillRect(0, 0, physicalViewSize.x, physicalViewSpaceFrameHeight)
ctx.textBaseline = 'top'
for (let x = Math.ceil(left / interval) * interval; x < right; x += interval) {
// TODO(jlfwong): Ensure that labels do not overlap
const pos = Math.round(configToPhysical.transformPosition(new Vec2(x, 0)).x)
const labelText = this.props.flamechart.formatValue(x)
const textWidth = Math.ceil(cachedMeasureTextWidth(ctx, labelText))
ctx.fillStyle = theme.fgPrimaryColor
ctx.fillText(labelText, pos - textWidth - labelPaddingPx, labelPaddingPx)
ctx.fillStyle = theme.fgSecondaryColor
ctx.fillRect(pos, 0, 1, physicalViewSize.y)
}
}
}
onWindowResize = () => {
this.onBeforeFrame()
}
componentWillReceiveProps(nextProps: FlamechartMinimapViewProps) {
if (this.props.flamechart !== nextProps.flamechart) {
this.renderCanvas()
} else if (this.props.configSpaceViewportRect != nextProps.configSpaceViewportRect) {
this.renderCanvas()
} else if (this.props.canvasContext !== nextProps.canvasContext) {
if (this.props.canvasContext) {
this.props.canvasContext.removeBeforeFrameHandler(this.onBeforeFrame)
}
if (nextProps.canvasContext) {
nextProps.canvasContext.addBeforeFrameHandler(this.onBeforeFrame)
nextProps.canvasContext.requestFrame()
}
}
}
componentDidMount() {
window.addEventListener('resize', this.onWindowResize)
this.props.canvasContext.addBeforeFrameHandler(this.onBeforeFrame)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onWindowResize)
this.props.canvasContext.removeBeforeFrameHandler(this.onBeforeFrame)
}
private resizeOverlayCanvasIfNeeded() {
if (!this.overlayCanvas) return
let {width, height} = this.overlayCanvas.getBoundingClientRect()
{
/*
We render text at a higher resolution then scale down to
ensure we're rendering at 1:1 device pixel ratio.
This ensures our text is rendered crisply.
*/
}
width = Math.floor(width)
height = Math.floor(height)
// Still initializing: don't resize yet
if (width === 0 || height === 0) return
const scaledWidth = width * window.devicePixelRatio
const scaledHeight = height * window.devicePixelRatio
if (scaledWidth === this.overlayCanvas.width && scaledHeight === this.overlayCanvas.height)
return
this.overlayCanvas.width = scaledWidth
this.overlayCanvas.height = scaledHeight
}
private onBeforeFrame = () => {
this.maybeClearInteractionLock()
this.resizeOverlayCanvasIfNeeded()
this.renderRects()
this.renderOverlays()
}
private renderCanvas = () => {
this.props.canvasContext.requestFrame()
}
// Inertial scrolling introduces tricky interaction problems.
// Namely, if you start panning, and hit the edge of the scrollable
// area, the browser continues to receive WheelEvents from inertial
// scrolling. If we start zooming by holding Cmd + scrolling, then
// release the Cmd key, this can cause us to interpret the incoming
// inertial scrolling events as panning. To prevent this, we introduce
// a concept of an "Interaction Lock". Once a certain interaction has
// begun, we don't allow the other type of interaction to begin until
// we've received two frames with no inertial wheel events. This
// prevents us from accidentally switching between panning & zooming.
private frameHadWheelEvent = false
private framesWithoutWheelEvents = 0
private interactionLock: 'pan' | 'zoom' | null = null
private maybeClearInteractionLock = () => {
if (this.interactionLock) {
if (!this.frameHadWheelEvent) {
this.framesWithoutWheelEvents++
if (this.framesWithoutWheelEvents >= 2) {
this.interactionLock = null
this.framesWithoutWheelEvents = 0
}
}
this.props.canvasContext.requestFrame()
}
this.frameHadWheelEvent = false
}
private pan(logicalViewSpaceDelta: Vec2) {
this.interactionLock = 'pan'
const physicalDelta = this.logicalToPhysicalViewSpace().transformVector(logicalViewSpaceDelta)
const configDelta = this.configSpaceToPhysicalViewSpace().inverseTransformVector(physicalDelta)
if (!configDelta) return
this.props.transformViewport(AffineTransform.withTranslation(configDelta))
}
private zoom(multiplier: number) {
this.interactionLock = 'zoom'
const configSpaceViewport = this.props.configSpaceViewportRect
const configSpaceCenter = configSpaceViewport.origin.plus(configSpaceViewport.size.times(1 / 2))
if (!configSpaceCenter) return
const zoomTransform = AffineTransform.withTranslation(configSpaceCenter.times(-1))
.scaledBy(new Vec2(multiplier, 1))
.translatedBy(configSpaceCenter)
this.props.transformViewport(zoomTransform)
}
private onWheel = (ev: WheelEvent) => {
ev.preventDefault()
this.frameHadWheelEvent = true
const isZoom = ev.metaKey || ev.ctrlKey
if (isZoom && this.interactionLock !== 'pan') {
let multiplier = 1 + ev.deltaY / 100
// On Chrome & Firefox, pinch-to-zoom maps to
// WheelEvent + Ctrl Key. We'll accelerate it in
// this case, since it feels a bit sluggish otherwise.
if (ev.ctrlKey) {
multiplier = 1 + ev.deltaY / 40
}
multiplier = clamp(multiplier, 0.1, 10.0)
this.zoom(multiplier)
} else if (this.interactionLock !== 'zoom') {
this.pan(new Vec2(ev.deltaX, ev.deltaY))
}
this.renderCanvas()
}
private configSpaceMouse(ev: MouseEvent): Vec2 | null {
const logicalSpaceMouse = this.windowToLogicalViewSpace().transformPosition(
new Vec2(ev.clientX, ev.clientY),
)
const physicalSpaceMouse = this.logicalToPhysicalViewSpace().transformPosition(
logicalSpaceMouse,
)
return this.configSpaceToPhysicalViewSpace().inverseTransformPosition(physicalSpaceMouse)
}
private dragStartConfigSpaceMouse: Vec2 | null = null
private dragConfigSpaceViewportOffset: Vec2 | null = null
private draggingMode: DraggingMode | null = null
private onMouseDown = (ev: MouseEvent) => {
const configSpaceMouse = this.configSpaceMouse(ev)
if (configSpaceMouse) {
if (this.props.configSpaceViewportRect.contains(configSpaceMouse)) {
// If dragging starting inside the viewport rectangle,
// we'll move the existing viewport
this.draggingMode = DraggingMode.TRANSLATE_VIEWPORT
this.dragConfigSpaceViewportOffset = configSpaceMouse.minus(
this.props.configSpaceViewportRect.origin,
)
} else {
// If dragging starts outside the the viewport rectangle,
// we'll start drawing a new viewport
this.draggingMode = DraggingMode.DRAW_NEW_VIEWPORT
}
this.dragStartConfigSpaceMouse = configSpaceMouse
window.addEventListener('mousemove', this.onWindowMouseMove)
window.addEventListener('mouseup', this.onWindowMouseUp)
this.updateCursor(configSpaceMouse)
}
}
private onWindowMouseMove = (ev: MouseEvent) => {
if (!this.dragStartConfigSpaceMouse) return
let configSpaceMouse = this.configSpaceMouse(ev)
if (!configSpaceMouse) return
this.updateCursor(configSpaceMouse)
// Clamp the mouse position to avoid weird behavior when outside the canvas bounds
configSpaceMouse = new Rect(new Vec2(0, 0), this.configSpaceSize()).closestPointTo(
configSpaceMouse,
)
if (this.draggingMode === DraggingMode.DRAW_NEW_VIEWPORT) {
const configStart = this.dragStartConfigSpaceMouse
let configEnd = configSpaceMouse
if (!configStart || !configEnd) return
const left = Math.min(configStart.x, configEnd.x)
const right = Math.max(configStart.x, configEnd.x)
const width = right - left
const height = this.props.configSpaceViewportRect.height()
this.props.setConfigSpaceViewportRect(
new Rect(new Vec2(left, configEnd.y - height / 2), new Vec2(width, height)),
)
} else if (this.draggingMode === DraggingMode.TRANSLATE_VIEWPORT) {
if (!this.dragConfigSpaceViewportOffset) return
const newOrigin = configSpaceMouse.minus(this.dragConfigSpaceViewportOffset)
this.props.setConfigSpaceViewportRect(
this.props.configSpaceViewportRect.withOrigin(newOrigin),
)
}
}
private updateCursor = (configSpaceMouse: Vec2) => {
if (this.draggingMode === DraggingMode.TRANSLATE_VIEWPORT) {
document.body.style.cursor = 'grabbing'
document.body.style.cursor = '-webkit-grabbing'
} else if (this.draggingMode === DraggingMode.DRAW_NEW_VIEWPORT) {
document.body.style.cursor = 'col-resize'
} else if (this.props.configSpaceViewportRect.contains(configSpaceMouse)) {
document.body.style.cursor = 'grab'
document.body.style.cursor = '-webkit-grab'
} else {
document.body.style.cursor = 'col-resize'
}
}
private onMouseLeave = () => {
if (this.draggingMode == null) {
document.body.style.cursor = 'default'
}
}
private onMouseMove = (ev: MouseEvent) => {
const configSpaceMouse = this.configSpaceMouse(ev)
if (!configSpaceMouse) return
this.updateCursor(configSpaceMouse)
}
private onWindowMouseUp = (ev: MouseEvent) => {
this.draggingMode = null
window.removeEventListener('mousemove', this.onWindowMouseMove)
window.removeEventListener('mouseup', this.onWindowMouseUp)
const configSpaceMouse = this.configSpaceMouse(ev)
if (!configSpaceMouse) return
this.updateCursor(configSpaceMouse)
}
private overlayCanvasRef = (element: Element | null) => {
if (element) {
this.overlayCanvas = element as HTMLCanvasElement
this.overlayCtx = this.overlayCanvas.getContext('2d')
this.renderCanvas()
} else {
this.overlayCanvas = null
this.overlayCtx = null
}
}
render() {
const style = this.getStyle()
return (
<div
ref={this.containerRef}
onWheel={this.onWheel}
onMouseDown={this.onMouseDown}
onMouseMove={this.onMouseMove}
onMouseLeave={this.onMouseLeave}
className={css(style.minimap, commonStyle.vbox)}
>
<canvas width={1} height={1} ref={this.overlayCanvasRef} className={css(style.fill)} />
</div>
)
}
} | the_stack |
import * as path from 'path';
import * as fs from 'fs';
import { KVStore } from '../src/kv_store';
import { NotFoundError } from '../src/errors';
interface KeyValuePair {
key: string;
value: Buffer;
}
describe('KVStore', () => {
let db: KVStore;
beforeAll(async () => {
const parentPath = path.join(__dirname, '../tmp');
if (!fs.existsSync(parentPath)) {
await fs.promises.mkdir(parentPath);
}
db = new KVStore(path.join(parentPath, '/test.db'));
});
afterEach(async () => {
await db.clear();
});
describe('constructor', () => {
it('should throw error if the parent folder does not exist', () => {
expect(() => new KVStore('./random-folder/sample.db')).toThrow(
'random-folder does not exist',
);
});
});
describe('get', () => {
it('should reject with NotFoundError if the key does not exist', async () => {
await expect(db.get('Random value')).rejects.toThrow(NotFoundError);
});
it('should return JSON object if exists', async () => {
const defaultKey = 'random';
const defaultValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(defaultKey, defaultValue);
const value = await db.get(defaultKey);
expect(value).toEqual(defaultValue);
});
});
describe('exists', () => {
it('should return false if key does not exist', async () => {
await expect(db.exists('Random value')).resolves.toBeFalse();
});
it('should return true if key exists', async () => {
const defaultKey = 'random';
const defaultValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(defaultKey, defaultValue);
await expect(db.exists(defaultKey)).resolves.toBeTrue();
});
});
describe('put', () => {
it('should put the JSON object to the database', async () => {
const defaultKey = 'random';
const defaultValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db.put(defaultKey, defaultValue);
const value = await db['_db'].get(defaultKey);
expect(value).toEqual(defaultValue);
});
});
describe('del', () => {
it('should delete the key if exists', async () => {
const defaultKey = 'random';
const defaultValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(defaultKey, defaultValue);
await db.del(defaultKey);
await expect(db.get(defaultKey)).rejects.toThrow(NotFoundError);
});
it('should not throw error if key does not exist', async () => {
const defaultKey = 'random';
await expect(db.del(defaultKey)).not.toReject();
});
});
describe('createReadStream', () => {
let expectedValues: KeyValuePair[];
beforeEach(async () => {
expectedValues = [
{
key: '001',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '103',
value: Buffer.from(JSON.stringify(3), 'binary'),
},
{
key: '010',
value: Buffer.from(JSON.stringify([19, 5, 6]), 'binary'),
},
{
key: '321',
value: Buffer.from(JSON.stringify('string'), 'binary'),
},
];
const batch = db.batch();
for (const expected of expectedValues) {
batch.put(expected.key, expected.value);
}
await batch.write();
});
it('should return all the entries in lexicographical order', async () => {
const stream = db.createReadStream();
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(expectedValues.length);
expect(result[0].key).toEqual(expectedValues[0].key);
expect(result[1].key).toEqual(expectedValues[2].key);
expect(result[2].key).toEqual(expectedValues[1].key);
});
it('should return all the entries in reverse lexicographical order when reverse is specified', async () => {
const stream = db.createReadStream({ reverse: true });
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(expectedValues.length);
expect(result[0].key).toEqual(expectedValues[3].key);
expect(result[1].key).toEqual(expectedValues[1].key);
expect(result[2].key).toEqual(expectedValues[2].key);
});
it('should return limited number of entries when limit is specified', async () => {
const stream = db.createReadStream({ limit: 2 });
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(2);
expect(result[0].key).toEqual(expectedValues[0].key);
expect(result[1].key).toEqual(expectedValues[2].key);
});
it('should return limited number of entries in reverse order when limit and reverse are specified', async () => {
const stream = db.createReadStream({ limit: 2, reverse: true });
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(2);
expect(result[0].key).toEqual(expectedValues[3].key);
expect(result[1].key).toEqual(expectedValues[1].key);
});
it('should return ranged value if gte and lte is specified', async () => {
const stream = db.createReadStream({ gte: '001', lte: '010' });
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(2);
expect(result[0].key).toEqual(expectedValues[0].key);
expect(result[1].key).toEqual(expectedValues[2].key);
});
it('should return ranged value if gte and lte is specified in reverse order', async () => {
const stream = db.createReadStream({
gte: '001',
lte: '010',
reverse: true,
});
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(2);
expect(result[0].key).toEqual(expectedValues[2].key);
expect(result[1].key).toEqual(expectedValues[0].key);
});
it('should return ranged value if gt and lt is specified', async () => {
const stream = db.createReadStream({ gte: '000', lt: '010' });
const result = await new Promise<KeyValuePair[]>((resolve, reject) => {
const data: KeyValuePair[] = [];
stream
.on('data', ({ key, value }) => {
data.push({ key, value });
})
.on('error', error => {
reject(error);
})
.on('end', () => {
resolve(data);
});
});
expect(result).toHaveLength(1);
expect(result[0].key).toEqual(expectedValues[0].key);
});
});
describe('batch', () => {
it('should put the batched operation', async () => {
const expectedValues = [
{
key: '1',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '3',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '2',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
];
const batch = db.batch();
for (const expected of expectedValues) {
batch.put(expected.key, expected.value);
}
await batch.write();
expect.assertions(expectedValues.length);
for (const expected of expectedValues) {
const result = await db['_db'].get(expected.key);
expect(result).toEqual(expected.value);
}
});
it('should update and delete in the same batch', async () => {
const deletingKey = 'random';
const deletingValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(deletingKey, deletingValue);
const updatingKey = '1';
const updatingValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(updatingKey, updatingValue);
const expectedValues = [
{
key: '1',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '3',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '2',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
];
const batch = db.batch();
for (const expected of expectedValues) {
batch.put(expected.key, expected.value);
}
batch.del(deletingKey);
await batch.write();
expect.assertions(expectedValues.length + 1);
for (const expected of expectedValues) {
const result = await db['_db'].get(expected.key);
expect(result).toEqual(expected.value);
}
await expect(db.get(deletingKey)).rejects.toThrow(NotFoundError);
});
});
describe('clear', () => {
it('should remove all data existed', async () => {
const defaultKey = 'random';
const defaultValue = Buffer.from(
JSON.stringify({
key: 'something',
balance: 1000000,
}),
'binary',
);
await db['_db'].put(defaultKey, defaultValue);
await db.clear();
await expect(db.get(defaultKey)).rejects.toThrow(NotFoundError);
});
it('should only remove specified data', async () => {
const expectedValues = [
{
key: '001',
value: Buffer.from(JSON.stringify([4, 5, 6]), 'binary'),
},
{
key: '103',
value: Buffer.from(JSON.stringify(3), 'binary'),
},
{
key: '010',
value: Buffer.from(JSON.stringify([19, 5, 6]), 'binary'),
},
];
const batch = db.batch();
for (const expected of expectedValues) {
batch.put(expected.key, expected.value);
}
await batch.write();
await db.clear({ gt: '001', lt: '103', limit: 2 });
await expect(db.get(expectedValues[0].key)).toResolve();
await expect(db.get(expectedValues[1].key)).toResolve();
await expect(db.get(expectedValues[2].key)).rejects.toThrow(NotFoundError);
});
});
}); | the_stack |
import { HTTPCodes, HTTPMethod, HTTPRequestContext } from '../WebDAVRequest'
import { XML, XMLElementBuilder, XMLElement } from 'xml-js-builder'
import { ResourceType } from '../../../manager/v2/fileSystem/CommonTypes'
import { STATUS_CODES } from 'http'
import { startsWith } from '../../../helper/JSCompatibility'
import { Workflow } from '../../../helper/Workflow'
import { Errors } from '../../../Errors'
export default class implements HTTPMethod
{
unchunked(ctx : HTTPRequestContext, data : Buffer, callback : () => void) : void
{
ctx.getResource((e, r) => {
ctx.checkIfHeader(r, () => {
//ctx.requirePrivilege([ 'canSetProperty', 'canRemoveProperty' ], r, () => {
const multistatus = new XMLElementBuilder('D:multistatus', {
'xmlns:D': 'DAV:'
});
const response = multistatus.ele('D:response');
response.ele('D:href', undefined, true).add(HTTPRequestContext.encodeURL(ctx.fullUri()));
try
{
const xml = XML.parse(data as any);
const root = xml.find('DAV:propertyupdate');
const notifications : any = { }
const reverse = [];
let finalize = function()
{
finalize = function()
{
const next = () => {
const codes = Object.keys(notifications);
codes.forEach((code) => {
const propstat = response.ele('D:propstat');
const prop = propstat.ele('D:prop');
notifications[code].forEach((name) => prop.add(new XMLElementBuilder(name)));
propstat.ele('D:status').add('HTTP/1.1 ' + code + ' ' + STATUS_CODES[code]);
})
ctx.setCode(HTTPCodes.MultiStatus);
ctx.writeBody(multistatus);
callback();
}
if(Object.keys(notifications).length > 1)
{
new Workflow()
.each(reverse, (action, cb) => action(cb))
.error((e) => {
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
callback();
})
.done(() => {
if(notifications[HTTPCodes.OK])
{
notifications[HTTPCodes.FailedDependency] = notifications[HTTPCodes.OK];
delete notifications[HTTPCodes.OK];
}
next();
})
}
else
next();
}
}
const notify = function(el : any, error : any)
{
const code = error ? HTTPCodes.Forbidden : HTTPCodes.OK;
if(!notifications[code])
notifications[code] = [];
notifications[code].push(el.name);
}
const execute = function(name : string, eventName : /*EventsName*/string, fnProp)
{
const list = root.findMany(name);
if(list.length === 0)
{
finalize();
return;
}
list.forEach(function(el) {
const els = el.find('DAV:prop').elements;
new Workflow(false)
.each(els, (x, cb) => {
if(x.type !== 'element')
return cb();
fnProp(x, cb);
})
.intermediate((el, e) => {
/*if(!e)
ctx.invokeEvent(eventName, r, el)*/
if(el.type === 'element')
notify(el, e)
})
.done((_) => finalize())
})
}
r.fs.checkPrivilege(ctx, r.path, 'canWriteProperties', (e, can) => {
if(e || !can)
{
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
}
else if(!can)
ctx.setCodeFromError(Errors.NotEnoughPrivilege);
return callback();
}
r.fs.isLocked(ctx, r.path, (e, locked) => {
if(e || locked)
{
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
}
else if(locked)
ctx.setCode(HTTPCodes.Locked);
return callback();
}
r.propertyManager((e, pm) => {
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
return callback();
}
pm.getProperties((e, props) => {
if(e)
{
if(!ctx.setCodeFromError(e))
ctx.setCode(HTTPCodes.InternalServerError)
return callback();
}
const properties = JSON.parse(JSON.stringify(props));
const pushSetReverseAction = (el : XMLElement) => {
const prop = properties[el.name];
if(prop)
reverse.push((cb) => pm.setProperty(el.name, prop.value, prop.attributes, cb));
else
reverse.push((cb) => pm.removeProperty(el.name, cb));
}
const pushRemoveReverseAction = (el : XMLElement) => {
const prop = properties[el.name];
reverse.push((cb) => pm.setProperty(el.name, prop.value, prop.attributes, cb));
}
execute('DAV:set', 'setProperty', (el : XMLElement, callback) => {
if(startsWith(el.name, 'DAV:'))
{
pushSetReverseAction(el);
return callback(Errors.Forbidden);
}
pm.setProperty(el.name, el.elements, el.attributes, (e) => {
if(!e)
pushSetReverseAction(el);
callback(e);
})
})
execute('DAV:remove', 'removeProperty', (el : XMLElement, callback) => {
if(startsWith(el.name, 'DAV:'))
{
pushRemoveReverseAction(el);
return callback(Errors.Forbidden);
}
pm.removeProperty(el.name, (e) => {
if(!e)
pushRemoveReverseAction(el);
callback(e);
})
})
}, false)
})
})
})
}
catch(ex)
{
ctx.setCode(HTTPCodes.BadRequest);
callback();
}
//})
})
})
}
isValidFor(ctx : HTTPRequestContext, type : ResourceType)
{
return !!type;
}
} | the_stack |
import { Component, Complex, NotifyPropertyChanges, INotifyPropertyChanged, Property } from '@syncfusion/ej2-base';
import { isNullOrUndefined, Browser, ModuleDeclaration } from '@syncfusion/ej2-base';
import { createElement, remove, Event, EmitType, EventHandler } from '@syncfusion/ej2-base';
import { createSvg, RectOption, measureText, TextOption, renderTextElement } from '../smithchart/utils/helper';
import { removeElement, textTrim } from '../smithchart/utils/helper';
import { SmithchartRect, SmithchartSize } from '../smithchart/utils/utils';
import { SmithchartMarginModel, SmithchartBorderModel, SmithchartFontModel } from '../smithchart/utils/utils-model';
import { SmithchartMargin, SmithchartBorder, SmithchartFont } from '../smithchart/utils/utils';
import { TitleModel, SubtitleModel } from '../smithchart/title/title-model';
import { SmithchartLegendSettingsModel } from '../smithchart/legend/legend-model';
import { SmithchartAxisModel } from '../smithchart/axis/axis-model';
import { TooltipRender } from '../smithchart/series/tooltip';
import { ISmithchartLoadedEventArgs, ISmithchartLoadEventArgs, ISmithchartThemeStyle } from '../smithchart/model/interface';
import { ISmithchartLegendRenderEventArgs, ITitleRenderEventArgs, ISubTitleRenderEventArgs } from '../smithchart/model/interface';
import { ISmithchartAxisLabelRenderEventArgs, ISmithchartPrintEventArgs, ISmithChartTooltipEventArgs } from '../smithchart/model/interface';
import { ISmithchartSeriesRenderEventArgs, ISmithchartAnimationCompleteEventArgs } from '../smithchart/model/interface';
import { ISmithchartTextRenderEventArgs } from '../smithchart/model/interface';
import { getThemeColor } from '../smithchart/model/theme';
import { SmithchartLegendSettings } from '../smithchart/legend/legend';
import { SmithchartAxis } from '../smithchart/axis/axis';
import { Title } from '../smithchart/title/title';
import { SmithchartSeriesModel } from '../smithchart/series/series-model';
import { SmithchartSeries } from '../smithchart/series/series';
import { AreaBounds } from '../smithchart/utils/area';
import { AxisRender } from '../smithchart/axis/axisrender';
import { SmithchartLegend } from '../smithchart/legend/legendrender';
import { SeriesRender } from '../smithchart/series/seriesrender';
import { Collection } from '@syncfusion/ej2-base';
import { getSeriesColor } from '../smithchart/model/theme';
import { SmithchartTheme, RenderType } from '../smithchart/utils/enum';
import { Tooltip, SvgRenderer } from '@syncfusion/ej2-svg-base';
import { ExportUtils } from '../smithchart/utils/export';
import { SmithchartExportType } from '../smithchart/utils/enum';
import { PdfPageOrientation } from '@syncfusion/ej2-pdf-export';
import { titleRender, subtitleRender, load, loaded } from '../smithchart/model/constant';
import { SmithchartModel } from '../smithchart/smithchart-model';
/**
* Represents the Smithchart control.
* ```html
* <div id="smithchart"/>
* <script>
* var chartObj = new Smithchart({ isResponsive : true });
* chartObj.appendTo("#smithchart");
* </script>
* ```
*/
@NotifyPropertyChanges
export class Smithchart extends Component<HTMLElement> implements INotifyPropertyChanged {
/**
* legend bounds
*/
public legendBounds: SmithchartRect;
/**
* area bounds
*/
public bounds: SmithchartRect;
/**
* `smithchartLegendModule` is used to add legend to the smithchart.
*/
public smithchartLegendModule: SmithchartLegend;
/**
* `tooltipRenderModule` is used to add tooltip to the smithchart.
*/
public tooltipRenderModule: TooltipRender;
/**
* render type of smithchart.
*
* @default Impedance
*/
@Property('Impedance')
public renderType: RenderType;
/**
* width for smithchart.
*
* @default ''
*/
@Property('')
public width: string;
/**
* height for smithchart.
*
* @default ''
*/
@Property('')
public height: string;
/**
* theme for smithchart.
*
* @default Material
*/
@Property('Material')
public theme: SmithchartTheme;
/** @private */
public seriesrender: SeriesRender;
/** @private */
public themeStyle: ISmithchartThemeStyle;
/** @private */
public availableSize: SmithchartSize;
/**
* options for customizing margin
*/
@Complex<SmithchartMarginModel>({}, SmithchartMargin)
public margin: SmithchartMarginModel;
/**
* options for customizing margin
*/
@Complex<SmithchartFontModel>({}, SmithchartFont)
public font: SmithchartFontModel;
/**
* options for customizing border
*/
@Complex<SmithchartBorderModel>({}, SmithchartBorder)
public border: SmithchartBorderModel;
/**
* options for customizing title
*/
@Complex<TitleModel>({}, Title)
public title: TitleModel;
/**
* options for customizing series
*/
@Collection<SmithchartSeriesModel>([{}], SmithchartSeries)
public series: SmithchartSeriesModel[];
/**
* options for customizing legend
*/
@Complex<SmithchartLegendSettingsModel>({}, SmithchartLegendSettings)
public legendSettings: SmithchartLegendSettingsModel;
/**
* Options to configure the horizontal axis.
*/
@Complex<SmithchartAxisModel>({}, SmithchartAxis)
public horizontalAxis: SmithchartAxisModel;
/**
* Options to configure the vertical axis.
*/
@Complex<SmithchartAxisModel>({}, SmithchartAxis)
public radialAxis: SmithchartAxisModel;
/**
* svg renderer object.
*
* @private
*/
public renderer: SvgRenderer;
/** @private */
public svgObject: Element;
/** @private */
public animateSeries: boolean;
/** @private */
public seriesColors: string[];
public chartArea: SmithchartRect;
/**
* Resize the smithchart
*/
private resizeTo: number;
private isTouch: boolean;
private fadeoutTo: number;
/**
* The background color of the smithchart.
*/
@Property(null)
public background: string;
/**
* Spacing between elements
*
* @default 10
*/
@Property(10)
public elementSpacing: number;
/**
* Spacing between elements
*
* @default 1
*/
@Property(1)
public radius: number;
/**
* Triggers before the prints gets started.
*
* @event beforePrint
*/
@Event()
public beforePrint: EmitType<ISmithchartPrintEventArgs>;
/**
* Triggers after the animation completed.
*
* @event animationComplete
*/
@Event()
public animationComplete: EmitType<ISmithchartAnimationCompleteEventArgs>;
/**
* Triggers before smithchart rendered.
*
* @event load
*/
@Event()
public load: EmitType<ISmithchartLoadEventArgs>;
/**
* Triggers after smithchart rendered.
*
* @event loaded
*/
@Event()
public loaded: EmitType<ISmithchartLoadedEventArgs>;
/**
* Triggers before the legend is rendered.
*
* @event legendRender
*/
@Event()
public legendRender: EmitType<ISmithchartLegendRenderEventArgs>;
/**
* Triggers before the title is rendered.
*
* @event titleRender
*/
@Event()
public titleRender: EmitType<ITitleRenderEventArgs>;
/**
* Triggers before the sub-title is rendered.
*
* @event subtitleRender
*/
@Event()
public subtitleRender: EmitType<ISubTitleRenderEventArgs>;
/**
* Triggers before the datalabel text is rendered.
*
* @event textRender
*/
@Event()
public textRender: EmitType<ISmithchartTextRenderEventArgs>;
/**
* Triggers before the axis label is rendered
*
* @event axisLabelRender
*/
@Event()
public axisLabelRender: EmitType<ISmithchartAxisLabelRenderEventArgs>;
/**
* Triggers before the series is rendered.
*
* @event seriesRender
*/
@Event()
public seriesRender: EmitType<ISmithchartSeriesRenderEventArgs>;
/**
* Triggers before the tooltip rendering
*
* @event tooltipRender
*/
@Event()
public tooltipRender: EmitType<ISmithChartTooltipEventArgs>;
/**
* Get component name
*/
public getModuleName(): string {
return 'smithchart';
}
/**
* Get the properties to be maintained in the persisted state.
*
* @private
*/
public getPersistData(): string {
return '';
}
/**
* Method to create SVG element.
*/
private createChartSvg(): void {
this.removeSvg();
createSvg(this);
}
private renderTitle(title: TitleModel, type: string, groupEle: Element): void {
const font: SmithchartFontModel = title.font ? title.font : title.textStyle;
let textSize: SmithchartSize = measureText(title.text, font);
let x: number;
const textAlignment: string = title.textAlignment;
let titleText: string = title.text;
const maxTitleWidth: number = (isNullOrUndefined(title.maximumWidth)) ?
Math.abs(this.margin.left + this.margin.right - (this.availableSize.width)) :
title.maximumWidth;
const titleWidthEnable: boolean = textSize.width > maxTitleWidth ? true : false;
if (textSize.width > this.availableSize.width) {
x = this.margin.left + this.border.width;
} else {
x = textAlignment === 'Center' ? (this.availableSize.width / 2 - textSize['width'] / 2) :
(textAlignment === 'Near' ? (this.margin.left + this.elementSpacing + this.border.width) : (this.availableSize.width
- textSize['width'] - (this.margin.right + this.elementSpacing + this.border.width)));
}
const y: number = this.margin.top + textSize['height'] / 2 + this.elementSpacing;
if (title.enableTrim && titleWidthEnable) {
titleText = textTrim(maxTitleWidth, title.text, font);
textSize = measureText(titleText, font);
}
groupEle = this.renderer.createGroup({ id: this.element.id + '_Title_Group' });
const titleEventArgs: ITitleRenderEventArgs = {
text: titleText,
x: x,
y: y,
name: titleRender,
cancel: false
};
let options: TextOption;
const titleRenderSuccess: Function = (args: ITitleRenderEventArgs) => {
if (!args.cancel) {
options = new TextOption(
this.element.id + '_Smithchart_' + type, args.x, args.y, 'start', args.text
);
font.fontFamily = this.themeStyle.fontFamily || title.textStyle.fontFamily;
font.size = this.themeStyle.fontSize || title.textStyle.size;
const element: Element = renderTextElement(options, font, this.themeStyle.chartTitle, groupEle);
element.setAttribute('aria-label', title.description || args.text);
const titleLocation: { x: number, y: number, textSize: SmithchartSize } = { x: args.x, y: args.y, textSize: textSize };
this.svgObject.appendChild(groupEle);
if (title.subtitle.text !== '' && title.subtitle.visible) {
this.renderSubtitle(title, type, textSize, this.availableSize, titleLocation, groupEle);
}
}
};
titleRenderSuccess.bind(this);
this.trigger(titleRender, titleEventArgs, titleRenderSuccess);
}
private renderSubtitle(
title: TitleModel, type: string, textSize: SmithchartSize, size: SmithchartSize,
titleLocation: { x: number, y: number, textSize: SmithchartSize }, groupEle: Element): void {
const font: SmithchartFontModel = title.subtitle.textStyle;
const subTitle: SubtitleModel = title.subtitle;
const subTitleSize: SmithchartSize = measureText(subTitle.text, font);
let subTitleText: string = subTitle.text;
const maxSubTitleWidth: number = isNullOrUndefined(subTitle.maximumWidth) ?
(this.bounds.width * 0.75) : subTitle.maximumWidth;
if (subTitle.enableTrim && subTitleSize.width > maxSubTitleWidth) {
subTitleText = textTrim(maxSubTitleWidth, subTitle.text, font);
}
const x: number = title['subtitle'].textAlignment === 'Far' ? (titleLocation.x + (titleLocation.textSize.width)) :
(title['subtitle'].textAlignment === 'Near') ? titleLocation.x :
(titleLocation.x + (titleLocation.textSize.width / 2));
const y: number = titleLocation.y + (2 * this.elementSpacing);
const textAnchor: string = title['subtitle'].textAlignment === 'Far' ? 'end' :
(title['subtitle'].textAlignment === 'Near') ? 'start' : 'middle';
const subtitleEventArgs: ISubTitleRenderEventArgs = {
text: subTitleText,
x: x,
y: y,
name: subtitleRender,
cancel: false
};
const subtitleRenderSuccess: Function = (args: ISubTitleRenderEventArgs) => {
if (!args.cancel) {
const options: TextOption = new TextOption(
this.element.id + '_Smithchart_' + type, args.x, args.y, textAnchor, args.text
);
const element: Element = renderTextElement(options, font, this.themeStyle.chartTitle, groupEle);
element.setAttribute('aria-label', subTitle.description || args.text);
groupEle.appendChild(element);
}
};
subtitleRenderSuccess.bind(this);
this.trigger(subtitleRender, subtitleEventArgs, subtitleRenderSuccess);
}
/**
* Render the smithchart border
*
* @private
*/
private renderBorder(): void {
const border: SmithchartBorderModel = this.border;
this.background = this.background ? this.background : this.themeStyle.background;
const borderRect: RectOption = new RectOption(
this.element.id + '_SmithchartBorder', this.background, border, 1, new SmithchartRect(
border.width / 2, border.width / 2,
this.availableSize.width - border.width,
this.availableSize.height - border.width));
this.svgObject.appendChild(this.renderer.drawRectangle(borderRect) as SVGRectElement);
}
/**
* Called internally if any of the property value changed.
*
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public onPropertyChanged(newProp: SmithchartModel, oldProp: SmithchartModel): void {
let renderer: boolean = false;
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'background':
case 'border':
case 'series':
case 'legendSettings':
case 'radius':
renderer = true;
break;
case 'size':
this.createChartSvg();
renderer = true;
break;
case 'theme':
case 'renderType':
this.animateSeries = true;
renderer = true;
break;
}
}
if (renderer) {
this.render();
}
}
/**
* Constructor for creating the Smithchart widget
*/
constructor(options?: SmithchartModel, element?: string | HTMLElement) {
super(options, <HTMLElement | string>element);
}
/**
* Initialize the event handler.
*/
protected preRender(): void {
this.allowServerDataBinding = false;
this.trigger(load, { smithchart: this });
this.unWireEVents();
this.initPrivateVariable();
this.wireEVents();
}
private initPrivateVariable(): void {
this.animateSeries = true;
}
/**
* To Initialize the control rendering.
*/
private setTheme(): void {
/*! Set theme */
this.themeStyle = getThemeColor(this.theme);
this.seriesColors = getSeriesColor(this.theme);
// let count: number = colors.length;
// for (let i: number = 0; i < this.series.length; i++) {
// this.series[i].fill = this.series[i].fill ? this.series[i].fill : colors[i % count];
// }
}
protected render(): void {
this.createChartSvg();
this.element.appendChild(this.svgObject);
this.setTheme();
this.createSecondaryElement();
this.renderBorder();
if (this.smithchartLegendModule && this.legendSettings.visible) {
this.legendBounds = this.smithchartLegendModule.renderLegend(this);
}
this.legendBounds = this.legendBounds ? this.legendBounds : { x: 0, y: 0, width: 0, height: 0 };
const areaBounds: AreaBounds = new AreaBounds();
this.bounds = areaBounds.calculateAreaBounds(this, this.title, this.legendBounds);
if (this.title.text !== '' && this.title.visible) {
this.renderTitle(this.title, 'title', null);
}
const axisRender: AxisRender = new AxisRender();
axisRender.renderArea(this, this.bounds);
this.seriesrender = new SeriesRender();
this.seriesrender.draw(this, axisRender, this.bounds);
this.renderComplete();
this.allowServerDataBinding = true;
this.trigger(loaded, { smithchart: this });
}
private createSecondaryElement(): void {
if (isNullOrUndefined(document.getElementById(this.element.id + '_Secondary_Element'))) {
const secondaryElement: HTMLElement = createElement('div', {
id: this.element.id + '_Secondary_Element',
styles: 'z-index:1;'
});
this.element.appendChild(secondaryElement);
const rect: ClientRect = this.element.getBoundingClientRect();
const svgRect: HTMLElement = document.getElementById(this.element.id + '_svg');
if (svgRect) {
const svgClientRect: ClientRect = svgRect.getBoundingClientRect();
secondaryElement.style.left = Math.max(svgClientRect.left - rect.left, 0) + 'px';
secondaryElement.style.top = Math.max(svgClientRect.top - rect.top, 0) + 'px';
}
} else {
removeElement(this.element.id + '_Secondary_Element');
}
}
/**
* To destroy the widget
*
* @returns {void}.
*/
public destroy(): void {
if (this.element) {
this.unWireEVents();
super.destroy();
this.element.classList.remove('e-smithchart');
this.removeSvg();
this.svgObject = null;
}
}
/**
* To bind event handlers for smithchart.
*/
private wireEVents(): void {
EventHandler.add(this.element, 'click', this.smithchartOnClick, this);
EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this);
EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this);
window.addEventListener(
(Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize',
this.smithchartOnResize.bind(this)
);
}
public mouseMove(e: PointerEvent): void {
if (e.type === 'touchmove') {
this.isTouch = true;
} else {
this.isTouch = e.pointerType === 'touch' || e.pointerType === '2' || this.isTouch;
}
if (this.tooltipRenderModule && !this.isTouch) {
this.tooltipRenderModule.smithchartMouseMove(this, e);
}
}
public mouseEnd(e: PointerEvent): void {
if (e.type === 'touchend') {
this.isTouch = true;
} else {
this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';
}
if (this.tooltipRenderModule && this.isTouch) {
const tooltipElement: Tooltip = this.tooltipRenderModule.smithchartMouseMove(this, e);
if (tooltipElement) {
this.fadeoutTo = +setTimeout(
(): void => {
tooltipElement.fadeOut();
},
2000);
}
}
}
/**
* To handle the click event for the smithchart.
*/
public smithchartOnClick(e: PointerEvent): void {
const targetEle: Element = <Element>e.target;
const targetId: string = targetEle.id;
const parentElement: Element = document.getElementById(targetId).parentElement;
const grpElement: Element = document.getElementById(parentElement.id).parentElement;
if (grpElement.id === 'containerlegendItem_Group' && this.legendSettings.toggleVisibility) {
const childElement: HTMLElement = <HTMLElement>parentElement.childNodes[1];
const circleElement: HTMLElement = <HTMLElement>parentElement.childNodes[0];
const legendText: string = childElement.textContent;
let seriesIndex: number;
let fill: string;
for (let i: number = 0; i < this.smithchartLegendModule.legendSeries.length; i++) {
if (legendText === this.smithchartLegendModule.legendSeries[i]['text']) {
seriesIndex = this.smithchartLegendModule.legendSeries[i].seriesIndex;
fill = this.smithchartLegendModule.legendSeries[i].fill;
}
}
const seriesElement: HTMLElement = <HTMLElement>document.getElementById(
this.element.id + '_svg' + '_seriesCollection' + seriesIndex);
if (seriesElement.getAttribute('visibility') === 'visible') {
circleElement.setAttribute('fill', 'gray');
seriesElement.setAttribute('visibility', 'hidden');
this.series[seriesIndex].visibility = 'hidden';
} else {
circleElement.setAttribute('fill', fill);
seriesElement.setAttribute('visibility', 'visible');
this.series[seriesIndex].visibility = 'visible';
}
}
}
/**
* To unbind event handlers from smithchart.
*/
private unWireEVents(): void {
EventHandler.remove(this.element, 'click', this.smithchartOnClick);
EventHandler.remove(this.element, Browser.touchMoveEvent, this.mouseMove);
EventHandler.remove(this.element, Browser.touchEndEvent, this.mouseEnd);
window.removeEventListener(
(Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize',
this.smithchartOnResize
);
}
public print(id?: string[] | string | Element): void {
const exportChart: ExportUtils = new ExportUtils(this);
exportChart.print(id);
}
/**
* Handles the export method for chart control.
*/
public export(type: SmithchartExportType, fileName: string, orientation?: PdfPageOrientation): void {
const exportMap: ExportUtils = new ExportUtils(this);
exportMap.export(type, fileName, orientation);
}
/**
* To handle the window resize event on smithchart.
*/
public smithchartOnResize(): boolean {
this.animateSeries = false;
if (this.resizeTo) {
clearTimeout(this.resizeTo);
}
this.resizeTo = +setTimeout(
(): void => {
this.render();
},
500);
return false;
}
/**
* To provide the array of modules needed for smithchart rendering
*
* @private
*/
public requiredModules(): ModuleDeclaration[] {
const modules: ModuleDeclaration[] = [];
if (this.legendSettings.visible) {
modules.push({
member: 'SmithchartLegend',
args: [this]
});
}
for (let i: number = 0; i < this.series.length; i++) {
if (this.series[i].tooltip.visible) {
modules.push({
member: 'TooltipRender',
args: [this]
});
break;
}
}
return modules;
}
/**
* To Remove the SVG.
*
* @private
*/
public removeSvg(): void {
removeElement(this.element.id + '_Secondary_Element');
const removeLength: number = 0;
if (this.svgObject) {
while (this.svgObject.childNodes.length > removeLength) {
this.svgObject.removeChild(this.svgObject.firstChild);
}
if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {
remove(this.svgObject);
}
}
}
} | the_stack |
import '@polymer/polymer/polymer-legacy';
import '@polymer/app-layout/app-drawer/app-drawer';
import '@polymer/app-layout/app-drawer-layout/app-drawer-layout';
import '@polymer/app-layout/app-toolbar/app-toolbar';
import '@polymer/iron-icon/iron-icon';
import '@polymer/iron-icons/iron-icons';
import '@polymer/iron-pages/iron-pages';
import '@polymer/paper-icon-button/paper-icon-button';
import '@polymer/paper-toast/paper-toast';
import '@polymer/paper-dialog/paper-dialog';
import '@polymer/paper-dialog-scrollable/paper-dialog-scrollable';
import '@polymer/paper-listbox/paper-listbox';
import '@polymer/paper-menu-button/paper-menu-button';
import './cloud-install-styles';
import './outline-about-dialog';
import './outline-do-oauth-step';
import './outline-gcp-oauth-step';
import './outline-gcp-create-server-app';
import './outline-feedback-dialog';
import './outline-survey-dialog';
import './outline-intro-step';
import './outline-per-key-data-limit-dialog';
import './outline-language-picker';
import './outline-manual-server-entry';
import './outline-modal-dialog';
import './outline-region-picker-step';
import './outline-server-list';
import './outline-tos-view';
import {AppLocalizeBehavior} from '@polymer/app-localize-behavior/app-localize-behavior';
import {mixinBehaviors} from '@polymer/polymer/lib/legacy/class';
import {html} from '@polymer/polymer/lib/utils/html-tag';
import {PolymerElement} from '@polymer/polymer/polymer-element';
import {DisplayCloudId} from './cloud-assets';
import type {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin';
import type {AppDrawerElement} from '@polymer/app-layout/app-drawer/app-drawer';
import type {AppDrawerLayoutElement} from '@polymer/app-layout/app-drawer-layout/app-drawer-layout';
import type {PaperDialogElement} from '@polymer/paper-dialog/paper-dialog';
import type {PaperToastElement} from '@polymer/paper-toast/paper-toast';
import type {PolymerElementProperties} from '@polymer/polymer/interfaces';
import type {OutlineRegionPicker} from './outline-region-picker-step';
import type {OutlineDoOauthStep} from './outline-do-oauth-step';
import type {GcpConnectAccountApp} from './outline-gcp-oauth-step';
import type {GcpCreateServerApp} from './outline-gcp-create-server-app';
import type {OutlineServerList, ServerViewListEntry} from './outline-server-list';
import type {OutlineManualServerEntry} from './outline-manual-server-entry';
import type {OutlinePerKeyDataLimitDialog} from './outline-per-key-data-limit-dialog';
import type {OutlineFeedbackDialog} from './outline-feedback-dialog';
import type {OutlineAboutDialog} from './outline-about-dialog';
import type {OutlineShareDialog} from './outline-share-dialog';
import type {OutlineMetricsOptionDialog} from './outline-metrics-option-dialog';
import type {OutlineModalDialog} from './outline-modal-dialog';
import type {ServerView} from './outline-server-view';
import type {LanguageDef} from './outline-language-picker';
const TOS_ACK_LOCAL_STORAGE_KEY = 'tos-ack';
/** A cloud account to be displayed */
type AccountListEntry = {
id: string;
name: string;
};
/** An access key to be displayed */
export type ServerListEntry = {
id: string;
accountId: string;
name: string;
isSynced: boolean;
};
// mixinBehaviors() returns `any`, but the documentation indicates that
// this is the actual return type.
const polymerElementWithLocalize =
mixinBehaviors(AppLocalizeBehavior, PolymerElement) as
new () => PolymerElement&LegacyElementMixin&AppLocalizeBehavior;
export class AppRoot extends polymerElementWithLocalize {
static get template() {
return html`
<style include="cloud-install-styles"></style>
<style>
:host {
--side-bar-width: 48px;
}
.app-container {
margin: 0 auto;
}
/* Large display desktops */
@media (min-width: 1281px) {
.app-container {
max-width: 1200px;
}
}
/* Laptop, desktops */
@media (min-width: 1025px) and (max-width: 1280px) {
.app-container {
max-width: 920px;
}
}
#toast {
align-items: center;
display: flex;
justify-content: space-between;
padding: 24px;
max-width: 450px;
}
#toast paper-icon-button {
/* prevents the icon from resizing when there is a long message in the toast */
flex-shrink: 0;
padding: 0;
height: 20px;
width: 20px;
}
/* rtl:begin:ignore */
#appDrawer {
--app-drawer-content-container: {
color: var(--medium-gray);
background-color: var(--background-contrast-color);
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: right;
}
}
/* rtl:end:ignore */
#appDrawer > * {
width: 100%;
}
.servers {
overflow-y: scroll;
flex: 1;
}
.servers::-webkit-scrollbar {
/* Do not display the scroll bar in the drawer or side bar. It is not styled on some platforms. */
display: none;
}
.servers-section {
padding: 12px 0;
border-bottom: 1px solid var(--border-color);
}
.servers-section:last-child {
border-bottom: none;
}
.servers-header {
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 24px;
line-height: 39px;
}
.servers-header > span {
flex: 1;
}
.do-overflow-menu {
padding: 24px;
color: var(--dark-gray);
text-align: left;
display: flex;
flex-direction: column;
}
.do-overflow-menu h4 {
margin-top: 0;
white-space: nowrap;
}
.do-overflow-menu .account-info {
display: flex;
align-items: center;
color: var(--faded-gray);
}
.do-overflow-menu .account-info img {
margin-right: 12px;
width: 24px;
}
.do-overflow-menu .sign-out-button {
margin-top: 24px;
align-self: flex-end;
font-weight: bold;
cursor: pointer;
text-transform: uppercase;
}
.servers-container {
padding-right: 12px; /* In case the server name is wraps. */
}
.server {
display: flex;
align-items: center;
width: 100%; /* For the side bar icons. */
margin: 18px 0;
padding: 6px 0;
cursor: pointer;
}
.server.selected {
color: white;
border-left: 2px solid var(--primary-green);
}
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.server.syncing {
cursor: wait;
}
.syncing .server-icon {
animation: rotate 1.75s ease-out infinite;
opacity: 0.5;
}
.server-icon {
width: 22px;
height: 22px;
/* Prevent the image from shrinking when the server title spans multiple lines */
min-width: 22px !important;
margin: 0 24px;
}
.selected > .server-icon {
/* Account for the selected border width to preserve center alignment. */
margin-left: 22px;
}
.add-server-section {
padding: 24px 0;
text-transform: uppercase;
color: var(--primary-green);
font-size: 12px;
letter-spacing: 0.6px;
border-top: 1px solid var(--border-color);
border-bottom: 1px solid var(--border-color);
cursor: pointer;
}
.add-server-section paper-icon-item {
margin-left: 24px;
}
.add-server-section paper-icon-item iron-icon {
margin-right: 24px;
}
#appDrawer > paper-listbox {
color: var(--medium-gray);
background-color: var(--background-contrast-color);
}
#appDrawer > paper-listbox > * {
display: block;
cursor: pointer;
padding-left: 24px;
font-size: 14px;
line-height: 40px;
outline: none;
}
#appDrawer a {
color: inherit;
}
#appDrawer a:focus {
outline: none;
}
#links-footer {
margin-top: 36px;
}
.legal-links {
margin: 0 -6px;
}
.legal-links > * {
margin: 0 6px;
}
#language-row {
display: flex;
align-items: center;
}
#language-icon {
padding-top: 10px;
}
#language-dropdown {
padding-left: 22px;
--paper-input-container: {
width: 156px;
};
}
app-toolbar [main-title] img {
height: 16px;
margin-top: 8px;
}
.side-bar-margin {
margin-left: var(--side-bar-width);
}
/* rtl:begin:ignore */
#sideBar {
--app-drawer-width: var(--side-bar-width);
--app-drawer-content-container: {
background-color: var(--background-contrast-color);
}
}
/* rtl:end:ignore */
.side-bar-container {
height: 100%;
text-align: center;
color: var(--light-gray);
display: flex;
flex-direction: column;
}
.side-bar-container .servers {
flex: initial; /* Prevent the server list pushing down the add server button. */
}
.side-bar-section {
display: flex;
flex-direction: column;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--border-color);
}
.side-bar-section.menu {
min-height: 32px;
}
.side-bar-section.servers-section {
padding: 24px 0;
}
.side-bar-section .server {
justify-content: center;
margin: 12px auto;
padding: 2px 0;
}
.side-bar-section .provider-icon {
margin-bottom: 12px;
padding: 12px 0;
opacity: 0.54;
filter: grayscale(100%);
}
.side-bar-section.add-server-section {
flex: 1 0 24px;
border-bottom: none;
}
.side-bar-section > .server-icon {
margin: 0;
}
#getConnectedDialog {
height: 562px;
background: white;
}
#getConnectedDialog iframe {
padding: 0;
margin: 0;
width: 100%;
border: none;
border-bottom: 1px solid #ccc;
height: 500px;
}
#getConnectedDialog .buttons {
margin-top: -5px; /* undo spacing added after iframe */
}
</style>
<outline-tos-view id="tosView" has-accepted-terms-of-service="{{userAcceptedTos}}" hidden\$="{{hasAcceptedTos}}" localize="[[localize]]"></outline-tos-view>
<div hidden\$="{{!hasAcceptedTos}}">
<!-- This responsive width sets the minimum layout area to 648px. -->
<app-drawer-layout id="drawerLayout" responsive-width="886px" on-narrow-changed="_computeShouldShowSideBar" class\$="[[sideBarMarginClass]]">
<app-drawer id="appDrawer" slot="drawer" on-opened-changed="_computeShouldShowSideBar">
<app-toolbar class="toolbar" hidden\$="[[shouldShowSideBar]]">
<paper-icon-button icon="menu" on-click="_toggleAppDrawer"></paper-icon-button>
<div main-title=""><img src="images/outline-manager-logo.svg"></div>
</app-toolbar>
<!-- Servers section -->
<div class="servers">
${this.expandedServersTemplate()}
</div>
<!-- Add server -->
<div class="add-server-section" on-tap="showIntro">
<paper-icon-item>
<iron-icon icon="add" slot="item-icon"></iron-icon>[[localize('servers-add')]]
</paper-icon-item>
</div>
<!-- Links section -->
<paper-listbox>
<span on-tap="maybeCloseDrawer"><a href="https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection">[[localize('nav-data-collection')]]</a></span>
<span on-tap="submitFeedbackTapped">[[localize('nav-feedback')]]</span>
<span on-tap="maybeCloseDrawer"><a href="https://s3.amazonaws.com/outline-vpn/index.html#/en/support/">[[localize('nav-help')]]</a></span>
<span on-tap="aboutTapped">[[localize('nav-about')]]</span>
<div id="links-footer">
<paper-icon-item id="language-row">
<iron-icon id="language-icon" icon="language" slot="item-icon"></iron-icon>
<outline-language-picker id="language-dropdown" selected-language="{{language}}" languages="{{supportedLanguages}}"></outline-language-picker>
</paper-icon-item>
<div class="legal-links" on-tap="maybeCloseDrawer">
<a href="https://www.google.com/policies/privacy/">[[localize('nav-privacy')]]</a>
<a href="https://s3.amazonaws.com/outline-vpn/static_downloads/Outline-Terms-of-Service.html">[[localize('nav-terms')]]</a>
<span on-tap="showLicensesTapped">[[localize('nav-licenses')]]</span>
</div>
</div>
</paper-listbox>
</app-drawer>
<app-header-layout>
<div class="app-container">
<iron-pages attr-for-selected="id" selected="{{ currentPage }}">
<outline-intro-step id="intro" digital-ocean-account-name="{{digitalOceanAccount.name}}" gcp-account-name="{{gcpAccount.name}}" localize="[[localize]]"></outline-intro-step>
<outline-do-oauth-step id="digitalOceanOauth" localize="[[localize]]"></outline-do-oauth-step>
<outline-gcp-oauth-step id="gcpOauth" localize="[[localize]]"></outline-gcp-oauth-step>
<outline-gcp-create-server-app id="gcpCreateServer" localize="[[localize]]" language="[[language]]"></outline-gcp-create-server-app>
<outline-manual-server-entry id="manualEntry" localize="[[localize]]"></outline-manual-server-entry>
<!-- TODO: Move to a new outline-do-oauth-step. -->
<outline-region-picker-step id="regionPicker" localize="[[localize]]" language="[[language]]"></outline-region-picker-step>
<outline-server-list id="serverView" server-list="[[_serverViewList(serverList)]]" selected-server-id="[[selectedServerId]]" language="[[language]]" localize="[[localize]]"></outline-server-list>
</div>
</iron-pages>
</div>
</app-header-layout>
</app-drawer-layout>
<!-- Side bar -->
<app-drawer id="sideBar" opened\$="[[shouldShowSideBar]]" persistent="">
<div class="side-bar-container">
<div class="side-bar-section menu">
<paper-icon-button icon="menu" on-click="_toggleAppDrawer"></paper-icon-button>
</div>
<div class="servers">
${this.minimizedServersTemplate()}
</div>
<div class="side-bar-section add-server-section" on-tap="showIntro">
<paper-icon-item>
<iron-icon icon="add" slot="item-icon"></iron-icon>
</paper-icon-item>
</div>
</div>
</app-drawer>
<paper-toast id="toast"><paper-icon-button icon="icons:close" on-tap="closeError"></paper-icon-button></paper-toast>
<!-- Modal dialogs must be outside the app container; otherwise the backdrop covers them. -->
<outline-survey-dialog id="surveyDialog" localize="[[localize]]"></outline-survey-dialog>
<outline-feedback-dialog id="feedbackDialog" localize="[[localize]]"></outline-feedback-dialog>
<outline-about-dialog id="aboutDialog" outline-version="[[outlineVersion]]" localize="[[localize]]"></outline-about-dialog>
<outline-modal-dialog id="modalDialog"></outline-modal-dialog>
<outline-share-dialog id="shareDialog" localize="[[localize]]"></outline-share-dialog>
<outline-metrics-option-dialog id="metricsDialog" localize="[[localize]]"></outline-metrics-option-dialog>
<outline-per-key-data-limit-dialog id="perKeyDataLimitDialog" language="[[language]]" localize="[[localize]]"></outline-per-key-data-limit-dialog>
<paper-dialog id="getConnectedDialog" modal="">
<!-- iframe gets inserted here once we are given the invite URL. -->
<div class="buttons">
<paper-button on-tap="closeGetConnectedDialog" autofocus="">[[localize('close')]]</paper-button>
</div>
</paper-dialog>
<paper-dialog id="licenses" modal="" restorefocusonclose="">
<paper-dialog-scrollable>
<code id="licensesText">
[[localize('error-licenses')]]
</code>
</paper-dialog-scrollable>
<div class="buttons">
<paper-button dialog-dismiss="" autofocus="">[[localize('close')]]</paper-button>
</div>
</paper-dialog>
</div>
`;
}
static expandedServersTemplate() {
return html`
<!-- DigitalOcean servers -->
<div class="servers-section" hidden\$="[[!digitalOceanAccount]]">
<div class="servers-header">
<span>[[localize('servers-digitalocean')]]</span>
<paper-menu-button horizontal-align="left" class="" close-on-activate="" no-animations="" dynamic-align="" no-overlap="">
<paper-icon-button icon="more-vert" slot="dropdown-trigger"></paper-icon-button>
<div class="do-overflow-menu" slot="dropdown-content">
<h4>[[localize('digitalocean-disconnect-account')]]</h4>
<div class="account-info"><img src="images/digital_ocean_logo.svg">[[digitalOceanAccount.name]]</div>
<div class="sign-out-button" on-tap="_digitalOceanSignOutTapped">[[localize('disconnect')]]</div>
</div>
</paper-menu-button>
</div>
<div class="servers-container">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="[[_accountServerFilter(digitalOceanAccount)]]" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
<span>[[server.name]]</span>
</div>
</template>
</div>
</div>
<!-- GCP servers -->
<div class="servers-section" hidden\$="[[!gcpAccount]]">
<div class="servers-header">
<span>[[localize('servers-gcp')]]</span>
<paper-menu-button horizontal-align="left" class="" close-on-activate="" no-animations="" dynamic-align="" no-overlap="">
<paper-icon-button icon="more-vert" slot="dropdown-trigger"></paper-icon-button>
<div class="do-overflow-menu" slot="dropdown-content">
<h4>[[localize('gcp-disconnect-account')]]</h4>
<div class="account-info"><img src="images/gcp-logo.svg">[[gcpAccount.name]]</div>
<div class="sign-out-button" on-tap="_gcpSignOutTapped">[[localize('disconnect')]]</div>
</div>
</paper-menu-button>
</div>
<div class="servers-container">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="[[_accountServerFilter(gcpAccount)]]" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
<span>[[server.name]]</span>
</div>
</template>
</div>
</div>
<!-- Manual servers -->
<div class="servers-section" hidden\$="[[!_hasManualServers(serverList)]]">
<div class="servers-header">
<span>[[localize('servers-manual')]]</span>
</div>
<div class="servers-container">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="_isServerManual" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
<span>[[server.name]]</span>
</div>
</template>
</div>
</div>
`;
}
static minimizedServersTemplate() {
return html`
<!-- DigitalOcean servers -->
<div class="side-bar-section servers-section" hidden\$="[[!digitalOceanAccount]]">
<img class="provider-icon" src="images/do_white_logo.svg">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="[[_accountServerFilter(digitalOceanAccount)]]" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
</div>
</template>
</div>
<!-- GCP servers -->
<div class="side-bar-section servers-section" hidden\$="[[!gcpAccount]]">
<img class="provider-icon" src="images/gcp-logo.svg">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="[[_accountServerFilter(gcpAccount)]]" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
</div>
</template>
</div>
<!-- Manual servers -->
<div class="side-bar-section servers-section" hidden\$="[[!_hasManualServers(serverList)]]">
<img class="provider-icon" src="images/cloud.svg">
<template is="dom-repeat" items="[[serverList]]" as="server" filter="_isServerManual" sort="_sortServersByName">
<div class\$="server [[_computeServerClasses(selectedServerId, server)]]" data-server\$="[[server]]" on-tap="_showServer">
<img class="server-icon" src\$="images/[[_computeServerImage(selectedServerId, server)]]">
</div>
</template>
</div>
`;
}
static get is() {
return 'app-root';
}
static get properties(): PolymerElementProperties {
return {
// Properties language and useKeyIfMissing are used by Polymer.AppLocalizeBehavior.
language: {type: String},
supportedLanguages: {type: Array},
useKeyIfMissing: {type: Boolean},
serverList: {type: Array},
selectedServerId: {type: String},
digitalOceanAccount: Object,
gcpAccount: Object,
outlineVersion: String,
userAcceptedTos: {
type: Boolean,
// Get notified when the user clicks the OK button in the ToS view
observer: '_userAcceptedTosChanged',
},
hasAcceptedTos: {
type: Boolean,
computed: '_computeHasAcceptedTermsOfService(userAcceptedTos)',
},
currentPage: {
type: String,
observer: '_currentPageChanged',
},
shouldShowSideBar: {type: Boolean},
sideBarMarginClass: {
type: String,
computed: '_computeSideBarMarginClass(shouldShowSideBar)',
},
};
}
selectedServerId = '';
language = '';
supportedLanguages: LanguageDef[] = [];
useKeyIfMissing = true;
serverList: ServerListEntry[] = [];
digitalOceanAccount: AccountListEntry = null;
gcpAccount: AccountListEntry = null;
outlineVersion = '';
currentPage = 'intro';
shouldShowSideBar = false;
constructor() {
super();
this.addEventListener('RegionSelected', this.handleRegionSelected);
this.addEventListener(
'SetUpGenericCloudProviderRequested', this.handleSetUpGenericCloudProviderRequested);
this.addEventListener('SetUpAwsRequested', this.handleSetUpAwsRequested);
this.addEventListener('SetUpGcpRequested', this.handleSetUpGcpRequested);
this.addEventListener('ManualServerEntryCancelled', this.handleManualCancelled);
}
/**
* Loads a new translation file and returns a Promise which resolves when the file is loaded or
* rejects when there was an error loading translations.
*
* @param language The language code to load translations for, eg 'en'
*/
loadLanguageResources(language: string) {
const localizeResourcesResponder = new Promise<void>((resolve, reject) => {
// loadResources uses events and continuation instead of Promises. In order to make this
// function easier to use, we wrap the language-changing logic in event handlers which
// resolve or reject the Promise. Note that they need to clean up whichever event handler
// didn't fire so we don't leak it, which could cause future language changes to not work
// properly by triggering old event listeners.
let successHandler: () => void, failureHandler: () => void;
successHandler = () => {
this.removeEventListener('app-localize-resources-error', failureHandler);
resolve();
};
failureHandler = () => {
this.removeEventListener('app-localize-resources-loaded', successHandler);
reject(new Error(`Failed to load resources for language ${language}`));
};
this.addEventListener('app-localize-resources-loaded', successHandler, {once: true});
this.addEventListener('app-localize-resources-error', failureHandler, {once: true});
});
const messagesUrl = `./messages/${language}.json`;
this.loadResources(messagesUrl, language, /* merge= */ false);
return localizeResourcesResponder;
}
/**
* Sets the language and direction for the application
* @param language The ISO language code for the new language, e.g. 'en'.
*/
async setLanguage(language: string, direction: 'rtl'|'ltr') {
await this.loadLanguageResources(language);
const alignDir = direction === 'ltr' ? 'left' : 'right';
(this.$.appDrawer as AppDrawerElement).align = alignDir;
(this.$.sideBar as AppDrawerElement).align = alignDir;
this.language = language;
}
showIntro() {
this.maybeCloseDrawer();
this.selectedServerId = '';
this.currentPage = 'intro';
}
getDigitalOceanOauthFlow(onCancel: Function): OutlineDoOauthStep {
const oauthFlow = this.$.digitalOceanOauth as OutlineDoOauthStep;
oauthFlow.onCancel = onCancel;
return oauthFlow;
}
showDigitalOceanOauthFlow() {
this.currentPage = 'digitalOceanOauth';
}
getAndShowDigitalOceanOauthFlow(onCancel: Function) {
this.currentPage = 'digitalOceanOauth';
const oauthFlow = this.getDigitalOceanOauthFlow(onCancel);
oauthFlow.showConnectAccount();
return oauthFlow;
}
getAndShowGcpOauthFlow(onCancel: Function) {
this.currentPage = 'gcpOauth';
const oauthFlow = this.$.gcpOauth as GcpConnectAccountApp;
oauthFlow.onCancel = onCancel;
return oauthFlow;
}
getAndShowGcpCreateServerApp(): GcpCreateServerApp {
this.currentPage = 'gcpCreateServer';
return this.$.gcpCreateServer as GcpCreateServerApp;
}
getAndShowRegionPicker(): OutlineRegionPicker {
this.currentPage = 'regionPicker';
const regionPicker = this.$.regionPicker as OutlineRegionPicker;
regionPicker.reset();
return regionPicker;
}
getManualServerEntry() {
return this.$.manualEntry as OutlineManualServerEntry;
}
showServerView() {
this.currentPage = 'serverView';
}
_currentPageChanged() {
if (this.currentPage !== 'gcpCreateServer') {
// The refresh loop will be restarted by App, which calls
// GcpCreateServerApp.start() whenever it switches back to this page.
(this.$.gcpCreateServer as GcpCreateServerApp).stopRefreshingBillingAccounts();
}
}
/** Gets the ServerView for the server given by its id */
getServerView(displayServerId: string): Promise<ServerView> {
const serverList = this.shadowRoot.querySelector<OutlineServerList>('#serverView');
return serverList.getServerView(displayServerId);
}
handleRegionSelected(e: CustomEvent) {
this.fire('SetUpDigitalOceanServerRequested', {region: e.detail.selectedLocation});
}
handleSetUpGenericCloudProviderRequested() {
this.handleManualServerSelected('generic');
}
handleSetUpAwsRequested() {
this.handleManualServerSelected('aws');
}
handleSetUpGcpRequested() {
this.handleManualServerSelected('gcp');
}
handleManualServerSelected(cloudProvider: 'generic'|'aws'|'gcp') {
const manualEntry = this.$.manualEntry as OutlineManualServerEntry;
manualEntry.clear();
manualEntry.cloudProvider = cloudProvider;
this.currentPage = 'manualEntry';
}
handleManualCancelled() {
this.currentPage = 'intro';
}
showError(errorMsg: string) {
this.showToast(errorMsg, Infinity);
}
showNotification(message: string, durationMs = 3000) {
this.showToast(message, durationMs);
}
/**
* Show a toast with a message
* @param duration in seconds
*/
showToast(message: string, duration: number) {
const toast = this.$.toast as PaperToastElement;
toast.close();
// Defer in order to trigger the toast animation, otherwise the
// update happens in place.
setTimeout(() => {
toast.show({
text: message,
duration,
noOverlap: true,
});
}, 0);
}
closeError() {
(this.$.toast as PaperToastElement).close();
}
/**
* @param cb a function which accepts a single boolean which is true
* iff
* the user chose to retry the failing operation.
*/
showConnectivityDialog(cb: (retry: boolean) => void) {
const dialogTitle = this.localize('error-connectivity-title');
const dialogText = this.localize('error-connectivity');
this.showModalDialog(dialogTitle, dialogText, [this.localize('digitalocean-disconnect'), this.localize('retry')])
.then(clickedButtonIndex => {
cb(clickedButtonIndex === 1); // pass true if user clicked retry
});
}
getConfirmation(title: string, text: string, confirmButtonText: string,
continueFunc: Function) {
this.showModalDialog(title, text, [this.localize('cancel'), confirmButtonText])
.then(clickedButtonIndex => {
if (clickedButtonIndex === 1) {
// user clicked to confirm.
continueFunc();
}
});
}
showManualServerError(errorTitle: string, errorText: string) {
this.showModalDialog(errorTitle, errorText, [this.localize('cancel'), this.localize('retry')])
.then(clickedButtonIndex => {
const manualEntry = this.$.manualEntry as OutlineManualServerEntry;
if (clickedButtonIndex === 1) {
manualEntry.retryTapped();
} else {
manualEntry.cancelTapped();
}
});
}
_hasManualServers(serverList: ServerListEntry[]) {
return serverList.filter(server => !server.accountId).length > 0;
}
_userAcceptedTosChanged(userAcceptedTos: boolean) {
if (userAcceptedTos) {
window.localStorage[TOS_ACK_LOCAL_STORAGE_KEY] = Date.now();
}
}
_computeHasAcceptedTermsOfService(userAcceptedTos: boolean) {
return userAcceptedTos || !!window.localStorage[TOS_ACK_LOCAL_STORAGE_KEY];
}
_toggleAppDrawer() {
const drawerLayout = this.$.drawerLayout as AppDrawerLayoutElement;
const drawerNarrow = drawerLayout.narrow;
const forceNarrow = drawerLayout.forceNarrow;
if (drawerNarrow) {
if (forceNarrow) {
// The window width is below the responsive threshold. Do not force narrow mode.
drawerLayout.forceNarrow = false;
}
(this.$.appDrawer as AppDrawerElement).toggle();
} else {
// Forcing narrow mode when the window width is above the responsive threshold effectively
// collapses the drawer. Conversely, reverting force narrow expands the drawer.
drawerLayout.forceNarrow = !forceNarrow;
}
}
maybeCloseDrawer() {
const drawerLayout = this.$.drawerLayout as AppDrawerLayoutElement;
if (drawerLayout.narrow || drawerLayout.forceNarrow) {
(this.$.appDrawer as AppDrawerElement).close();
}
}
submitFeedbackTapped() {
(this.$.feedbackDialog as OutlineFeedbackDialog).open();
this.maybeCloseDrawer();
}
aboutTapped() {
(this.$.aboutDialog as OutlineAboutDialog).open();
this.maybeCloseDrawer();
}
_digitalOceanSignOutTapped() {
this.fire('DigitalOceanSignOutRequested');
}
_gcpSignOutTapped() {
this.fire('GcpSignOutRequested');
}
openManualInstallFeedback(prepopulatedMessage: string) {
(this.$.feedbackDialog as OutlineFeedbackDialog).open(prepopulatedMessage, true);
}
openShareDialog(accessKey: string, s3Url: string) {
(this.$.shareDialog as OutlineShareDialog).open(accessKey, s3Url);
}
openPerKeyDataLimitDialog(keyName: string, activeDataLimitBytes: number,
onDataLimitSet: (dataLimitBytes: number) => Promise<boolean>,
onDataLimitRemoved: () => Promise<boolean>) {
// attach listeners here
(this.$.perKeyDataLimitDialog as OutlinePerKeyDataLimitDialog).open(
keyName, activeDataLimitBytes, onDataLimitSet, onDataLimitRemoved);
}
openGetConnectedDialog(inviteUrl: string) {
const dialog = this.$.getConnectedDialog as PaperDialogElement;
if (dialog.children.length > 1) {
return; // The iframe is already loading.
}
// Reset the iframe's state, by replacing it with a newly constructed
// iframe. Unfortunately the location.reload API does not work in our case due to
// this Chrome error:
// "Blocked a frame with origin "outline://web_app" from accessing a cross-origin frame."
const iframe = document.createElement('iframe');
iframe.onload = () => dialog.open();
iframe.src = inviteUrl;
dialog.insertBefore(iframe, dialog.children[0]);
}
closeGetConnectedDialog() {
const dialog = this.$.getConnectedDialog as PaperDialogElement;
dialog.close();
const oldIframe = dialog.children[0];
dialog.removeChild(oldIframe);
}
showMetricsDialogForNewServer() {
(this.$.metricsDialog as OutlineMetricsOptionDialog).showMetricsOptInDialog();
}
/** @return A Promise which fulfills with the index of the button clicked. */
showModalDialog(title: string, text: string, buttons: string[]): Promise<number> {
return (this.$.modalDialog as OutlineModalDialog).open(title, text, buttons);
}
closeModalDialog() {
return (this.$.modalDialog as OutlineModalDialog).close();
}
showLicensesTapped() {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
(this.$.licensesText as HTMLElement).innerText = xhr.responseText;
(this.$.licenses as PaperDialogElement).open();
};
xhr.onerror = () => {
console.error('could not load license.txt');
};
xhr.open('GET', '/ui_components/licenses/licenses.txt', true);
xhr.send();
}
_computeShouldShowSideBar() {
const drawerNarrow = (this.$.drawerLayout as AppDrawerLayoutElement).narrow;
const drawerOpened = (this.$.appDrawer as AppDrawerElement).opened;
if (drawerOpened && drawerNarrow) {
this.shouldShowSideBar = false;
} else {
this.shouldShowSideBar = drawerNarrow;
}
}
_computeSideBarMarginClass(shouldShowSideBar: boolean) {
return shouldShowSideBar ? 'side-bar-margin' : '';
}
_accountServerFilter(account: AccountListEntry) {
return (server: ServerListEntry) => account && server.accountId === account.id;
}
_isServerManual(server: ServerListEntry) {
return !server.accountId;
}
_sortServersByName(a: ServerListEntry, b: ServerListEntry) {
const aName = a.name.toUpperCase();
const bName = b.name.toUpperCase();
if (aName < bName) {
return -1;
} else if (aName > bName) {
return 1;
}
return 0;
}
_computeServerClasses(selectedServerId: string, server: ServerListEntry) {
const serverClasses = [];
if (this._isServerSelected(selectedServerId, server)) {
serverClasses.push('selected');
}
if (!server.isSynced) {
serverClasses.push('syncing');
}
return serverClasses.join(' ');
}
_computeServerImage(selectedServerId: string, server: ServerListEntry) {
if (this._isServerSelected(selectedServerId, server)) {
return 'server-icon-selected.png';
}
return 'server-icon.png';
}
_getCloudId(accountId: string): DisplayCloudId {
// TODO: Replace separate account fields with a map.
if (this.gcpAccount && accountId === this.gcpAccount.id) {
return DisplayCloudId.GCP;
} else if (this.digitalOceanAccount && accountId === this.digitalOceanAccount.id) {
return DisplayCloudId.DO;
}
return null;
}
_serverViewList(serverList: ServerListEntry[]): ServerViewListEntry[] {
return serverList.map(entry => ({
id: entry.id,
name: entry.name,
cloudId: this._getCloudId(entry.accountId),
}));
}
_isServerSelected(selectedServerId: string, server: ServerListEntry) {
return !!selectedServerId && selectedServerId === server.id;
}
_showServer(event: Event&{ model: {server: ServerListEntry; }; }) {
const server = event.model.server;
this.fire('ShowServerRequested', {displayServerId: server.id});
this.maybeCloseDrawer();
}
}
customElements.define(AppRoot.is, AppRoot); | the_stack |
import expect = require('expect.js');
import { loadGapi } from '../../lib/gapi';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { Contents } from '@jupyterlab/services';
import { JSONExt, UUID } from '@lumino/coreutils';
import { GoogleDrive } from '../../lib/contents';
import { authorizeGapiTesting, expectFailure, expectAjaxError } from './util';
const DEFAULT_DIRECTORY: Contents.IModel = {
name: 'jupyterlab_test_directory',
path: 'My Drive/jupyterlab_test_directory',
type: 'directory',
created: 'yesterday',
last_modified: 'today',
writable: false,
mimetype: '',
content: undefined,
format: 'json'
};
const DEFAULT_TEXT_FILE: Contents.IModel = {
name: 'jupyterlab_test_file_',
path: 'My Drive/jupyterlab_test_directory/jupyterlab_test_file_',
type: 'file',
created: 'yesterday',
last_modified: 'today',
writable: false,
mimetype: '',
content: 'This is a text file with unicode: 클래스의 정의한 함수',
format: 'text'
};
const DEFAULT_NOTEBOOK: Contents.IModel = {
name: 'jupyterlab_test_notebook_',
path: 'My Drive/jupyterlab_test_directory/jupyterlab_test_notebook_',
type: 'notebook',
created: 'yesterday',
last_modified: 'today',
writable: false,
mimetype: '',
content: {
cells: [
{
cell_type: 'markdown',
metadata: {},
source: ['Here is some content. 클래스의 정의한 함수']
},
{
cell_type: 'code',
execution_count: 1,
metadata: {},
outputs: [
{
name: 'stdout',
output_type: 'stream',
text: ['3\n']
}
],
source: ['print(1+2)']
}
],
metadata: {
kernelspec: {
display_name: 'Python 3',
language: 'python',
name: 'python3'
},
language_info: {
codemirror_mode: {
name: 'ipython',
version: 3
}
}
},
nbformat: 4,
nbformat_minor: 2
},
format: 'json'
};
describe('GoogleDrive', () => {
let registry: DocumentRegistry;
let drive: GoogleDrive;
before(async () => {
try {
registry = new DocumentRegistry();
await loadGapi();
await authorizeGapiTesting();
} catch (err) {
console.error(err);
}
});
beforeEach(() => {
drive = new GoogleDrive(registry);
});
afterEach(() => {
drive.dispose();
});
describe('#constructor()', () => {
it('should create a new Google Drive object', () => {
let newDrive = new GoogleDrive(registry);
expect(newDrive).to.be.a(GoogleDrive);
newDrive.dispose();
});
});
describe('#name', () => {
it('should return "GDrive"', () => {
expect(drive.name).to.be('GDrive');
});
});
describe('#get()', () => {
it('should get the contents of the pseudo-root', async () => {
const contents = await drive.get('');
expect(contents.name).to.be('');
expect(contents.format).to.be('json');
expect(contents.type).to.be('directory');
expect(contents.writable).to.be(false);
});
it('should get the contents of `My Drive`', async () => {
const contents = await drive.get('My Drive');
expect(contents.name).to.be('My Drive');
expect(contents.format).to.be('json');
expect(contents.type).to.be('directory');
expect(contents.writable).to.be(true);
});
it('should get the contents of `Shared with me`', async () => {
const contents = await drive.get('Shared with me');
expect(contents.name).to.be('Shared with me');
expect(contents.format).to.be('json');
expect(contents.type).to.be('directory');
expect(contents.writable).to.be(false);
});
});
describe('#save()', () => {
it('should save a file', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
const model = await drive.save(contents.path, contents);
expect(model.name).to.be(contents.name);
expect(model.content).to.be(contents.content);
await drive.delete(model.path);
});
it('should be able to get an identical file back', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
await drive.save(contents.path, contents);
const model = await drive.get(contents.path);
expect(model.name).to.be(contents.name);
expect(model.content).to.be(contents.content);
await drive.delete(model.path);
});
it('should save a notebook', async () => {
let id = UUID.uuid4();
// Note, include .ipynb to interpret the result as a notebook.
let contents = {
...DEFAULT_NOTEBOOK,
name: DEFAULT_NOTEBOOK.name + String(id) + '.ipynb',
path: DEFAULT_NOTEBOOK.path + String(id) + '.ipynb'
};
const model = await drive.save(contents.path, contents);
expect(model.name).to.be(contents.name);
expect(JSONExt.deepEqual(model.content, contents.content)).to.be(true);
await drive.delete(model.path);
});
it('should be able to get an identical notebook back', async () => {
let id = UUID.uuid4();
// Note, include .ipynb to interpret the result as a notebook.
let contents = {
...DEFAULT_NOTEBOOK,
name: DEFAULT_NOTEBOOK.name + String(id) + '.ipynb',
path: DEFAULT_NOTEBOOK.path + String(id) + '.ipynb'
};
await drive.save(contents.path, contents);
const model = await drive.get(contents.path);
expect(model.name).to.be(contents.name);
expect(JSONExt.deepEqual(model.content, contents.content)).to.be(true);
await drive.delete(model.path);
});
it('should emit the fileChanged signal', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
let called = false;
const onFileChanged = (sender, args) => {
expect(args.type).to.be('save');
expect(args.oldValue).to.be(null);
expect(args.newValue.path).to.be(contents.path);
called = true;
};
drive.fileChanged.connect(onFileChanged);
const model = await drive.save(contents.path, contents);
drive.fileChanged.disconnect(onFileChanged);
await drive.delete(model.path);
expect(called).to.be(true);
});
});
describe('#fileChanged', () => {
it('should be emitted when a file changes', async () => {
let called = false;
const onFileChanged = (sender, args) => {
expect(sender).to.be(drive);
expect(args.type).to.be('new');
expect(args.oldValue).to.be(null);
expect(args.newValue.name.indexOf('untitled') === -1).to.be(false);
called = true;
};
drive.fileChanged.connect(onFileChanged);
const model = await drive.newUntitled({
path: DEFAULT_DIRECTORY.path,
type: 'file'
});
drive.fileChanged.disconnect(onFileChanged);
await drive.delete(model.path);
expect(called).to.be(true);
});
});
describe('#isDisposed', () => {
it('should test whether the drive is disposed', () => {
expect(drive.isDisposed).to.be(false);
drive.dispose();
expect(drive.isDisposed).to.be(true);
});
});
describe('#dispose()', () => {
it('should dispose of the resources used by the drive', () => {
expect(drive.isDisposed).to.be(false);
drive.dispose();
expect(drive.isDisposed).to.be(true);
drive.dispose();
expect(drive.isDisposed).to.be(true);
});
});
describe('#getDownloadUrl()', () => {
let contents: Contents.IModel;
before(async () => {
let id = UUID.uuid4();
contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
await drive.save(contents.path, contents);
});
after(async () => {
await drive.delete(contents.path);
});
it('should get the url of a file', async () => {
const url = await drive.getDownloadUrl(contents.path);
expect(url.length > 0).to.be(true);
});
it('should not handle relative paths', async () => {
let url = drive.getDownloadUrl('My Drive/../' + contents.path);
await expectFailure(url);
});
});
describe('#newUntitled()', () => {
it('should create a file', async () => {
const model = await drive.newUntitled({
path: DEFAULT_DIRECTORY.path,
type: 'file',
ext: 'test'
});
expect(model.path).to.be(DEFAULT_DIRECTORY.path + '/' + model.name);
expect(model.name.indexOf('untitled') === -1).to.be(false);
expect(model.name.indexOf('test') === -1).to.be(false);
await drive.delete(model.path);
});
it('should create a directory', async () => {
let options: Contents.ICreateOptions = {
path: DEFAULT_DIRECTORY.path,
type: 'directory'
};
const model = await drive.newUntitled(options);
expect(model.path).to.be(DEFAULT_DIRECTORY.path + '/' + model.name);
expect(model.name.indexOf('Untitled Folder') === -1).to.be(false);
await drive.delete(model.path);
});
it('should emit the fileChanged signal', async () => {
let called = false;
const onFileChanged = (sender, args) => {
expect(args.type).to.be('new');
expect(args.oldValue).to.be(null);
expect(args.newValue.path).to.be(
DEFAULT_DIRECTORY.path + '/' + args.newValue.name
);
expect(args.newValue.name.indexOf('untitled') === -1).to.be(false);
expect(args.newValue.name.indexOf('test') === -1).to.be(false);
called = true;
};
drive.fileChanged.connect(onFileChanged);
const model = await drive.newUntitled({
type: 'file',
ext: 'test',
path: DEFAULT_DIRECTORY.path
});
drive.fileChanged.disconnect(onFileChanged);
await drive.delete(model.path);
expect(called).to.be(true);
});
});
describe('#delete()', () => {
it('should delete a file', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
const model = await drive.save(contents.path, contents);
await drive.delete(model.path);
});
it('should emit the fileChanged signal', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + String(id),
path: DEFAULT_TEXT_FILE.path + String(id)
};
const model = await drive.save(contents.path, contents);
drive.fileChanged.connect((sender, args) => {
expect(args.type).to.be('delete');
expect(args.oldValue.path).to.be(contents.path);
});
await drive.delete(contents.path);
});
});
describe('#rename()', () => {
it('should rename a file', async () => {
let id1 = UUID.uuid4();
let id2 = UUID.uuid4();
let path2 = DEFAULT_TEXT_FILE.path + id2;
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id1,
path: DEFAULT_TEXT_FILE.path + id1
};
await drive.save(contents.path, contents);
const model = await drive.rename(contents.path, path2);
expect(model.name).to.be(DEFAULT_TEXT_FILE.name + id2);
expect(model.path).to.be(path2);
expect(model.content).to.be(contents.content);
await drive.delete(model.path);
});
it('should emit the fileChanged signal', async () => {
let id1 = UUID.uuid4();
let id2 = UUID.uuid4();
let path2 = DEFAULT_TEXT_FILE.path + id2;
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id1,
path: DEFAULT_TEXT_FILE.path + id1
};
let called = false;
const onFileChanged = (sender, args) => {
expect(args.type).to.be('rename');
expect(args.oldValue.path).to.be(contents.path);
expect(args.newValue.path).to.be(path2);
called = true;
};
await drive.save(contents.path, contents);
drive.fileChanged.connect(onFileChanged);
const model = await drive.rename(contents.path, path2);
drive.fileChanged.disconnect(onFileChanged);
await drive.delete(model.path);
expect(called).to.be(true);
});
});
describe('#copy()', () => {
it('should copy a file', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
await drive.save(contents.path, contents);
const model = await drive.copy(contents.path, DEFAULT_DIRECTORY.path);
expect(model.name.indexOf(contents.name) === -1).to.be(false);
expect(model.name.indexOf('Copy') === -1).to.be(false);
expect(model.content).to.be(contents.content);
let first = drive.delete(contents.path);
let second = drive.delete(model.path);
await Promise.all([first, second]);
});
it('should emit the fileChanged signal', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
let called = false;
const onFileChanged = (sender, args) => {
expect(args.type).to.be('new');
expect(args.oldValue).to.be(null);
expect(args.newValue.content).to.be(contents.content);
expect(args.newValue.name.indexOf(contents.name) === -1).to.be(false);
expect(args.newValue.name.indexOf('Copy') === -1).to.be(false);
called = true;
};
await drive.save(contents.path, contents);
drive.fileChanged.connect(onFileChanged);
const model = await drive.copy(contents.path, DEFAULT_DIRECTORY.path);
drive.fileChanged.disconnect(onFileChanged);
let first = drive.delete(contents.path);
let second = drive.delete(model.path);
await Promise.all([first, second]);
expect(called).to.be(true);
});
});
describe('#createCheckpoint()', () => {
it('should create a checkpoint', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
await drive.save(contents.path, contents);
const cp = await drive.createCheckpoint(contents.path);
expect(cp.last_modified.length > 0).to.be(true);
expect(cp.id.length > 0).to.be(true);
await drive.delete(contents.path);
});
});
describe('#listCheckpoints()', () => {
it('should list the checkpoints', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
await drive.save(contents.path, contents);
const cp = await drive.createCheckpoint(contents.path);
const cps = await drive.listCheckpoints(contents.path);
expect(cps.filter(c => c.id === cp.id).length === 0).to.be(false);
await drive.delete(contents.path);
});
});
describe('#restoreCheckpoint()', () => {
it('should restore a text file from a checkpoint', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
let newContents = {
...contents,
content: 'This is some new text'
};
await drive.save(contents.path, contents);
const cp = await drive.createCheckpoint(contents.path);
const model = await drive.save(contents.path, newContents);
expect(model.content).to.be(newContents.content);
await drive.restoreCheckpoint(contents.path, cp.id);
const oldModel = await drive.get(contents.path);
expect(oldModel.content).to.be(contents.content);
await drive.delete(contents.path);
});
it('should restore a notebook from a checkpoint', async () => {
let id = UUID.uuid4();
// Note, include .ipynb to interpret the result as a notebook.
let contents = {
...DEFAULT_NOTEBOOK,
name: DEFAULT_NOTEBOOK.name + String(id) + '.ipynb',
path: DEFAULT_NOTEBOOK.path + String(id) + '.ipynb'
};
let newContents = {
...contents,
content: 'This is some new text'
};
await drive.save(contents.path, contents);
const cp = await drive.createCheckpoint(contents.path);
const model = await drive.save(contents.path, newContents);
expect(model.content).to.be(newContents.content);
await drive.restoreCheckpoint(contents.path, cp.id);
const oldModel = await drive.get(contents.path);
expect(JSONExt.deepEqual(oldModel.content, contents.content)).to.be(true);
await drive.delete(contents.path);
});
});
describe('#deleteCheckpoint()', () => {
it('should delete a checkpoint', async () => {
let id = UUID.uuid4();
let contents = {
...DEFAULT_TEXT_FILE,
name: DEFAULT_TEXT_FILE.name + id,
path: DEFAULT_TEXT_FILE.path + id
};
await drive.save(contents.path, contents);
const cp = await drive.createCheckpoint(contents.path);
await drive.deleteCheckpoint(contents.path, cp.id);
const cps = await drive.listCheckpoints(contents.path);
expect(cps.filter(c => c.id === cp.id).length === 0).to.be(true);
});
});
}); | the_stack |
import { PointerComponent } from './pointer'
import { renderAll } from '../render'
import {
getTime,
isSnapshot,
toTimeStamp,
base64ToFloat32Array,
delay,
AnimationFrame,
nodeStore,
encodeWAV
} from '@timecat/utils'
import { ProgressComponent } from './progress'
import { ContainerComponent } from './container'
import { RecordData, AudioData, SnapshotRecord, ReplayInternalOptions, ReplayData, VideoData } from '@timecat/share'
import { BroadcasterComponent } from './broadcaster'
import { PlayerEventTypes } from '../types'
import {
Component,
html,
Store,
PlayerReducerTypes,
ReplayDataReducerTypes,
ConnectProps,
observer,
transToReplayData,
normalLoading,
parseHtmlStr,
isMobile,
IComponent
} from '../utils'
@Component(
'timecat-player',
html`<div class="timecat-player">
<iframe
class="player-sandbox"
sandbox="allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox"
></iframe>
</div>`
)
export class PlayerComponent implements IComponent {
target: HTMLElement
parent: HTMLElement
options: ReplayInternalOptions
c: ContainerComponent
pointer: PointerComponent
progress: ProgressComponent
broadcaster: BroadcasterComponent
audioNode: HTMLAudioElement
records: RecordData[]
speed = 0
recordIndex = 0
frameIndex = 0
isFirstTimePlay = true
frameInterval: number
maxFrameInterval = 250
frames: number[]
maxFps = 30
initTime: number
startTime: number
animationDelayTime = 300
elapsedTime = 0
audioOffset = 150
curViewStartTime: number
curViewEndTime: number
curViewDiffTime = 0
preViewsDurationTime = 0
viewIndex = 0
viewsLength: number
subtitlesIndex = 0
audioData: AudioData
audioBlobUrl: string
videos: VideoData[]
RAF: AnimationFrame
isJumping: boolean
shouldWaitForSync: boolean
maxIntensityStep = 8
constructor(
options: ReplayInternalOptions,
c: ContainerComponent,
pointer: PointerComponent,
progress: ProgressComponent,
broadcaster: BroadcasterComponent
) {
this.options = options
this.c = c
this.pointer = pointer
this.progress = progress
this.broadcaster = broadcaster
this.init()
}
@ConnectProps(state => ({
speed: state.player.speed
}))
private watchPlayerSpeed(state?: { speed: number }) {
if (state) {
const speed = state.speed
const curSpeed = this.speed
this.speed = speed
observer.emit(PlayerEventTypes.SPEED, speed)
if (speed > 0) {
this.play()
if (curSpeed === 0) {
observer.emit(PlayerEventTypes.PLAY)
}
} else {
this.pause()
}
}
}
@ConnectProps(state => ({
endTime: state.progress.endTime
}))
private watchProgress() {
this.recalculateProgress()
this.viewsLength = Store.getState().replayData.packs.length
}
private watcherProgressJump() {
observer.on(PlayerEventTypes.JUMP, async (state: { index: number; time: number; percent?: number }) =>
this.jump(state, true)
)
}
private async init() {
this.audioNode = new Audio()
this.calcFrames()
this.viewsLength = Store.getState().replayData.packs.length
this.initViewState()
this.setViewState()
if (this.records.length <= 2) {
// is live mode
window.addEventListener('record-data', this.streamHandle.bind(this))
this.options.destroyStore.add(() => window.removeEventListener('record-data', this.streamHandle.bind(this)))
} else {
this.watchProgress()
this.watchPlayerSpeed()
this.watcherProgressJump()
}
observer.on(PlayerEventTypes.RESIZE, async () => {
// wait for scaling page finish to get target offsetWidth
await delay(500)
this.recalculateProgress()
})
observer.on(PlayerEventTypes.PROGRESS, (frame: number) => {
const percent = frame / (this.frames.length - 1)
this.progress.setProgressPosition(percent)
})
}
private initAudio() {
if (!this.audioData) {
return
}
if (this.audioData.src) {
this.audioBlobUrl = location.href.split('/').slice(0, -1).join('/') + '/' + this.audioData.src
} else {
const { wavStrList, pcmStrList } = this.audioData
let type: 'wav' | 'pcm' | undefined = undefined
const list: string[] = []
if (wavStrList.length) {
type = 'wav'
list.push(...wavStrList)
} else if (pcmStrList.length) {
type = 'pcm'
list.push(...pcmStrList)
}
if (!type) {
return
}
const dataArray: Float32Array[] = []
for (let i = 0; i < list.length; i++) {
const data = base64ToFloat32Array(list[i])
dataArray.push(data)
}
const audioBlob =
type === 'wav' ? new Blob(dataArray, { type: 'audio/wav' }) : encodeWAV(dataArray, this.audioData.opts)
const audioBlobUrl = URL.createObjectURL(audioBlob)
this.audioBlobUrl = audioBlobUrl
}
}
private mountVideos() {
if (!this.videos || !this.videos.length) {
return
}
this.videos.forEach(video => {
const { src, id } = video
const videoElement = nodeStore.getNode(id)
if (videoElement) {
const target = videoElement as HTMLVideoElement
target.muted = true
target.autoplay = target.loop = target.controls = false
target.src = src
}
})
}
private streamHandle(this: PlayerComponent, e: CustomEvent) {
const record = e.detail as RecordData
if (isSnapshot(record)) {
Store.getState().replayData.currentData.snapshot = record as SnapshotRecord
this.setViewState()
return
}
this.execFrame(record as RecordData)
}
private initViewState() {
const { currentData } = Store.getState().replayData
const { records, audio, videos, head } = currentData
this.records = this.processing(records)
this.audioData = audio
this.videos = videos
const { userAgent } = head?.data || {}
if (isMobile(userAgent as string)) {
this.pointer.hidePointer()
}
// live mode
if (!this.records.length) {
return
}
this.subtitlesIndex = 0
this.broadcaster.cleanText()
this.curViewStartTime = (head && head.time) || records[0].time
this.curViewEndTime = records.slice(-1)[0].time
this.preViewsDurationTime = 0
this.curViewDiffTime = 0
this.viewIndex = 0
}
private setViewState() {
this.c.setViewState()
this.initAudio()
this.mountVideos()
}
public async jump(state: { index: number; time: number; percent?: number }, shouldLoading = false) {
this.isJumping = true
this.shouldWaitForSync = true
let loading: HTMLElement | undefined = undefined
const { speed } = Store.getState().player
const { index, time, percent } = state
if (shouldLoading) {
this.pause(false)
loading = parseHtmlStr(normalLoading)[0]
this.c.container.appendChild(loading)
await delay(100)
}
const nextReplayData = this.getNextReplayData(index)
if (!nextReplayData) {
return
}
this.initViewState()
if (this.viewIndex !== index || this.startTime >= time) {
const [{ packsInfo }, { packs }] = [Store.getState().progress, Store.getState().replayData]
const diffTime = packsInfo[index].diffTime
this.curViewEndTime = packs[index].slice(-1)[0].time
this.curViewDiffTime = diffTime
this.preViewsDurationTime = packsInfo.slice(0, index).reduce((a, b) => a + b.duration, 0)
this.viewIndex = index
this.records = packs[index]
}
const frameIndex =
1 +
this.frames.findIndex((t, i) => {
const cur = t
const next = this.frames[i + 1] || cur + 1
if (time >= cur && time <= next) {
return true
}
})
this.frameIndex = frameIndex
this.initTime = getTime()
this.recordIndex = 0
this.audioData = nextReplayData.audio
this.startTime = time
this.subtitlesIndex = 0
if (percent !== undefined) {
this.progress.moveThumb(percent)
await delay(100)
}
this.setViewState()
this.playAudio()
this.loopFramesByTime(this.frames[this.frameIndex])
if (loading) {
await delay(100)
this.c.container.removeChild(loading)
Store.dispatch({ type: PlayerReducerTypes.SPEED, data: { speed } })
}
this.isJumping = false
setTimeout(() => (this.shouldWaitForSync = false), 100)
}
private getNextReplayData(index: number): ReplayData | null {
const { packs } = Store.getState().replayData
const nextPack = packs[index]
if (nextPack) {
const nextData = transToReplayData(nextPack)
Store.dispatch({ type: ReplayDataReducerTypes.UPDATE_DATA, data: { currentData: nextData } })
return nextData
}
return null
}
private loopFramesByTime(currTime: number, isJumping = false) {
let nextTime = this.frames[this.frameIndex]
while (nextTime && currTime >= nextTime) {
if (!isJumping) {
observer.emit(PlayerEventTypes.PROGRESS, this.frameIndex, this.frames.length - 1)
}
this.frameIndex++
this.renderEachFrame()
nextTime = this.frames[this.frameIndex]
}
return nextTime
}
private play() {
if (this.frameIndex === 0) {
this.progress.moveThumb()
if (!this.isFirstTimePlay) {
this.getNextReplayData(0)
this.initViewState()
this.setViewState()
} else {
this.progress.drawHeatPoints()
}
}
this.playAudio()
this.isFirstTimePlay = false
if (this.RAF && this.RAF.requestID) {
this.RAF.stop()
}
this.RAF = new AnimationFrame(loop.bind(this), this.maxFps)
this.options.destroyStore.add(() => this.RAF.stop())
this.RAF.start()
this.initTime = getTime()
this.startTime = this.frames[this.frameIndex]
async function loop(this: PlayerComponent, t: number, loopIndex: number) {
const timeStamp = getTime() - this.initTime
if (this.frameIndex > 0 && this.frameIndex >= this.frames.length) {
this.stop()
return
}
const currTime = this.startTime + timeStamp * this.speed
const nextTime = this.loopFramesByTime(currTime)
if (nextTime > this.curViewEndTime - this.curViewDiffTime && this.viewIndex < this.viewsLength - 1) {
const { packsInfo } = Store.getState().progress
const index = this.viewIndex + 1
const { startTime, diffTime } = packsInfo[index]
this.jump({ index: index, time: startTime - diffTime })
}
this.elapsedTime = (currTime - this.frames[0]) / 1000
this.syncAudio()
this.syncVideos()
}
}
private playAudio() {
if (!this.audioData) {
return
}
if (!this.audioBlobUrl) {
this.pauseAudio()
return
}
if (this.audioNode) {
if (!this.audioNode.src || this.audioNode.src !== this.audioBlobUrl) {
this.audioNode.src = this.audioBlobUrl
}
this.syncAudioTargetNode()
if (this.speed > 0) {
this.audioNode.play()
}
}
}
private syncAudio() {
if (!this.audioNode) {
return
}
const targetCurrentTime = this.audioNode.currentTime
const targetExpectTime = this.elapsedTime - this.preViewsDurationTime / 1000
const diffTime = Math.abs(targetExpectTime - targetCurrentTime)
const allowDiff = (100 + this.audioOffset) / 1000
if (diffTime > allowDiff) {
this.syncAudioTargetNode()
}
}
private syncAudioTargetNode() {
const elapsedTime = this.elapsedTime - this.preViewsDurationTime / 1000
const offset = this.audioOffset / 1000
this.audioNode.currentTime = elapsedTime + offset
}
private syncVideos() {
const initTime = this.curViewStartTime
const currentTime = initTime + (this.elapsedTime * 1000 - this.preViewsDurationTime)
const allowDiff = 100
this.videos.forEach(video => {
const { startTime, endTime, id } = video
const target = nodeStore.getNode(id) as HTMLVideoElement
if (!target) {
return
}
if (currentTime >= startTime && currentTime < endTime) {
if (target.paused && this.speed > 0) {
target.play()
}
const targetCurrentTime = target.currentTime
const targetExpectTime =
this.elapsedTime - this.preViewsDurationTime / 1000 - (startTime - initTime) / 1000
const diffTime = Math.abs(targetExpectTime - targetCurrentTime)
if (diffTime > allowDiff / 1000) {
target.currentTime = targetExpectTime
}
} else {
if (!target.paused) {
target.pause()
}
}
})
}
private pauseAudio() {
if (this.audioNode) {
this.audioNode.pause()
}
}
private pauseVideos() {
if (this.videos && this.videos.length) {
this.videos.forEach(video => {
const target = nodeStore.getNode(video.id) as HTMLVideoElement | undefined
if (target) {
target.pause()
}
})
}
}
private renderEachFrame() {
this.progress.updateTimer(this.frameIndex, this.frameInterval, this.curViewDiffTime)
let data: RecordData
while (
this.recordIndex < this.records.length &&
(data = this.records[this.recordIndex]).time - this.curViewDiffTime <= this.frames[this.frameIndex]
) {
this.execFrame(data)
this.recordIndex++
}
this.syncSubtitles()
}
private async syncSubtitles() {
if (this.shouldWaitForSync) {
return
}
if (this.audioData && this.audioData.subtitles.length) {
const subtitles = this.audioData.subtitles
let { text } = subtitles[this.subtitlesIndex]
const { end } = subtitles[this.subtitlesIndex]
const audioEndTime = toTimeStamp(end)
if (this.elapsedTime > audioEndTime / 1000) {
this.broadcaster.cleanText()
if (this.subtitlesIndex < subtitles.length - 1) {
while (true) {
const nextEndTime = toTimeStamp(subtitles[this.subtitlesIndex].end)
if (nextEndTime / 1000 > this.elapsedTime) {
break
}
this.subtitlesIndex++
}
text = subtitles[this.subtitlesIndex].text
}
}
this.broadcaster.updateText(text)
}
}
public pause(emit = true) {
if (this.RAF) {
this.RAF.stop()
}
Store.dispatch({
type: PlayerReducerTypes.SPEED,
data: {
speed: 0
}
})
this.pauseAudio()
this.pauseVideos()
if (emit) {
observer.emit(PlayerEventTypes.PAUSE)
}
}
private stop() {
this.speed = 0
this.recordIndex = 0
this.frameIndex = 0
this.elapsedTime = 0 // unit: sec
this.pause()
this.audioNode.currentTime = 0
observer.emit(PlayerEventTypes.STOP)
}
private execFrame(record: RecordData) {
const { isJumping, speed } = this
renderAll.call(this, record, { isJumping, speed })
}
private calcFrames(maxInterval = this.maxFrameInterval) {
if (this.options.mode === 'live') {
return []
}
const preTime = this.frames && this.frames[this.frameIndex]
const { duration, startTime, endTime } = Store.getState().progress
this.frameInterval = Math.max(20, Math.min(maxInterval, (duration / 60 / 1000) * 60 - 40))
const interval = this.frameInterval
const frames: number[] = []
let nextFrameIndex: number | undefined
for (let i = startTime; i < endTime + interval; i += interval) {
frames.push(i)
if (!nextFrameIndex && preTime && i >= preTime) {
nextFrameIndex = frames.length - 1
}
}
frames.push(endTime)
if (nextFrameIndex) {
this.frameIndex = nextFrameIndex!
}
this.frames = frames
}
private calcHeatPointsData() {
const frames = this.frames
if (!frames?.length || !this.options.heatPoints) {
return []
}
const state = Store.getState()
const { packs } = state.replayData
const { duration } = state.progress
const sliderWidth = this.progress.slider.offsetWidth
const column = Math.floor(sliderWidth / 7)
const gap = duration / column
const heatPoints = packs.reduce((acc, records) => {
let index = 0
let step = 0
let snapshot = false
const endTime = records.slice(-1)[0].time
let currentTime = records[0].time
while (currentTime < endTime && index < records.length) {
const nextTime = currentTime + gap
const record = records[index]
if (record.time < nextTime) {
index++
step++
if (isSnapshot(record)) {
snapshot = true
}
continue
}
acc.push({ step, snapshot })
step = 0
snapshot = false
currentTime += gap
}
return acc
}, [] as { step: number; snapshot: boolean }[])
return heatPoints
}
private orderRecords(records: RecordData[]) {
if (!records.length) {
return []
}
records.sort((a: RecordData, b: RecordData) => {
return a.time - b.time
})
return records
}
private recalculateProgress() {
this.calcFrames()
this.progress.drawHeatPoints(this.calcHeatPointsData())
}
private processing(records: RecordData[]) {
return this.orderRecords(records)
}
} | the_stack |
import BigNumber from "bignumber.js";
import { decimalStr, MAX_UINT256, mweiStr } from '../utils/Converter';
import { logGas } from '../utils/Log';
import { ProxyContext, getProxyContext } from '../utils/ProxyContextV2';
import { assert } from 'chai';
import * as contracts from '../utils/Contracts';
import { Contract } from 'web3-eth-contract';
let lp: string;
let project: string;
let trader: string;
let config = {
lpFeeRate: decimalStr("0.003"),
k: decimalStr("0.1"),
i: decimalStr("1"),
};
async function init(ctx: ProxyContext): Promise<void> {
lp = ctx.SpareAccounts[0];
project = ctx.SpareAccounts[1];
trader = ctx.SpareAccounts[2];
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000000"));
await ctx.mintTestToken(project, ctx.DODO, decimalStr("1000000"));
await ctx.mintTestToken(lp, ctx.USDT, mweiStr("1000000"));
await ctx.mintTestToken(project, ctx.USDT, mweiStr("1000000"));
await ctx.mintTestToken(lp, ctx.USDC, mweiStr("1000000"));
await ctx.mintTestToken(project, ctx.USDC, mweiStr("1000000"));
await ctx.approveProxy(lp);
await ctx.approveProxy(project);
await ctx.approveProxy(trader);
}
async function initCreateDVM(ctx: ProxyContext, token0: string, token1: string, token0Amount: string, token1Amount: string, ethValue: string, i: string): Promise<string> {
let PROXY = ctx.DODOProxyV2;
await PROXY.methods.createDODOVendingMachine(
token0,
token1,
token0Amount,
token1Amount,
config.lpFeeRate,
i,
config.k,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
).send(ctx.sendParam(project, ethValue));
if (token0 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token0 = ctx.WETH.options.address;
if (token1 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token1 = ctx.WETH.options.address;
var addr = await ctx.DVMFactory.methods._REGISTRY_(token0, token1, 0).call();
return addr;
}
describe("DODOProxyV2.0", () => {
let snapshotId: string;
let ctx: ProxyContext;
let dvm_DODO_USDT: string;
let dvm_USDT_USDC: string;
let dvm_WETH_USDT: string;
let dvm_WETH_USDC: string;
let DVM_DODO_USDT: Contract;
let DVM_USDT_USDC: Contract;
let DVM_WETH_USDT: Contract;
let DVM_WETH_USDC: Contract;
before(async () => {
let ETH = await contracts.newContract(
contracts.WETH_CONTRACT_NAME
);
ctx = await getProxyContext(ETH.options.address);
await init(ctx);
dvm_DODO_USDT = await initCreateDVM(ctx, ctx.DODO.options.address, ctx.USDT.options.address, decimalStr("100000"), mweiStr("20000"), "0", mweiStr("0.2"));
DVM_DODO_USDT = contracts.getContractWithAddress(contracts.DVM_NAME, dvm_DODO_USDT);
dvm_USDT_USDC = await initCreateDVM(ctx, ctx.USDT.options.address, ctx.USDC.options.address, mweiStr("100000"), mweiStr("1000"), "0", decimalStr("1"));
DVM_USDT_USDC = contracts.getContractWithAddress(contracts.DVM_NAME, dvm_USDT_USDC);
dvm_WETH_USDT = await initCreateDVM(ctx, '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', ctx.USDT.options.address, decimalStr("5"), mweiStr("3000"), "5", mweiStr("600"));
DVM_WETH_USDT = contracts.getContractWithAddress(contracts.DVM_NAME, dvm_WETH_USDT);
dvm_WETH_USDC = await initCreateDVM(ctx, '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', ctx.USDC.options.address, decimalStr("5"), mweiStr("3000"), "5", mweiStr("600"));
DVM_WETH_USDC = contracts.getContractWithAddress(contracts.DVM_NAME, dvm_WETH_USDC);
console.log("dvm_DODO_USDT:", dvm_DODO_USDT);
console.log("dvm_USDT_USDC:", dvm_USDT_USDC);
console.log("dvm_WETH_USDT:", dvm_WETH_USDT);
console.log("dvm_WETH_USDC:", dvm_WETH_USDC);
});
beforeEach(async () => {
snapshotId = await ctx.EVM.snapshot();
});
afterEach(async () => {
await ctx.EVM.reset(snapshotId);
});
describe("DODOProxy", () => {
it("createDVM", async () => {
var baseToken = ctx.DODO.options.address;
var quoteToken = ctx.USDT.options.address;
var baseAmount = decimalStr("10000");
var quoteAmount = mweiStr("10000");
await logGas(await ctx.DODOProxyV2.methods.createDODOVendingMachine(
baseToken,
quoteToken,
baseAmount,
quoteAmount,
config.lpFeeRate,
config.i,
config.k,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(project), "createDVM");
var addrs = await ctx.DVMFactory.methods.getDODOPool(baseToken, quoteToken).call();
assert.equal(
await ctx.DODO.methods.balanceOf(addrs[1]).call(),
baseAmount
);
assert.equal(
await ctx.USDT.methods.balanceOf(addrs[1]).call(),
quoteAmount
);
});
it("createDVM - ETH", async () => {
var baseToken = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
var quoteToken = ctx.USDT.options.address;
var baseAmount = decimalStr("5");
var quoteAmount = mweiStr("10000");
await logGas(await ctx.DODOProxyV2.methods.createDODOVendingMachine(
baseToken,
quoteToken,
baseAmount,
quoteAmount,
config.lpFeeRate,
config.i,
config.k,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(project, '5'), "createDVM - Wrap ETH");
var addrs = await ctx.DVMFactory.methods.getDODOPool(ctx.WETH.options.address, quoteToken).call();
assert.equal(
await ctx.WETH.methods.balanceOf(addrs[1]).call(),
baseAmount
);
assert.equal(
await ctx.USDT.methods.balanceOf(addrs[1]).call(),
quoteAmount
);
});
it("addLiquidity", async () => {
var b_baseReserve = await DVM_DODO_USDT.methods._BASE_RESERVE_().call();
var b_quoteReserve = await DVM_DODO_USDT.methods._QUOTE_RESERVE_().call();
var b_dlp = await DVM_DODO_USDT.methods.balanceOf(lp).call();
assert.equal(b_baseReserve, decimalStr("100000"));
assert.equal(b_quoteReserve, mweiStr("20000"));
assert.equal(b_dlp, decimalStr("0"));
await logGas(await ctx.DODOProxyV2.methods.addDVMLiquidity(
dvm_DODO_USDT,
decimalStr("1000"),
mweiStr("300"),
decimalStr("0"),
mweiStr("0"),
0,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(lp), "addLiquidity");
var a_baseReserve = await DVM_DODO_USDT.methods._BASE_RESERVE_().call();
var a_quoteReserve = await DVM_DODO_USDT.methods._QUOTE_RESERVE_().call();
var a_dlp = await DVM_DODO_USDT.methods.balanceOf(lp).call();
assert.equal(a_baseReserve, decimalStr("101000"));
assert.equal(a_quoteReserve, mweiStr("20200"));
assert.equal(a_dlp, "1000000000000000000000");
});
it("addLiquidity - ETH", async () => {
var b_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var b_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var b_dlp = await DVM_WETH_USDT.methods.balanceOf(lp).call();
assert.equal(b_baseReserve, decimalStr("5"));
assert.equal(b_quoteReserve, mweiStr("3000"));
assert.equal(b_dlp, decimalStr("0"));
await logGas(await ctx.DODOProxyV2.methods.addDVMLiquidity(
dvm_WETH_USDT,
decimalStr("1"),
mweiStr("6000"),
decimalStr("0"),
mweiStr("0"),
1,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(lp, '1'), "addLiquidity - ETH");
var a_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var a_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var a_dlp = await DVM_WETH_USDT.methods.balanceOf(lp).call();
assert.equal(a_baseReserve, decimalStr("6"));
assert.equal(a_quoteReserve, mweiStr("3600"));
assert.equal(a_dlp, "1000000000000000000");
});
it("sellShares - ETH helper", async () => {
var b_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var b_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var b_dlp = await DVM_WETH_USDT.methods.balanceOf(project).call();
var b_WETH = await ctx.WETH.methods.balanceOf(project).call();
var b_USDT = await ctx.USDT.methods.balanceOf(project).call();
var b_ETH = await ctx.Web3.eth.getBalance(project);
// console.log("b_baseReserve:" + b_baseReserve + " b_quoteReserve:" + b_quoteReserve + " b_dlp:" + b_dlp + " b_WETH:" + b_WETH + " b_USDT:" + b_USDT + " b_ETH:" + b_ETH);
await logGas(await DVM_WETH_USDT.methods.sellShares(
decimalStr("1"),
ctx.DODOCalleeHelper.options.address,
decimalStr("0"),
mweiStr("0"),
'0x00',
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(project), "sellShares - ETH helper");
var a_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var a_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var a_dlp = await DVM_WETH_USDT.methods.balanceOf(project).call();
var a_WETH = await ctx.WETH.methods.balanceOf(project).call();
var a_USDT = await ctx.USDT.methods.balanceOf(project).call();
var a_ETH = await ctx.Web3.eth.getBalance(project);
// console.log("a_baseReserve:" + a_baseReserve + " a_quoteReserve:" + a_quoteReserve + " a_dlp:" + a_dlp + " a_WETH:" + a_WETH + " a_USDT:" + a_USDT + " a_ETH:" + a_ETH);
assert.equal(a_baseReserve, decimalStr("4"));
assert.equal(a_quoteReserve, mweiStr("2400"));
assert.equal(a_dlp, decimalStr("4"));
assert.equal(a_WETH, decimalStr("0"));
assert.equal(a_USDT, mweiStr("877600"));
assert.equal(new BigNumber(b_ETH).isGreaterThan(new BigNumber(a_ETH).minus(decimalStr("1"))), true);
})
it("sellShares - Without ETH helper", async () => {
var b_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var b_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var b_dlp = await DVM_WETH_USDT.methods.balanceOf(project).call();
var b_WETH = await ctx.WETH.methods.balanceOf(project).call();
var b_USDT = await ctx.USDT.methods.balanceOf(project).call();
var b_ETH = await ctx.Web3.eth.getBalance(project);
// console.log("b_baseReserve:" + b_baseReserve + " b_quoteReserve:" + b_quoteReserve + " b_dlp:" + b_dlp + " b_WETH:" + b_WETH + " b_USDT:" + b_USDT + " b_ETH:" + b_ETH);
await logGas(await DVM_WETH_USDT.methods.sellShares(
decimalStr("1"),
project,
decimalStr("0"),
mweiStr("0"),
'0x',
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(project), "sellShares - Without ETH helper");
var a_baseReserve = await DVM_WETH_USDT.methods._BASE_RESERVE_().call();
var a_quoteReserve = await DVM_WETH_USDT.methods._QUOTE_RESERVE_().call();
var a_dlp = await DVM_WETH_USDT.methods.balanceOf(project).call();
var a_WETH = await ctx.WETH.methods.balanceOf(project).call();
var a_USDT = await ctx.USDT.methods.balanceOf(project).call();
var a_ETH = await ctx.Web3.eth.getBalance(project);
// console.log("a_baseReserve:" + a_baseReserve + " a_quoteReserve:" + a_quoteReserve + " a_dlp:" + a_dlp + " a_WETH:" + a_WETH + " a_USDT:" + a_USDT + " a_ETH:" + a_ETH);
assert.equal(a_baseReserve, decimalStr("4"));
assert.equal(a_quoteReserve, mweiStr("2400"));
assert.equal(a_dlp, decimalStr("4"));
assert.equal(a_WETH, decimalStr("1"));
assert.equal(a_USDT, mweiStr("877600"));
})
it("swap - one jump", async () => {
await ctx.mintTestToken(trader, ctx.DODO, decimalStr("1000"));
var b_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var b_USDT = await ctx.USDT.methods.balanceOf(trader).call();
var dodoPairs = [
dvm_DODO_USDT
]
var directions = 0
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - one jump first");
var a_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var a_USDT = await ctx.USDT.methods.balanceOf(trader).call();
// console.log("b_DOOD:" + b_DOOD + " a_DODO:" + a_DOOD);
// console.log("b_USDT:" + b_USDT + " a_USDT:" + a_USDT);
assert.equal(a_DOOD, decimalStr("500"));
assert.equal(a_USDT, "126151370");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - one jump second");
});
it("swap - two jump", async () => {
await ctx.mintTestToken(trader, ctx.DODO, decimalStr("1000"));
var b_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var b_WETH = await ctx.WETH.methods.balanceOf(trader).call();
var dodoPairs = [
dvm_DODO_USDT,
dvm_WETH_USDT
]
var directions = 2
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.WETH.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - two jump first");
var a_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var a_WETH = await ctx.WETH.methods.balanceOf(trader).call();
// console.log("b_DOOD:" + b_DOOD + " a_DODO:" + a_DOOD);
// console.log("b_WETH:" + b_WETH + " a_WETH:" + a_WETH);
assert.equal(a_DOOD, decimalStr("500"));
assert.equal(a_WETH, "163816613646287588");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.WETH.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - two jump second");
});
it("swap - two jump - inETH", async () => {
var b_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var b_WETH = await ctx.WETH.methods.balanceOf(trader).call();
var b_ETH = await ctx.Web3.eth.getBalance(trader);
var dodoPairs = [
dvm_WETH_USDT,
dvm_DODO_USDT
]
var directions = 2
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2ETHToToken(
ctx.DODO.options.address,
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader, "1"), "swap - two jump - inETH - first");
var a_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var a_WETH = await ctx.WETH.methods.balanceOf(trader).call();
var a_ETH = await ctx.Web3.eth.getBalance(trader);
// console.log("b_DOOD:" + b_DOOD + " a_DODO:" + a_DOOD);
// console.log("b_WETH:" + b_WETH + " a_WETH:" + a_WETH);
// console.log("b_ETH:" + b_ETH + " a_ETH:" + a_ETH);
assert.equal(a_DOOD, "2814340111190341070680");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2ETHToToken(
ctx.DODO.options.address,
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader, "1"), "swap - two jump - inETH - second");
});
it("swap - two jump - outETH", async () => {
await ctx.mintTestToken(trader, ctx.DODO, decimalStr("2000"));
var dodoPairs = [
dvm_DODO_USDT,
dvm_WETH_USDT
]
var directions = 2
var tx = await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToETH(
ctx.DODO.options.address,
decimalStr("1000"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - two jump - outETH first");
var a_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
assert.equal(a_DOOD, decimalStr("1000"));
assert.equal(
tx.events['OrderHistory'].returnValues['returnAmount'],
"323865907568573497"
)
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToETH(
ctx.DODO.options.address,
decimalStr("1000"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - two jump - outETH second");
});
it("swap - three jump", async () => {
await ctx.mintTestToken(trader, ctx.DODO, decimalStr("1000"));
var dodoPairs = [
dvm_DODO_USDT,
dvm_USDT_USDC,
dvm_WETH_USDC
]
var directions = 4
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.WETH.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - three jump first");
var a_DOOD = await ctx.DODO.methods.balanceOf(trader).call();
var a_WETH = await ctx.WETH.methods.balanceOf(trader).call();
assert.equal(a_DOOD, decimalStr("500"));
assert.equal(a_WETH, "163633965833613187");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.WETH.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap - three jump second");
});
});
}); | the_stack |
import { Optional, Autowired, Injectable, Injector, INJECTOR_TOKEN } from '@opensumi/di';
import {
IContextKey,
Event,
IContextKeyService,
ContextKeyChangeEvent,
getDebugLogger,
Emitter,
IScopedContextKeyService,
PreferenceService,
PreferenceChanges,
PreferenceScope,
PreferenceSchemaProvider,
createPreferenceProxy,
} from '@opensumi/ide-core-browser';
import { Disposable, ILogger } from '@opensumi/ide-core-common';
import { IWorkspaceService } from '@opensumi/ide-workspace';
import { Emitter as EventEmitter } from '@opensumi/monaco-editor-core/esm/vs/base/common/event';
import { StaticServices } from '@opensumi/monaco-editor-core/esm/vs/editor/standalone/browser/standaloneServices';
import {
ConfigurationTarget,
IConfigurationChangeEvent,
IConfigurationService,
IConfigurationOverrides,
IConfigurationData,
IConfigurationValue,
} from '@opensumi/monaco-editor-core/esm/vs/platform/configuration/common/configuration';
import { ContextKeyService } from '@opensumi/monaco-editor-core/esm/vs/platform/contextkey/browser/contextKeyService';
import {
ContextKeyExpression,
IContextKeyServiceTarget,
ContextKeyExpr,
} from '@opensumi/monaco-editor-core/esm/vs/platform/contextkey/common/contextkey';
import { KeybindingResolver } from '@opensumi/monaco-editor-core/esm/vs/platform/keybinding/common/keybindingResolver';
import { IWorkspaceFolder } from '@opensumi/monaco-editor-core/esm/vs/platform/workspace/common/workspace';
// 新版本这个 magic string 没有导出了
const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';
@Injectable()
export class ConfigurationService extends Disposable implements IConfigurationService {
@Autowired(PreferenceService)
private readonly preferenceService: PreferenceService;
@Autowired(PreferenceSchemaProvider)
private readonly preferenceSchemaProvider: PreferenceSchemaProvider;
@Autowired(IWorkspaceService)
private readonly workspaceService: IWorkspaceService;
@Autowired(ILogger)
private readonly logger: ILogger;
private readonly _onDidChangeConfiguration = new EventEmitter<IConfigurationChangeEvent>();
public readonly onDidChangeConfiguration = this._onDidChangeConfiguration.event;
public _serviceBrand: undefined;
constructor() {
super();
this.preferenceService.onPreferencesChanged(this.triggerPreferencesChanged, this, this.disposables);
const monacoConfigService = StaticServices.configurationService.get();
monacoConfigService.getValue = this.getValue.bind(this);
}
public keys() {
this.logger.error('MonacoConfigurationService#keys not implement');
return {
default: [],
user: [],
workspace: [],
workspaceFolder: [],
memory: [],
};
}
// hack duck types for ContextKeyService
// https://github.com/microsoft/vscode/blob/master/src/vs/platform/configuration/common/configuration.ts
protected triggerPreferencesChanged(changesToEmit: PreferenceChanges) {
const changes = Object.values(changesToEmit);
const defaultScopeChanges = changes.filter((change) => change.scope === PreferenceScope.Default);
const userScopeChanges = changes.filter((change) => change.scope === PreferenceScope.User);
const workspaceScopeChanges = changes.filter((change) => change.scope === PreferenceScope.Workspace);
const workspaceFolderScopeChanges = changes.filter((change) => change.scope === PreferenceScope.Folder);
// 在 monaco-editor 内部,default scope 变化时需要刷新内置所有的 config 打头的对应的值
if (defaultScopeChanges.length) {
this._onDidChangeConfiguration.fire({
affectedKeys: defaultScopeChanges.map((n) => n.preferenceName),
source: ConfigurationTarget.DEFAULT,
change: {
keys: [],
overrides: [],
},
// 判定配置是否生效
affectsConfiguration(configuration: string) {
return true;
},
sourceConfig: {},
});
}
if (userScopeChanges.length) {
this._onDidChangeConfiguration.fire({
affectedKeys: userScopeChanges.map((n) => n.preferenceName),
source: ConfigurationTarget.USER,
change: {
keys: [],
overrides: [],
},
affectsConfiguration(configuration: string) {
return true;
},
sourceConfig: {},
});
}
if (workspaceScopeChanges.length) {
this._onDidChangeConfiguration.fire({
affectedKeys: workspaceScopeChanges.map((n) => n.preferenceName),
source: ConfigurationTarget.WORKSPACE,
change: {
keys: [],
overrides: [],
},
affectsConfiguration(configuration: string) {
return true;
},
sourceConfig: {},
});
}
if (workspaceFolderScopeChanges.length) {
this._onDidChangeConfiguration.fire({
affectedKeys: workspaceFolderScopeChanges.map((n) => n.preferenceName),
source: this.workspaceService.isMultiRootWorkspaceOpened
? ConfigurationTarget.WORKSPACE_FOLDER
: ConfigurationTarget.WORKSPACE,
change: {
keys: [],
overrides: [],
},
affectsConfiguration(configuration: string) {
return true;
},
sourceConfig: {},
});
}
}
public getValue<T>(section?: string): T;
public getValue<T>(overrides: IConfigurationOverrides): T;
public getValue<T>(sectionOrOverrides?: string | IConfigurationOverrides, overrides?: IConfigurationOverrides): T {
let section;
if (typeof sectionOrOverrides !== 'string') {
overrides = sectionOrOverrides;
section = undefined;
} else {
section = sectionOrOverrides;
}
const overrideIdentifier =
(overrides && 'overrideIdentifier' in overrides && (overrides['overrideIdentifier'] as string)) || undefined;
const resourceUri =
overrides && 'resource' in overrides && !!overrides['resource'] && overrides['resource'].toString();
const proxy = createPreferenceProxy<{ [key: string]: any }>(
this.preferenceService,
this.preferenceSchemaProvider.getCombinedSchema(),
{
resourceUri: resourceUri || undefined,
overrideIdentifier,
style: 'both',
},
);
if (section) {
return proxy[section] as T;
}
return proxy as any;
}
public async updateValue(key: string, value: any): Promise<void>;
public async updateValue(
key: string,
value: any,
targetOrOverrides?: ConfigurationTarget | IConfigurationOverrides,
target?: ConfigurationTarget,
donotNotifyError?: boolean,
): Promise<void> {
let scope: PreferenceScope = PreferenceScope.Default;
if (typeof target === 'number') {
scope = this.getPreferenceScope(target);
} else if (typeof targetOrOverrides === 'number') {
scope = this.getPreferenceScope(targetOrOverrides);
}
const overrideIdentifier =
(typeof targetOrOverrides === 'object' &&
'overrideIdentifier' in targetOrOverrides &&
(targetOrOverrides['overrideIdentifier'] as string)) ||
undefined;
const resourceUri =
typeof targetOrOverrides === 'object' &&
'resource' in targetOrOverrides &&
!!targetOrOverrides['resource'] &&
targetOrOverrides['resource'].toString();
this.preferenceService.set(key, value, scope, resourceUri || '', overrideIdentifier);
}
public inspect<T>(key: string, overrides?: IConfigurationOverrides): IConfigurationValue<T> {
const overrideIdentifier =
(typeof overrides === 'object' &&
'overrideIdentifier' in overrides &&
(overrides['overrideIdentifier'] as string)) ||
undefined;
const resourceUri =
typeof overrides === 'object' &&
'resource' in overrides &&
!!overrides['resource'] &&
overrides['resource'].toString();
const value = this.preferenceService.inspect(key, resourceUri || '', overrideIdentifier);
const effectValue =
typeof value?.workspaceFolderValue !== 'undefined'
? value?.workspaceFolderValue
: typeof value?.workspaceValue !== 'undefined'
? value?.workspaceValue
: typeof value?.globalValue !== 'undefined'
? value?.globalValue
: typeof value?.defaultValue !== 'undefined'
? value?.defaultValue
: undefined;
return {
defaultValue: value?.defaultValue as T,
userValue: value?.globalValue as T,
userLocalValue: value?.globalValue as T,
userRemoteValue: value?.globalValue as T,
workspaceValue: value?.workspaceValue as T,
workspaceFolderValue: value?.workspaceFolderValue as T,
memoryValue: undefined,
value: effectValue as T,
default: {
value: value?.defaultValue as T,
override: overrideIdentifier ? (value?.defaultValue as T) : undefined,
},
user: {
value: value?.globalValue as T,
override: overrideIdentifier ? (value?.globalValue as T) : undefined,
},
userLocal: {
value: value?.globalValue as T,
override: overrideIdentifier ? (value?.globalValue as T) : undefined,
},
userRemote: {
value: value?.globalValue as T,
override: overrideIdentifier ? (value?.globalValue as T) : undefined,
},
workspace: {
value: value?.workspaceValue as T,
override: overrideIdentifier ? (value?.workspaceValue as T) : undefined,
},
workspaceFolder: {
value: value?.workspaceFolderValue as T,
override: overrideIdentifier ? (value?.workspaceFolderValue as T) : undefined,
},
overrideIdentifiers: overrideIdentifier ? [overrideIdentifier] : undefined,
};
}
public async reloadConfiguration(folder?: IWorkspaceFolder): Promise<void> {
throw new Error('MonacoContextKeyService#reloadConfiguration method not implement');
}
private getPreferenceScope(target: ConfigurationTarget) {
let scope: PreferenceScope;
if (target === ConfigurationTarget.DEFAULT) {
scope = PreferenceScope.Default;
} else if (
target === ConfigurationTarget.USER ||
target === ConfigurationTarget.USER_LOCAL ||
target === ConfigurationTarget.USER_REMOTE
) {
scope = PreferenceScope.User;
} else if (target === ConfigurationTarget.WORKSPACE) {
scope = PreferenceScope.Workspace;
} else if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
scope = PreferenceScope.Folder;
} else {
scope = PreferenceScope.Default;
}
return scope;
}
getConfigurationData(): IConfigurationData | null {
throw new Error('MonacoContextKeyService#getConfigurationData method not implement');
}
}
export function isContextKeyService(thing: any): thing is ContextKeyService {
return thing['_myContextId'] !== undefined;
}
@Injectable()
abstract class BaseContextKeyService extends Disposable implements IContextKeyService {
protected _onDidChangeContext = new Emitter<ContextKeyChangeEvent>();
readonly onDidChangeContext: Event<ContextKeyChangeEvent> = this._onDidChangeContext.event;
@Autowired(INJECTOR_TOKEN)
protected readonly injector: Injector;
public contextKeyService: ContextKeyService;
constructor() {
super();
}
listenToContextChanges() {
this.addDispose(
this.contextKeyService.onDidChangeContext((payload) => {
this._onDidChangeContext.fire(new ContextKeyChangeEvent(payload));
}),
);
}
createKey<T>(key: string, defaultValue: T | undefined): IContextKey<T> {
return this.contextKeyService.createKey(key, defaultValue);
}
getKeysInWhen(when: string | ContextKeyExpression | undefined) {
let expr: ContextKeyExpression | undefined;
if (typeof when === 'string') {
expr = this.parse(when);
}
return expr ? expr.keys() : [];
}
getContextValue<T>(key: string): T | undefined {
return this.contextKeyService.getContextKeyValue(key);
}
getValue<T>(key: string): T | undefined {
return this.contextKeyService.getContextKeyValue(key);
}
createScoped(target: IContextKeyServiceTarget | ContextKeyService): IScopedContextKeyService {
if (target && isContextKeyService(target)) {
return this.injector.get(ScopedContextKeyService, [target]);
} else {
// monaco 21 开始 domNode 变为必选
// https://github.com/microsoft/vscode/commit/c88888aa9bcc76b05779edb21c19eb8c7ebac787
const domNode = target || document.createElement('div');
const scopedContextKeyService = this.contextKeyService.createScoped(domNode as IContextKeyServiceTarget);
return this.injector.get(ScopedContextKeyService, [scopedContextKeyService as ContextKeyService]);
}
}
// cache expressions
protected expressions = new Map<string, ContextKeyExpression | undefined>();
parse(when: string | undefined): ContextKeyExpression | undefined {
if (!when) {
return undefined;
}
let expression = this.expressions.get(when);
if (!expression) {
const parsedExpr = ContextKeyExpr.deserialize(when) as unknown;
expression = parsedExpr ? (parsedExpr as ContextKeyExpression) : undefined;
this.expressions.set(when, expression);
}
return expression;
}
dispose() {
this.contextKeyService.dispose();
}
abstract match(expression: string | ContextKeyExpression, context?: HTMLElement | null): boolean;
}
@Injectable()
export class MonacoContextKeyService extends BaseContextKeyService implements IContextKeyService {
@Autowired(IConfigurationService)
protected readonly configurationService: IConfigurationService;
public readonly contextKeyService: ContextKeyService;
constructor() {
super();
this.contextKeyService = new ContextKeyService(this.configurationService);
this.listenToContextChanges();
}
match(expression: string | ContextKeyExpression | undefined, context?: HTMLElement): boolean {
try {
// keybinding 将 html target 传递过来完成激活区域的 context 获取和匹配
const ctx =
context || (window.document.activeElement instanceof HTMLElement ? window.document.activeElement : undefined);
let parsed: ContextKeyExpression | undefined;
if (typeof expression === 'string') {
parsed = this.parse(expression);
} else {
parsed = expression;
}
// 如果匹配表达式时没有传入合适的 DOM,则使用全局 ContextKeyService 进行表达式匹配
if (!ctx) {
return this.contextKeyService.contextMatchesRules(parsed as any);
}
// 自行指定 KeybindingResolver.contextMatchesRules 的 Context,来自于当前的激活元素的 Context
// 如果 ctx 为 null 则返回 0 (应该是根 contextKeyService 的 context_id 即为 global 的 ctx key service)
// 找到 ctx DOM 上的 context_id 属性 则直接返回
// 如果找不到 ctx DOM 上的 context_id 返回 NaN
// 如果遍历到父节点为 html 时,其 parentElement 为 null,也会返回 0
const keyContext = this.contextKeyService.getContext(ctx);
return KeybindingResolver.contextMatchesRules(keyContext, parsed as any);
} catch (e) {
getDebugLogger().error(e);
return false;
}
}
}
@Injectable({ multiple: true })
class ScopedContextKeyService extends BaseContextKeyService implements IScopedContextKeyService {
constructor(@Optional() public readonly contextKeyService: ContextKeyService) {
super();
this.listenToContextChanges();
}
match(expression: string | ContextKeyExpression | undefined): boolean {
try {
let parsed: ContextKeyExpression | undefined;
if (typeof expression === 'string') {
parsed = this.parse(expression);
} else {
parsed = expression;
}
// getType 的类型不兼容
return this.contextKeyService.contextMatchesRules(parsed as any);
} catch (e) {
getDebugLogger().error(e);
return false;
}
}
attachToDomNode(domNode: HTMLElement) {
// _domNode 存在于 ScopedContextKeyService 上
if (this.contextKeyService['_domNode']) {
this.contextKeyService['_domNode'].removeAttribute(KEYBINDING_CONTEXT_ATTR);
}
this.contextKeyService['_domNode'] = domNode;
this.contextKeyService['_domNode'].setAttribute(
KEYBINDING_CONTEXT_ATTR,
String(this.contextKeyService['_myContextId']),
);
}
} | the_stack |
import S3 from "aws-sdk/clients/s3";
import { SecretsManager, SharedIniFileCredentials } from "aws-sdk";
import { parameterStoreDeploymentKey, Region } from "./stack-constants";
import IAM from "aws-sdk/clients/iam";
import Route53Domains from "aws-sdk/clients/route53domains";
import ACM from "aws-sdk/clients/acm";
import SES from "aws-sdk/clients/ses";
import SSM from "aws-sdk/clients/ssm";
import { execSync } from "child_process";
import CF from "aws-sdk/clients/cloudformation";
import CodeBuild from "aws-sdk/clients/codebuild";
import { waitForEnterKeyPromise } from "./lib";
const {
// only available on aws
CODEBUILD_BUILD_ARN,
} = process.env;
export const preDeployValidations = async (params: {
profile?: string;
primaryRegion: string;
failoverRegion?: string;
domain: string;
customDomain: boolean;
verifiedSenderEmail: string;
}) => {
const {
profile,
primaryRegion,
failoverRegion,
domain,
customDomain,
verifiedSenderEmail,
} = params;
if (failoverRegion && failoverRegion == primaryRegion) {
throw new Error("Failover region can't be the same as primary region");
}
const awsAccountId = await getAwsAccountId(profile);
console.log(
`Using region ${primaryRegion} and failover region ${failoverRegion}.`
);
await validateSenderEmail(profile, primaryRegion, verifiedSenderEmail);
console.log(`Validated sender email allowed:\n ${verifiedSenderEmail}`);
if (customDomain) {
console.log("Skipping domain validation and user must setup DNS later");
} else {
await validateDomain(profile, domain);
console.log(`Validated domain:\n ${domain}`);
}
const certificateArn = await getAwsCertArnForDomain(
profile,
primaryRegion,
domain
);
console.log(`Using primary region certificate:\n ${certificateArn}`);
const failoverRegionCertificateArn = failoverRegion
? await getAwsCertArnForDomain(profile, failoverRegion, domain)
: undefined;
if (failoverRegionCertificateArn) {
console.log(
`Using failover region certificate:\n ${failoverRegionCertificateArn}`
);
}
return { awsAccountId, certificateArn, failoverRegionCertificateArn };
};
export const stackExists = async (
client: CF,
name: string
): Promise<boolean> => {
try {
const { Stacks } = await client
.describeStacks({
StackName: name,
})
.promise();
if (!Stacks) {
throw new Error("Error checking stack: " + name);
}
return Stacks[0].StackStatus == "CREATE_COMPLETE";
} catch (err) {
if (err.message.includes("does not exist")) {
return false;
}
throw err;
}
};
export const createBucketIfNeeded =
(s3Instance: S3) => async (name: string) => {
if (!(await doesBucketExist(s3Instance, name))) {
await s3Instance
.createBucket({
Bucket: name,
ACL: "private",
})
.promise();
}
await s3Instance
.putPublicAccessBlock({
Bucket: name,
PublicAccessBlockConfiguration: {
/* required */ BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true,
},
})
.promise();
};
const doesBucketExist = async (s3: S3, bucketName: string) => {
try {
await s3
.headBucket({
Bucket: bucketName,
})
.promise();
return true;
} catch (error) {
if (error.statusCode === 404) {
return false;
}
throw error;
}
};
export const getAwsAccountId = async (profile?: string) => {
if (CODEBUILD_BUILD_ARN) {
console.log("Using codebuild ARN for accountId", CODEBUILD_BUILD_ARN);
// cannot use getUser when running as a role in codebuild, and
// codebuild does not document exposing the account ID in its own var.
// arn format:
// `arn:aws:codebuild:region-ID:account-ID:build/codebuild-demo-project:b1e6661e-e4f2-4156-9ab9-82a19EXAMPLE`
const arnParts = CODEBUILD_BUILD_ARN.split(":");
return arnParts[4];
}
const credentials = profile
? new SharedIniFileCredentials({
profile,
})
: undefined;
const user = await new IAM({ credentials }).getUser().promise();
const awsAccountId = user.User.Arn.split("arn:aws:iam::")[1].split(
/:user|:root/
)[0] as string;
return awsAccountId;
};
export const validateDomain = async (
profile: string | undefined,
domain: string
) => {
const credentials = profile
? new SharedIniFileCredentials({
profile,
})
: undefined;
// only certain regions allow querying this endpint, but the domains are considered global
const allDomains = await new Route53Domains({
credentials,
region: "us-east-1",
})
.listDomains()
.promise();
const d = allDomains.Domains.find((d) => domain.includes(d.DomainName));
if (!d) {
throw new Error(
`AWS Route53 domain was not found for ${domain}. Did you mean to use an existing custom domain instead?`
);
}
};
export const getAwsCertArnForDomain = async (
profile: string | undefined,
region: string,
domain: string
) => {
const credentials = profile
? new SharedIniFileCredentials({
profile,
})
: undefined;
const allCerts = await new ACM({ credentials, region })
.listCertificates()
.promise();
const cert = allCerts?.CertificateSummaryList?.find((c) =>
[`*.${domain}`, domain].includes(c.DomainName!)
);
if (!cert || !cert.CertificateArn) {
throw new Error(
`AWS ACM is missing a certificate for ${domain} in region ${region}. Check the region for the certificate, if it was already created. Found ${
allCerts?.CertificateSummaryList?.length ?? 0
} certs. ${allCerts?.CertificateSummaryList?.map((c) => c.DomainName!)}`
);
}
return cert.CertificateArn;
};
export const validateSenderEmail = async (
profile: string | undefined,
region: string,
senderEmail: string
) => {
const senderDomain = senderEmail.split("@")[1];
if (!senderDomain) {
throw new Error("Unexpected email format!");
}
const credentials = profile
? new SharedIniFileCredentials({
profile,
})
: undefined;
const ses = new SES({ credentials, region });
const { Identities: identities } = await ses
.listIdentities({
MaxItems: 1000,
})
.promise();
const blurb = `The address ${senderEmail} must be verified with SES to continue. Email addresses are case sensitive.`;
if (!identities || !identities.length) {
throw new Error(
`No verified SES email sender identities were found for ${region}. ${blurb}`
);
}
const identity = identities.find((emailOrDomain) => {
const identityIsDomain = !emailOrDomain.includes("@");
if (identityIsDomain) {
return emailOrDomain === senderDomain;
}
return emailOrDomain === senderEmail;
});
if (!identity) {
throw new Error(
`${blurb} Found ${
identities.length
} other verified sender identities in ${region}: ${identities.join(", ")}`
);
}
// They added the email or domain.
// Is it verified?
const {
VerificationAttributes: { [identity]: identityVerification },
} = await ses
.getIdentityVerificationAttributes({
Identities: [identity],
})
.promise();
if (identityVerification.VerificationStatus !== "Success") {
throw new Error(
`Found SES sender identity, but it is not yet verified by AWS.`
);
}
// ok
};
// extracts cloudformation templates to a folder `templates` within `containingFolder`, overwriting
// templates if they existed
export const processTemplatesReturningFolder = async (
containingFolder: string,
zipFileName: string
) => {
const extractToFolder = `${containingFolder}/templates`;
console.log(" Extracting templates to:", extractToFolder);
execSync(`rm -rf ${extractToFolder}`);
execSync(`mkdir -p ${extractToFolder}`);
execSync(`unzip ${containingFolder}/${zipFileName} -d ${extractToFolder}`, {
cwd: process.cwd(),
});
return extractToFolder;
};
export const stackResult = async (
client: CF,
name: string,
allowRollbackOk?: boolean
) => {
while (true) {
const response = await client
.describeStacks({
StackName: name,
})
.promise();
const { Stacks } = response;
if (!Stacks) {
console.log("Error fetching stack results", response);
throw new Error("Error fetching stack status: " + name);
}
const status = Stacks[0].StackStatus;
switch (status) {
case "CREATE_COMPLETE":
case "UPDATE_COMPLETE":
case "DELETE_COMPLETE":
case "ROLLBACK_COMPLETE":
case "IMPORT_COMPLETE":
case "IMPORT_ROLLBACK_COMPLETE":
console.log("Stack task complete:\n ", status, name);
const outputs = Stacks[0].Outputs,
res: Record<string, string> = {};
if (outputs) {
for (let { OutputKey, OutputValue } of outputs) {
res[OutputKey!] = OutputValue!;
}
}
return res;
case "CREATE_IN_PROGRESS":
case "UPDATE_IN_PROGRESS":
case "UPDATE_ROLLBACK_COMPLETE":
case "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS":
case "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS":
case "DELETE_IN_PROGRESS":
// failures will trigger rollback straight away, rather than an error state
case allowRollbackOk ? "ROLLBACK_IN_PROGRESS" : "__Not_Allowed":
case "IMPORT_IN_PROGRESS":
case "IMPORT_ROLLBACK_IN_PROGRESS":
console.log(" ", status, name);
await new Promise((resolve) => setTimeout(resolve, 10000));
break;
default:
console.log("Error status:", response);
throw new Error("Error creating stack: " + name);
}
}
};
export const waitForBuild = async (codeBuild: CodeBuild, buildId: string) => {
while (true) {
const { builds } = await codeBuild
.batchGetBuilds({ ids: [buildId] })
.promise();
if (!builds) {
throw new Error(`Failed waiting for build ${buildId}!`);
}
if (!builds[0]) {
throw new Error(`Build ${buildId} not found!`);
}
const status = builds[0].buildStatus;
switch (status) {
case "IN_PROGRESS":
console.log(" ", status, "build", buildId);
await new Promise((resolve) => setTimeout(resolve, 10000));
break;
case "SUCCEEDED":
console.log(" ", status, "build", buildId);
return;
default:
throw new Error(`Build ${buildId} reached bad status ${status}`);
}
}
};
export const getLatestBuild = async (
codebuild: CodeBuild,
codebuildProjectName: string
): Promise<
| (Pick<CodeBuild.Build, "id" | "buildNumber" | "buildStatus"> & {
environmentVariables: CodeBuild.EnvironmentVariables;
})
| null
> => {
const { ids } = await codebuild
.listBuildsForProject({
projectName: codebuildProjectName,
sortOrder: "DESCENDING",
})
.promise();
const buildId = ids?.[0];
if (!buildId) {
return null;
}
const { builds } = await codebuild
.batchGetBuilds({ ids: [buildId] })
.promise();
const build = builds?.[0];
if (!build) {
return null;
}
const { id, buildStatus, buildNumber, environment } = build!;
const environmentVariables = environment!
.environmentVariables as CodeBuild.EnvironmentVariables;
return { id, buildStatus, buildNumber, environmentVariables };
};
export const dangerouslyDeleteS3BucketsWithConfirm = async (params: {
s3: S3;
all: boolean;
filterIgnore?: string;
filterInclude?: string;
dryRun?: boolean;
force?: boolean;
}) => {
const { s3, all, filterIgnore, filterInclude, dryRun, force } = params;
const { Buckets: allBuckets } = await s3.listBuckets().promise();
let filteredBuckets =
allBuckets?.filter((b) => b.Name?.includes("envkey-")) || [];
if (filterIgnore) {
filteredBuckets = filteredBuckets.filter(
(b) => !b.Name?.includes(filterIgnore)
);
} else if (filterInclude) {
filteredBuckets = filteredBuckets.filter((b) =>
b.Name?.includes(filterInclude)
);
}
if (!filteredBuckets.length) {
console.log(" No buckets found");
return;
}
console.log(" Buckets found:", filteredBuckets.length);
if (dryRun) {
console.log(" ", filteredBuckets.map((b) => b.Name).join("\n "));
return;
}
if (all && !force) {
console.log(filteredBuckets.map((b) => b.Name));
const res = await waitForEnterKeyPromise(
`\n Delete all ${filteredBuckets.length} envkey buckets!? Enter number of buckets: `
);
if (res !== filteredBuckets.length.toString()) {
console.log("Aborted!");
return;
}
}
for (const bucket of filteredBuckets) {
console.log("");
const name = bucket.Name!;
if (!force) {
const res = await waitForEnterKeyPromise(
`\n Delete bucket ${name} ?? [n/y] `
);
if (res !== "y") {
console.log(" Skipping bucket", name);
continue;
}
}
try {
let marker;
let objects: S3.ObjectList = [];
while (true) {
const { Contents, Marker } = await s3
.listObjects({
Bucket: name,
MaxKeys: 100,
})
.promise();
marker = Marker;
if (Contents) {
objects.push(...Contents);
}
if (!Contents?.length || !Marker) {
break;
}
}
console.log(" Emptying bucket:", name);
console.log(" Items:", objects?.length);
if (objects?.length) {
for (const o of objects) {
const { Versions } = await s3
.listObjectVersions({ Bucket: name, Prefix: o.Key! })
.promise();
if (Versions?.length) {
for (const v of Versions) {
try {
console.log(" Deleting version", o.Key, v.VersionId);
await s3
.deleteObject({
Bucket: name,
Key: o.Key!,
VersionId: v.VersionId,
})
.promise();
} catch (err) {
console.error(" ", err.message);
}
}
continue;
}
await s3.deleteObject({ Bucket: name, Key: o.Key! }).promise();
}
}
} catch (err) {
console.error(err.message);
console.error(" Delete objects problem.");
console.log(" Will try to delete bucket, still:", name);
}
console.log(" Deleting bucket:", name);
await s3.deleteBucket({ Bucket: name }).promise();
console.log(" Deleted bucket successfully:", name);
}
};
export const listCodebuildProjects = async (
codeBuild: CodeBuild,
deploymentTag: string
): Promise<string[]> => {
const tagProjects: string[] = [];
let nextToken: string | undefined;
while (true) {
const { projects, nextToken: nt } = await codeBuild
.listProjects(nextToken ? { nextToken } : {})
.promise();
nextToken = nt;
if (projects?.length) {
tagProjects.push(
...projects.filter(
(projectName) =>
projectName.includes("envkey") &&
projectName.includes(deploymentTag)
)
);
}
if (!nextToken || !projects?.length) {
break;
}
}
return tagProjects;
};
export const dangerouslyDeleteSecretsWithConfirm = async (params: {
secretsManager: SecretsManager;
all: boolean;
force?: boolean;
filterIgnore?: string;
filterInclude?: string;
dryRun?: boolean;
}) => {
const { secretsManager, all, force, filterIgnore, filterInclude, dryRun } =
params;
const { SecretList } = await secretsManager
.listSecrets({
MaxResults: 100,
Filters: [
{
Key: "name",
Values: ["envkey-"],
},
],
})
.promise();
let secrets = SecretList || [];
if (filterIgnore) {
secrets = secrets.filter((b) => !b.Name?.includes(filterIgnore));
} else if (filterInclude) {
secrets = secrets.filter((b) => b.Name?.includes(filterInclude));
}
if (!secrets.length) {
console.log("No secrets found");
return;
}
console.log("Secrets found:", secrets.length);
if (dryRun) {
console.log(" ", secrets.map((b) => b.Name).join("\n "));
return;
}
if (all && !force) {
console.log(secrets.map((s) => s.Name));
const res = await waitForEnterKeyPromise(
`\nDelete all ${secrets.length} envkey secrets!? Enter number of secrets: `
);
if (res !== secrets.length.toString()) {
console.log("Aborted!");
return;
}
}
for (const secret of secrets) {
console.log("");
const name = secret.Name;
if (!all) {
const res = await waitForEnterKeyPromise(
`\nDelete secret ${name}? [n/y] `
);
if (res !== "y") {
console.log("Skipping secret", name);
continue;
}
}
console.log(" Deleting secret:", name);
await secretsManager
.deleteSecret({ RecoveryWindowInDays: 7, SecretId: name! })
.promise();
console.log(" Deleted secret successfully:", name);
}
};
export const putDeployTag = async (params: {
profile: string | undefined;
primaryRegion: string;
deploymentTag: string;
}) => {
const credentials = params.profile
? new SharedIniFileCredentials({
profile: params.profile,
})
: undefined;
const ssm = new SSM({ region: params.primaryRegion, credentials });
const tags = [...(await listDeploymentTags(params)), params.deploymentTag];
await ssm
.putParameter({
Name: parameterStoreDeploymentKey,
Value: tags.join(","),
Type: "StringList",
Overwrite: true,
})
.promise();
return listDeploymentTags(params);
};
export const deleteDeployTag = async (params: {
profile: string | undefined;
primaryRegion: string;
deploymentTag: string;
}): Promise<string[]> => {
const credentials = params.profile
? new SharedIniFileCredentials({
profile: params.profile,
})
: undefined;
const ssm = new SSM({ region: params.primaryRegion, credentials });
const existing = await listDeploymentTags(params);
const tags = existing.filter((t) => t !== params.deploymentTag).join(",");
if (!tags.length) {
await ssm
.deleteParameter({
Name: parameterStoreDeploymentKey,
})
.promise();
} else {
await ssm
.putParameter({
Name: parameterStoreDeploymentKey,
Value: tags,
Type: "StringList",
Overwrite: true,
})
.promise();
}
return listDeploymentTags(params);
};
export const listDeploymentTags = async (params: {
profile: string | undefined;
primaryRegion: string;
}): Promise<string[]> => {
const credentials = params.profile
? new SharedIniFileCredentials({
profile: params.profile,
})
: undefined;
const ssm = new SSM({ region: params.primaryRegion, credentials });
const existing = await safeGetParameter(ssm, parameterStoreDeploymentKey);
if (existing) {
return existing.split(",");
}
return [];
};
export const safeGetParameter = async (
ssm: SSM,
paramName: string
): Promise<string | undefined> => {
try {
const param = (await ssm.getParameter({ Name: paramName }).promise())
?.Parameter?.Value;
return param;
} catch (err) {
if (err.code !== "ParameterNotFound") {
// this is how parameter store tells us the parameter does not exist
throw err;
}
}
return undefined;
}; | the_stack |
module BABYLON {
/**
* Class for the ObservableStringDictionary.onDictionaryChanged observable
*/
export class DictionaryChanged<T> {
/**
* Contain the action that were made on the dictionary, it's one of the DictionaryChanged.xxxAction members.
* Note the action's value can be used in the "mask" field of the Observable to only be notified about given action(s)
*/
public action: number;
/**
* Only valid if the action is newItemAction
*/
public newItem: { key: string, value: T }
/**
* Only valid if the action is removedItemAction
*/
public removedKey: string;
/**
* Only valid if the action is itemValueChangedAction
*/
public changedItem: { key: string, oldValue: T, newValue: T }
/**
* The content of the dictionary was totally cleared
*/
public static get clearAction() {
return DictionaryChanged._clearAction;
}
/**
* A new item was added, the newItem field contains the key/value pair
*/
public static get newItemAction() {
return DictionaryChanged._newItemAction;
}
/**
* An existing item was removed, the removedKey field contains its key
*/
public static get removedItemAction() {
return DictionaryChanged._removedItemAction;
}
/**
* An existing item had a value change, the changedItem field contains the key/value
*/
public static get itemValueChangedAction() {
return DictionaryChanged._itemValueChangedAction;
}
/**
* The dictionary's content was reset and replaced by the content of another dictionary.
* DictionaryChanged<T> contains no further information about this action
*/
public static get replacedAction() {
return DictionaryChanged._replacedAction;
}
private static _clearAction = 0x1;
private static _newItemAction = 0x2;
private static _removedItemAction = 0x4;
private static _itemValueChangedAction = 0x8;
private static _replacedAction = 0x10;
}
export class OSDWatchedObjectChangedInfo<T> {
key: string;
object: T;
propertyChanged: PropertyChangedInfo;
}
export class ObservableStringDictionary<T> extends StringDictionary<T> implements IPropertyChanged {
constructor(watchObjectsPropertyChange: boolean) {
super();
this._propertyChanged = null;
this._dictionaryChanged = null;
this.dci = new DictionaryChanged<T>();
this._callingDicChanged = false;
this._watchedObjectChanged = null;
this._callingWatchedObjectChanged = false;
this._woci = new OSDWatchedObjectChangedInfo<T>();
this._watchObjectsPropertyChange = watchObjectsPropertyChange;
this._watchedObjectList = this._watchObjectsPropertyChange ? new StringDictionary<Observer<PropertyChangedInfo>>() : null;
}
/**
* This will clear this dictionary and copy the content from the 'source' one.
* If the T value is a custom object, it won't be copied/cloned, the same object will be used
* @param source the dictionary to take the content from and copy to this dictionary
*/
public copyFrom(source: StringDictionary<T>) {
let oldCount = this.count;
// Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
super.clear();
source.forEach((t, v) => this._add(t, v, false, this._watchObjectsPropertyChange));
this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
this.onPropertyChanged("count", oldCount, this.count);
}
/**
* Get a value from its key or add it if it doesn't exist.
* This method will ensure you that a given key/data will be present in the dictionary.
* @param key the given key to get the matching value from
* @param factory the factory that will create the value if the key is not present in the dictionary.
* The factory will only be invoked if there's no data for the given key.
* @return the value corresponding to the key.
*/
public getOrAddWithFactory(key: string, factory: (key: string) => T): T {
let val = super.getOrAddWithFactory(key, k => {
let v = factory(key);
this._add(key, v, true, this._watchObjectsPropertyChange);
return v;
});
return val;
}
/**
* Add a new key and its corresponding value
* @param key the key to add
* @param value the value corresponding to the key
* @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
*/
public add(key: string, value: T): boolean {
return this._add(key, value, true, this._watchObjectsPropertyChange);
}
public getAndRemove(key: string): T {
let val = super.get(key);
this._remove(key, true, val);
return val;
}
private _add(key: string, value: T, fireNotif: boolean, registerWatcher: boolean): boolean {
if (super.add(key, value)) {
if (fireNotif) {
this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
this.onPropertyChanged("count", this.count - 1, this.count);
}
if (registerWatcher) {
this._addWatchedElement(key, value);
}
return true;
}
return false;
}
private _addWatchedElement(key: string, el: T) {
if (el["propertyChanged"]) {
this._watchedObjectList.add(key, (<IPropertyChanged><any>el).propertyChanged.add((e, d) => {
this.onWatchedObjectChanged(key, el, e);
}));
}
}
private _removeWatchedElement(key: string, el: T) {
let observer = this._watchedObjectList.getAndRemove(key);
if (el["propertyChanged"]) {
(<IPropertyChanged><any>el).propertyChanged.remove(observer);
}
}
public set(key: string, value: T): boolean {
let oldValue = this.get(key);
if (this._watchObjectsPropertyChange) {
this._removeWatchedElement(key, oldValue);
}
if (super.set(key, value)) {
this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
this._addWatchedElement(key, value);
return true;
}
return false;
}
/**
* Remove a key/value from the dictionary.
* @param key the key to remove
* @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
*/
public remove(key: string): boolean {
return this._remove(key, true);
}
private _remove(key: string, fireNotif: boolean, element?: T): boolean {
if (!element) {
element = this.get(key);
}
if (!element) {
return false;
}
if (super.remove(key) === undefined) {
return false;
}
this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
this.onPropertyChanged("count", this.count + 1, this.count);
if (this._watchObjectsPropertyChange) {
this._removeWatchedElement(key, element);
}
return true;
}
/**
* Clear the whole content of the dictionary
*/
public clear() {
if (this._watchedObjectList) {
this._watchedObjectList.forEach((k, v) => {
let el = this.get(k);
this._removeWatchedElement(k, el);
});
this._watchedObjectList.clear();
}
let oldCount = this.count;
super.clear();
this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
this.onPropertyChanged("count", oldCount, 0);
}
get propertyChanged(): Observable<PropertyChangedInfo> {
if (!this._propertyChanged) {
this._propertyChanged = new Observable<PropertyChangedInfo>();
}
return this._propertyChanged;
}
protected onPropertyChanged<T>(propName: string, oldValue: T, newValue: T, mask?: number) {
if (this._propertyChanged && this._propertyChanged.hasObservers()) {
let pci = ObservableStringDictionary.callingPropChanged ? new PropertyChangedInfo() : ObservableStringDictionary.pci;
pci.oldValue = oldValue;
pci.newValue = newValue;
pci.propertyName = propName;
try {
ObservableStringDictionary.callingPropChanged = true;
this.propertyChanged.notifyObservers(pci, mask);
} finally {
ObservableStringDictionary.callingPropChanged = false;
}
}
}
get dictionaryChanged(): Observable<DictionaryChanged<T>> {
if (!this._dictionaryChanged) {
this._dictionaryChanged = new Observable<DictionaryChanged<T>>();
}
return this._dictionaryChanged;
}
protected onDictionaryChanged(action: number, newItem: { key: string, value: T }, removedKey: string, changedItem: { key: string, oldValue: T, newValue: T }) {
if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
let dci = this._callingDicChanged ? new DictionaryChanged<T>() : this.dci;
dci.action = action;
dci.newItem = newItem;
dci.removedKey = removedKey;
dci.changedItem = changedItem;
try {
this._callingDicChanged = true;
this.dictionaryChanged.notifyObservers(dci, action);
} finally {
this._callingDicChanged = false;
}
}
}
get watchedObjectChanged(): Observable<OSDWatchedObjectChangedInfo<T>> {
if (!this._watchedObjectChanged) {
this._watchedObjectChanged = new Observable<OSDWatchedObjectChangedInfo<T>>();
}
return this._watchedObjectChanged;
}
protected onWatchedObjectChanged(key: string, object: T, propChanged: PropertyChangedInfo) {
if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
let woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo<T>() : this._woci;
woci.key = key;
woci.object = object;
woci.propertyChanged = propChanged;
try {
this._callingWatchedObjectChanged = true;
this.watchedObjectChanged.notifyObservers(woci);
} finally {
this._callingWatchedObjectChanged = false;
}
}
}
private _propertyChanged: Observable<PropertyChangedInfo>;
private static pci = new PropertyChangedInfo();
private static callingPropChanged: boolean = false;
private _dictionaryChanged: Observable<DictionaryChanged<T>>;
private dci: DictionaryChanged<T>;
private _callingDicChanged: boolean;
private _watchedObjectChanged: Observable<OSDWatchedObjectChangedInfo<T>>;
private _woci: OSDWatchedObjectChangedInfo<T>;
private _callingWatchedObjectChanged: boolean;
private _watchObjectsPropertyChange: boolean;
private _watchedObjectList: StringDictionary<Observer<PropertyChangedInfo>>;
}
} | the_stack |
import * as assert from "@esfx/internal-assert";
import { HashMap } from "@esfx/collections-hashmap";
import { Equaler } from "@esfx/equatable";
import { identity } from '@esfx/fn';
import { Grouping, HierarchyGrouping } from "@esfx/iter-grouping";
import { HierarchyIterable } from '@esfx/iter-hierarchy';
import { Page, HierarchyPage } from "@esfx/iter-page";
import { flowHierarchy } from './internal/utils';
class PageByIterable<T, R> implements Iterable<R> {
private _source: Iterable<T>;
private _pageSize: number;
private _pageSelector: (page: number, offset: number, values: Iterable<T>) => R;
constructor(source: Iterable<T>, pageSize: number, pageSelector: (page: number, offset: number, values: Iterable<T>) => R) {
this._source = source;
this._pageSize = pageSize;
this._pageSelector = pageSelector;
}
*[Symbol.iterator](): Iterator<R> {
const source = this._source;
const pageSize = this._pageSize;
const pageSelector = this._pageSelector;
let elements: T[] = [];
let page = 0;
for (const value of source) {
elements.push(value);
if (elements.length >= pageSize) {
yield pageSelector(page, page * pageSize, flowHierarchy(elements, source));
elements = [];
page++;
}
}
if (elements.length > 0) {
yield pageSelector(page, page * pageSize, flowHierarchy(elements, source));
}
}
}
/**
* Creates an `Iterable` that splits an `Iterable` into one or more pages.
* While advancing from page to page is evaluated lazily, the elements of the page are
* evaluated eagerly.
*
* @param source An `Iterable` object.
* @param pageSize The number of elements per page.
* @category Subquery
*/
export function pageBy<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>, pageSize: number): Iterable<HierarchyPage<TNode, T>>;
/**
* Creates an `Iterable` that splits an `Iterable` into one or more pages.
* While advancing from page to page is evaluated lazily, the elements of the page are
* evaluated eagerly.
*
* @param source An `Iterable` object.
* @param pageSize The number of elements per page.
* @param pageSelector A callback used to create a result for a page.
* @category Subquery
*/
export function pageBy<TNode, T extends TNode, R>(source: HierarchyIterable<TNode, T>, pageSize: number, pageSelector: (page: number, offset: number, values: HierarchyIterable<TNode, T>) => R): Iterable<R>;
/**
* Creates an `Iterable` that splits an `Iterable` into one or more pages.
* While advancing from page to page is evaluated lazily, the elements of the page are
* evaluated eagerly.
*
* @param source An `Iterable` object.
* @param pageSize The number of elements per page.
* @category Subquery
*/
export function pageBy<T>(source: Iterable<T>, pageSize: number): Iterable<Page<T>>;
/**
* Creates an `Iterable` that splits an `Iterable` into one or more pages.
* While advancing from page to page is evaluated lazily, the elements of the page are
* evaluated eagerly.
*
* @param source An `Iterable` object.
* @param pageSize The number of elements per page.
* @param pageSelector A callback used to create a result for a page.
* @category Subquery
*/
export function pageBy<T, R>(source: Iterable<T>, pageSize: number, pageSelector: (page: number, offset: number, values: Iterable<T>) => R): Iterable<R>;
export function pageBy<T, R>(source: Iterable<T>, pageSize: number, pageSelector: ((page: number, offset: number, values: Iterable<T>) => Page<T> | R) | ((page: number, offset: number, values: HierarchyIterable<unknown, T>) => Page<T> | R) = Page.from): Iterable<Page<T> | R> {
assert.mustBeIterableObject(source, "source");
assert.mustBePositiveNonZeroFiniteNumber(pageSize, "pageSize");
assert.mustBeFunction(pageSelector, "pageSelector");
return new PageByIterable(source, pageSize, pageSelector as (page: number, offset: number, values: Iterable<T>) => R);
}
class SpanMapIterable<T, K, V, R> implements Iterable<R> {
private _source: Iterable<T>;
private _keySelector: (element: T) => K;
private _keyEqualer: Equaler<K>;
private _elementSelector: (element: T) => V;
private _spanSelector: (key: K, elements: Iterable<T | V>) => R;
constructor(source: Iterable<T>, keySelector: (element: T) => K, keyEqualer: Equaler<K>, elementSelector: (element: T) => V, spanSelector: (key: K, elements: Iterable<T | V>) => R) {
this._source = source;
this._keySelector = keySelector;
this._keyEqualer = keyEqualer;
this._elementSelector = elementSelector;
this._spanSelector = spanSelector;
}
*[Symbol.iterator](): Iterator<R> {
const source = this._source;
const keySelector = this._keySelector;
const keyEqualer = this._keyEqualer;
const elementSelector = this._elementSelector;
const spanSelector = this._spanSelector;
let span: (T | V)[] | undefined;
let previousKey!: K;
for (const element of source) {
const key = keySelector(element);
if (!span) {
previousKey = key;
span = [];
}
else if (!keyEqualer.equals(previousKey, key)) {
yield spanSelector(previousKey, elementSelector === identity ? flowHierarchy(span, source as Iterable<T | V>) : span);
span = [];
previousKey = key;
}
span.push(elementSelector(element));
}
if (span) {
yield spanSelector(previousKey, elementSelector === identity ? flowHierarchy(span, source as Iterable<T | V>) : span);
}
}
}
/**
* Creates a subquery whose elements are the contiguous ranges of elements that share the same key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param keyEqualer An `Equaler` used to compare key equality.
* @category Grouping
*/
export function spanMap<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<HierarchyGrouping<K, TNode, T>>;
/**
* Creates a subquery whose elements are the contiguous ranges of elements that share the same key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param spanSelector A callback used to select a result from a contiguous range.
* @param keyEqualer An `Equaler` used to compare key equality.
* @category Grouping
*/
export function spanMap<TNode, T extends TNode, K, R>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, elementSelector: undefined, spanSelector: (key: K, elements: HierarchyIterable<TNode, T>) => R, keyEqualer?: Equaler<K>): Iterable<R>;
/**
* Creates a subquery whose elements are the contiguous ranges of elements that share the same key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param keyEqualer An `Equaler` used to compare key equality.
* @category Grouping
*/
export function spanMap<T, K>(source: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<Grouping<K, T>>;
/**
* Creates a subquery whose values are computed from each element of the contiguous ranges of elements that share the same key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param keyEqualer An `Equaler` used to compare key equality.
* @category Grouping
*/
export function spanMap<T, K, V>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): Iterable<Grouping<K, V>>;
/**
* Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param spanSelector A callback used to select a result from a contiguous range.
* @param keyEqualer An `Equaler` used to compare key equality.
* @category Grouping
*/
export function spanMap<T, K, V, R>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, spanSelector: (key: K, elements: Iterable<V>) => R, keyEqualer?: Equaler<K>): Iterable<R>;
export function spanMap<T, K, V, R>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: ((element: T) => T | V) | Equaler<K> = identity, spanSelector: ((key: K, span: Iterable<T | V>) => Grouping<K, T | V> | R) | ((key: K, span: HierarchyIterable<unknown, T>) => Grouping<K, T | V> | R) | Equaler<K> = Grouping.from, keyEqualer: Equaler<K> = Equaler.defaultEqualer) {
if (typeof elementSelector === "object") {
keyEqualer = elementSelector;
elementSelector = identity;
}
if (typeof spanSelector === "object") {
keyEqualer = spanSelector;
spanSelector = Grouping.from;
}
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeFunction(elementSelector, "elementSelector");
assert.mustBeFunction(spanSelector, "spanSelector");
assert.mustBeType(Equaler.hasInstance, keyEqualer, "keyEqualer");
return new SpanMapIterable(source, keySelector, keyEqualer, elementSelector, spanSelector as (key: K, span: Iterable<T | V>) => Grouping<K, T | V> | R);
}
function createGroupings<T, K, V>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): HashMap<K, V[]> {
const map = new HashMap<K, V[]>(keyEqualer);
for (const item of source) {
const key = keySelector(item);
const element = elementSelector(item);
const grouping = map.get(key);
if (grouping === undefined) {
map.set(key, [element]);
}
else {
grouping.push(element);
}
}
return map;
}
class GroupByIterable<T, K, V, R> implements Iterable<R> {
private _source: Iterable<T>;
private _keySelector: (element: T) => K;
private _elementSelector: (element: T) => T | V;
private _resultSelector: (key: K, elements: Iterable<T | V>) => R;
constructor(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, resultSelector: (key: K, elements: Iterable<T | V>) => R) {
this._source = source;
this._keySelector = keySelector;
this._elementSelector = elementSelector;
this._resultSelector = resultSelector;
}
*[Symbol.iterator](): Iterator<R> {
const source = this._source;
const elementSelector = this._elementSelector;
const resultSelector = this._resultSelector;
const map = createGroupings(source, this._keySelector, elementSelector);
for (const [key, values] of map) {
yield resultSelector(key, elementSelector === identity ? flowHierarchy(values, source as Iterable<T | V>) : values);
}
}
}
/**
* Groups each element of an `Iterable` by its key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function groupBy<TNode, T extends TNode, K>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<HierarchyGrouping<K, TNode, T>>;
/**
* Groups each element of an `Iterable` by its key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param resultSelector A callback used to select a result from a group.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function groupBy<TNode, T extends TNode, K, R>(source: HierarchyIterable<TNode, T>, keySelector: (element: T) => K, elementSelector: undefined, resultSelector: (key: K, elements: HierarchyIterable<TNode, T>) => R, keyEqualer?: Equaler<K>): Iterable<R>;
/**
* Groups each element of an `Iterable` by its key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function groupBy<T, K>(source: Iterable<T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Iterable<Grouping<K, T>>;
/**
* Groups each element of an `Iterable` by its key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function groupBy<T, K, V>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): Iterable<Grouping<K, V>>;
/**
* Groups each element of an `Iterable` by its key.
*
* @param source An `Iterable` object.
* @param keySelector A callback used to select the key for an element.
* @param elementSelector A callback used to select a value for an element.
* @param resultSelector A callback used to select a result from a group.
* @param keyEqualer An `Equaler` object used to compare key equality.
* @category Subquery
*/
export function groupBy<T, K, V, R>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => V, resultSelector: (key: K, elements: Iterable<V>) => R, keyEqualer?: Equaler<K>): Iterable<R>;
export function groupBy<T, K, V, R>(source: Iterable<T>, keySelector: (element: T) => K, elementSelector: ((element: T) => T | V) | Equaler<K> = identity, resultSelector: ((key: K, elements: Iterable<T | V>) => Grouping<K, T | V> | R) | ((key: K, elements: HierarchyIterable<unknown, T>) => Grouping<K, T | V> | R) | Equaler<K> = Grouping.from, keyEqualer?: Equaler<K>) {
if (typeof elementSelector !== "function") {
resultSelector = elementSelector;
elementSelector = identity;
}
if (typeof resultSelector !== "function") {
keyEqualer = resultSelector;
resultSelector = Grouping.from;
}
assert.mustBeIterableObject(source, "source");
assert.mustBeFunction(keySelector, "keySelector");
assert.mustBeFunction(elementSelector, "elementSelector");
assert.mustBeFunction(resultSelector, "resultSelector");
assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer");
return new GroupByIterable(source, keySelector, elementSelector, resultSelector as (key: K, elements: Iterable<T | V>) => Grouping<K, T | V> | R);
} | the_stack |
import * as Address from "../../../generated/joynr/system/RoutingTypes/Address";
import * as DiscoveryEntry from "../../../generated/joynr/types/DiscoveryEntry";
import * as DiscoveryEntryWithMetaInfo from "../../../generated/joynr/types/DiscoveryEntryWithMetaInfo";
/**
* The <code>CapabilityDiscovery</code> is a joynr internal interface. When the Arbitrator does a lookup for capabilities, this module is
* queried. If a provider needs to be registered, this module selects the places to register at.
*/
import GlobalDiscoveryEntry from "../../../generated/joynr/types/GlobalDiscoveryEntry";
import DiscoveryQos from "../../proxy/DiscoveryQos";
import DiscoveryQosGen from "../../../generated/joynr/types/DiscoveryQos";
import DiscoveryScope from "../../../generated/joynr/types/DiscoveryScope";
import ProviderScope from "../../../generated/joynr/types/ProviderScope";
import GlobalCapabilitiesDirectoryProxy from "../../../generated/joynr/infrastructure/GlobalCapabilitiesDirectoryProxy";
import * as Typing from "../../util/Typing";
import LoggingManager from "../../system/LoggingManager";
import * as UtilInternal from "../../util/UtilInternal";
import ProviderRuntimeException from "../../exceptions/ProviderRuntimeException";
import * as CapabilitiesUtil from "../../util/CapabilitiesUtil";
import { DiscoveryStub } from "../interface/DiscoveryStub";
import ProxyBuilder = require("../../proxy/ProxyBuilder");
import MessageRouter = require("../../messaging/routing/MessageRouter");
import CapabilitiesStore = require("../CapabilitiesStore");
import JoynrRuntimeException = require("../../exceptions/JoynrRuntimeException");
import DiscoveryError from "../../../generated/joynr/types/DiscoveryError";
import ApplicationException from "../../exceptions/ApplicationException";
const TTL_30DAYS_IN_MS = 30 * 24 * 60 * 60 * 1000;
const log = LoggingManager.getLogger("joynr/capabilities/discovery/CapabilityDiscovery");
interface QueuedGlobalDiscoveryEntires {
discoveryEntry: DiscoveryEntry;
gbids: string[];
resolve: (value: any) => void;
reject: (error: any) => void;
}
interface QueuedGlobalLookups {
domains: string[];
interfaceName: string;
ttl: number;
capabilities: any[];
gbids: string[];
resolve: (value: any) => void;
reject: (error: any) => void;
}
interface QueuedGlobalLookupsByParticipantId {
participantId: string;
ttl: number;
gbids: string[];
resolve: (value: any) => void;
reject: (error: any) => void;
}
class CapabilityDiscovery implements DiscoveryStub {
private globalCapabilitiesDomain: string;
private proxyBuilder!: ProxyBuilder;
private messageRouter!: MessageRouter;
private globalCapabilitiesCache: CapabilitiesStore;
private localCapabilitiesStore: CapabilitiesStore;
private queuedGlobalLookups: QueuedGlobalLookups[];
private queuedGlobalLookupsByParticipantId: QueuedGlobalLookupsByParticipantId[];
private queuedGlobalDiscoveryEntries: QueuedGlobalDiscoveryEntires[];
private globalAddressSerialized?: string;
private knownGbids: string[];
/**
* The CapabilitiesDiscovery looks up the local and global capabilities directory
*
* @constructor
*
* @param localCapabilitiesStore the local capabilities store
* @param globalCapabilitiesCache the cache for the global capabilities directory
* @param globalCapabilitiesDomain the domain to communicate with the GlobalCapablitiesDirectory
* GlobalCapab
* @param knownGbids known global backend identifiers provided by provisioning
*/
public constructor(
localCapabilitiesStore: CapabilitiesStore,
globalCapabilitiesCache: CapabilitiesStore,
globalCapabilitiesDomain: string,
knownGbids: string[]
) {
if (!knownGbids || knownGbids.length === 0) {
throw new JoynrRuntimeException({
detailMessage: `knownGbids needs the have a length of at least one ${knownGbids}`
});
}
this.queuedGlobalDiscoveryEntries = [];
this.queuedGlobalLookups = [];
this.queuedGlobalLookupsByParticipantId = [];
this.localCapabilitiesStore = localCapabilitiesStore;
this.globalCapabilitiesCache = globalCapabilitiesCache;
this.globalCapabilitiesDomain = globalCapabilitiesDomain;
this.knownGbids = knownGbids;
}
/**
* Set necessary dependencies
*
* @param messageRouter the message router
* @param proxyBuilder the proxy builder used to create the GlobalCapabilitiesDirectoryProxy
*/
public setDependencies(messageRouter: MessageRouter, proxyBuilder: ProxyBuilder): void {
this.messageRouter = messageRouter;
this.proxyBuilder = proxyBuilder;
}
/**
* This method create a new global capabilities proxy with the provided ttl as messaging QoS
*
* @param ttl time to live of joynr messages triggered by the returning proxy
*
* @returns the newly created proxy
*/
private getGlobalCapabilitiesDirectoryProxy(ttl: number): Promise<GlobalCapabilitiesDirectoryProxy> {
return this.proxyBuilder
.build(GlobalCapabilitiesDirectoryProxy, {
domain: this.globalCapabilitiesDomain,
messagingQos: {
ttl
},
discoveryQos: new DiscoveryQos({
discoveryScope: DiscoveryScope.GLOBAL_ONLY,
cacheMaxAgeMs: UtilInternal.getMaxLongValue()
})
})
.catch(error => {
throw new Error(`Failed to create global capabilities directory proxy: ${error}`);
});
}
private lookupGlobal(
domains: string[],
interfaceName: string,
ttl: number,
capabilities: DiscoveryEntryWithMetaInfo[],
gbids: string[]
): Promise<DiscoveryEntryWithMetaInfo[]> {
return this.getGlobalCapabilitiesDirectoryProxy(ttl)
.then(globalCapabilitiesDirectoryProxy =>
globalCapabilitiesDirectoryProxy.lookup({
domains,
interfaceName,
gbids
})
)
.then(opArgs => {
const messageRouterPromises = [];
const globalCapabilities = opArgs.result;
let globalAddress;
if (globalCapabilities === undefined) {
log.error("globalCapabilitiesDirectoryProxy.lookup() returns with missing result");
} else {
for (let i = globalCapabilities.length - 1; i >= 0; i--) {
const globalDiscoveryEntry = globalCapabilities[i];
if (globalDiscoveryEntry.address === this.globalAddressSerialized) {
globalCapabilities.splice(i, 1);
} else {
try {
globalAddress = Typing.augmentTypes(JSON.parse(globalDiscoveryEntry.address));
} catch (e) {
log.error(
`unable to use global discoveryEntry with unknown address type: ${
globalDiscoveryEntry.address
}`
);
continue;
}
// Update routing table
const isGloballyVisible = globalDiscoveryEntry.qos.scope === ProviderScope.GLOBAL;
messageRouterPromises.push(
this.messageRouter.addNextHop(
globalDiscoveryEntry.participantId,
globalAddress,
isGloballyVisible
)
);
capabilities.push(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, globalDiscoveryEntry)
);
}
}
}
return Promise.all(messageRouterPromises);
})
.then(() => capabilities);
}
/**
* expects a capabilities array which is then filled with any that are found from the proxy
*
* @param domains - the domains
* @param interfaceName - the interface name
* @param ttl - time to live of joynr messages triggered by the returning proxy
* @param capabilities - the capabilities array to be filled
* @param gbids - array of knownGbids in which to look for providers
*
* @returns - the capabilities array filled with the capabilities found in the global capabilities directory
*/
private lookupGlobalCapabilities(
domains: string[],
interfaceName: string,
ttl: number,
capabilities: any[],
gbids: string[]
): Promise<any[]> {
if (!this.globalAddressSerialized) {
const deferred = UtilInternal.createDeferred();
this.queuedGlobalLookups.push({
domains,
interfaceName,
ttl,
capabilities,
gbids,
resolve: deferred.resolve,
reject: deferred.reject
});
return deferred.promise;
} else {
return this.lookupGlobal(domains, interfaceName, ttl, capabilities, gbids);
}
}
private lookupGlobalByParticipantId(
participantId: string,
ttl: number,
gbids: string[]
): Promise<DiscoveryEntryWithMetaInfo> {
let result: DiscoveryEntryWithMetaInfo;
return this.getGlobalCapabilitiesDirectoryProxy(ttl)
.then(globalCapabilitiesDirectoryProxy =>
globalCapabilitiesDirectoryProxy.lookup({
participantId,
gbids
})
)
.then(opArgs => {
const messageRouterPromises = [];
const globalDiscoveryEntry = opArgs.result;
let globalAddress;
if (!globalDiscoveryEntry) {
log.error("globalCapabilitiesDirectoryProxy.lookup() returns with missing result");
return Promise.reject(
new ApplicationException({
detailMessage: "Got empty result from global lookup",
error: DiscoveryError.INTERNAL_ERROR
})
);
} else {
if (globalDiscoveryEntry.address !== this.globalAddressSerialized) {
try {
globalAddress = Typing.augmentTypes(JSON.parse(globalDiscoveryEntry.address));
} catch (e) {
log.error(
`unable to use global discoveryEntry with unknown address type: ${
globalDiscoveryEntry.address
}`
);
return Promise.reject(
new ApplicationException({
detailMessage: "The address could not be deserialized, see error log message",
error: DiscoveryError.INTERNAL_ERROR
})
);
}
// Update routing table
const isGloballyVisible = globalDiscoveryEntry.qos.scope === ProviderScope.GLOBAL;
messageRouterPromises.push(
this.messageRouter.addNextHop(
globalDiscoveryEntry.participantId,
globalAddress,
isGloballyVisible
)
);
}
result = CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, globalDiscoveryEntry);
}
return Promise.all(messageRouterPromises);
})
.then(() => result);
}
private lookupGlobalCapabilitiesByParticipantId(participantId: string, ttl: number, gbids: string[]): Promise<any> {
if (!this.globalAddressSerialized) {
const deferred = UtilInternal.createDeferred();
this.queuedGlobalLookupsByParticipantId.push({
participantId,
ttl,
gbids,
resolve: deferred.resolve,
reject: deferred.reject
});
return deferred.promise;
} else {
return this.lookupGlobalByParticipantId(participantId, ttl, gbids);
}
}
/**
* @param discoveryEntry to be added to the global discovery directory
* @param gbids global backend identifiers of backends to add discoveryEntries into
* @returns an A+ promise
*/
private addGlobal(discoveryEntry: DiscoveryEntry, gbids: string[]): Promise<void> {
return this.getGlobalCapabilitiesDirectoryProxy(TTL_30DAYS_IN_MS)
.then(globalCapabilitiesDirectoryProxy => {
const discoveryEntryWithAddress = discoveryEntry as DiscoveryEntry & { address: string };
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
discoveryEntryWithAddress.address = this.globalAddressSerialized!;
return globalCapabilitiesDirectoryProxy.add({
globalDiscoveryEntry: new GlobalDiscoveryEntry(discoveryEntryWithAddress),
gbids
});
})
.catch(error => {
log.error(`Error calling operation "add" of GlobalCapabilitiesDirectory because: ${error}`);
throw error;
});
}
/**
* @param queuedDiscoveryEntry contains a discoveryEntry and the resolve
* and reject functions from the original Promise created on add().
*/
private addGlobalQueued(queuedDiscoveryEntry: QueuedGlobalDiscoveryEntires): void {
this.addGlobal(queuedDiscoveryEntry.discoveryEntry, queuedDiscoveryEntry.gbids)
.then(queuedDiscoveryEntry.resolve)
.catch(queuedDiscoveryEntry.reject);
}
/**
* This method removes a capability from the global capabilities directory.
*
* @param participantId to remove
*
* @returns an A+ promise
*/
private removeParticipantIdFromGlobalCapabilitiesDirectory(participantId: string): Promise<void> {
return this.getGlobalCapabilitiesDirectoryProxy(TTL_30DAYS_IN_MS)
.then(globalCapabilitiesDirectoryProxy => {
return globalCapabilitiesDirectoryProxy.remove({
participantId
});
})
.catch(error => {
throw new Error(`Error calling operation "remove" of GlobalCapabilitiesDirectory because: ${error}`);
});
}
/**
* This method is called when the global address has been created
*
* @param newGlobalAddress the address used to register discovery entries globally
*/
public globalAddressReady(newGlobalAddress: Address): void {
let parameters;
this.globalAddressSerialized = JSON.stringify(newGlobalAddress);
for (let i = 0; i < this.queuedGlobalDiscoveryEntries.length; i++) {
this.addGlobalQueued(this.queuedGlobalDiscoveryEntries[i]);
}
this.queuedGlobalDiscoveryEntries = [];
for (let i = 0; i < this.queuedGlobalLookups.length; i++) {
parameters = this.queuedGlobalLookups[i];
this.lookupGlobal(
parameters.domains,
parameters.interfaceName,
parameters.ttl,
parameters.capabilities,
parameters.gbids
)
.then(parameters.resolve)
.catch(parameters.reject);
}
this.queuedGlobalLookups = [];
for (let i = 0; i < this.queuedGlobalLookupsByParticipantId.length; i++) {
parameters = this.queuedGlobalLookupsByParticipantId[i];
this.lookupGlobalByParticipantId(parameters.participantId, parameters.ttl, parameters.gbids)
.then(parameters.resolve)
.catch(parameters.reject);
}
this.queuedGlobalLookupsByParticipantId = [];
}
/**
* This method queries the local and/or global capabilities directory according to the given discoveryStrategy given in the
* DiscoveryQos object
*
* @param domains the domains
* @param interfaceName the interface name
* @param discoveryQos the DiscoveryQos giving the strategy for discovering a capability
* @param gbids the backends in which the lookup shall be performed
* @returns an A+ Promise object, that will provide an array of discovered capabilities, callback signatures:
* then({Array[GlobalDiscoveryEntry]} discoveredCaps).catch({Error} error)
*/
public lookup(
domains: string[],
interfaceName: string,
discoveryQos: DiscoveryQosGen,
gbids: string[]
): Promise<DiscoveryEntryWithMetaInfo[]> {
let localCapabilities, globalCapabilities;
gbids = gbids.length > 0 ? gbids : this.knownGbids;
if (domains.length !== 1) {
return Promise.reject(
new ProviderRuntimeException({
detailMessage: "Cluster-controller does not yet support multi-proxy lookups."
})
);
}
switch (discoveryQos.discoveryScope.value) {
// only interested in local results
case DiscoveryScope.LOCAL_ONLY.value:
localCapabilities = this.localCapabilitiesStore.lookup({
domains,
interfaceName
});
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(true, localCapabilities)
);
// if anything local use it. Otherwise lookup global.
case DiscoveryScope.LOCAL_THEN_GLOBAL.value:
localCapabilities = this.localCapabilitiesStore.lookup({
domains,
interfaceName
});
if (localCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(true, localCapabilities)
);
}
globalCapabilities = this.globalCapabilitiesCache.lookup({
domains,
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
if (globalCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(false, globalCapabilities)
);
}
return this.lookupGlobalCapabilities(
domains,
interfaceName,
TTL_30DAYS_IN_MS,
localCapabilities,
gbids
);
// Use local results, but then lookup global
case DiscoveryScope.LOCAL_AND_GLOBAL.value:
localCapabilities = this.localCapabilitiesStore.lookup({
domains,
interfaceName
});
globalCapabilities = this.globalCapabilitiesCache.lookup({
domains,
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
if (globalCapabilities.length === 0) {
return this.lookupGlobalCapabilities(
domains,
interfaceName,
TTL_30DAYS_IN_MS,
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(true, localCapabilities),
gbids
);
}
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(true, localCapabilities).concat(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(false, globalCapabilities)
)
);
case DiscoveryScope.GLOBAL_ONLY.value:
globalCapabilities = this.globalCapabilitiesCache.lookup({
domains,
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
if (globalCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfoArray(false, globalCapabilities)
);
}
return this.lookupGlobalCapabilities(
domains,
interfaceName,
TTL_30DAYS_IN_MS,
globalCapabilities,
gbids
);
default:
return Promise.reject(
new ProviderRuntimeException({
detailMessage: `unknown discoveryScope value: ${discoveryQos.discoveryScope.value}`
})
);
}
}
/**
* This method queries the local and/or global capabilities directory according to the given discoveryStrategy given in the
* DiscoveryQos object
*
* @param participantId the participantId
* @param discoveryQos the DiscoveryQos giving the strategy for discovering a capability
* @param gbids the backends in which the lookup shall be performed
* @returns an A+ Promise object, that will one single discovered capabilities, callback signatures:
* then({GlobalDiscoveryEntry} discoveredCap).catch({Error} error)
*/
public lookupByParticipantId(
participantId: string,
discoveryQos: DiscoveryQosGen,
gbids: string[]
): Promise<DiscoveryEntryWithMetaInfo> {
let localCapabilities, globalCapabilities;
gbids = gbids.length > 0 ? gbids : this.knownGbids;
switch (discoveryQos.discoveryScope.value) {
// only interested in local results
case DiscoveryScope.LOCAL_ONLY.value:
localCapabilities = this.localCapabilitiesStore.lookup({ participantId });
if (localCapabilities.length === 0) {
log.debug(
`lookupByParticipantId(): no capability entry found in local capabilities store for participantId ${participantId}.`
);
return Promise.reject(DiscoveryError.NO_ENTRY_FOR_PARTICIPANT);
}
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(true, localCapabilities[0])
);
case DiscoveryScope.LOCAL_THEN_GLOBAL.value:
case DiscoveryScope.LOCAL_AND_GLOBAL.value:
localCapabilities = this.localCapabilitiesStore.lookup({ participantId });
if (localCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(true, localCapabilities[0])
);
}
globalCapabilities = this.globalCapabilitiesCache.lookup({
participantId,
cacheMaxAge: discoveryQos.cacheMaxAge
});
if (globalCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, globalCapabilities[0])
);
}
// no capability entry found in local or global cache
// search for local entries in the global capabilities directory
return this.lookupGlobalCapabilitiesByParticipantId(participantId, TTL_30DAYS_IN_MS, gbids);
case DiscoveryScope.GLOBAL_ONLY.value:
globalCapabilities = this.globalCapabilitiesCache.lookup({
participantId,
cacheMaxAge: discoveryQos.cacheMaxAge
});
if (globalCapabilities.length > 0) {
return Promise.resolve(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, globalCapabilities[0])
);
}
// no capability entry found found in local cache
// search for global entries in the global capabilities directory
return this.lookupGlobalCapabilitiesByParticipantId(participantId, TTL_30DAYS_IN_MS, gbids);
default:
log.debug(`lookupByParticipantId(): unknown discovery scope ${discoveryQos.discoveryScope.value}`);
return Promise.reject(DiscoveryError.INTERNAL_ERROR);
}
}
/**
* This method adds a capability in the local and/or global capabilities directory according to
* the given registration strategy. Global capabilities will be added to all known gbids.
*
* @param discoveryEntry DiscoveryEntry to add to all known backends
* @returns Promise resolved on success.
*/
public addToAll(discoveryEntry: DiscoveryEntry): Promise<void> {
return this.addInternal(discoveryEntry, this.knownGbids);
}
private addInternal(discoveryEntry: DiscoveryEntry, gbids: string[]): Promise<void> {
this.localCapabilitiesStore.add({
discoveryEntry,
remote: false
});
discoveryEntry.lastSeenDateMs = Date.now();
if (discoveryEntry.qos.scope === ProviderScope.LOCAL) {
return Promise.resolve();
} else if (discoveryEntry.qos.scope === ProviderScope.GLOBAL) {
if (!this.globalAddressSerialized) {
const deferred = UtilInternal.createDeferred();
this.queuedGlobalDiscoveryEntries.push({
discoveryEntry,
gbids,
resolve: deferred.resolve,
reject: deferred.reject
});
return deferred.promise;
} else {
return this.addGlobal(discoveryEntry, gbids);
}
}
return Promise.reject(new Error(`Encountered unknown ProviderQos scope "${discoveryEntry.qos.scope}"`));
}
/**
* This method adds a capability in the local and/or global capabilities directory according to the given registration
* strategy.
*
* @param discoveryEntry DiscoveryEntry of the capability
* @param _awaitGlobalRegistration webSocket-libjoynr specific property part of the DiscoveryStub interface
* @param gbids identifiers of global backends to add capability into
*
* @returns an A+ promise
*/
public add(
discoveryEntry: DiscoveryEntry,
_awaitGlobalRegistration?: boolean,
gbids: string[] = []
): Promise<void> {
return this.addInternal(discoveryEntry, gbids.length > 0 ? gbids : [this.knownGbids[0]]);
}
/**
* This method sends a freshness update to the global capabilities directory to update
* the lastSeenDateMs of the entries registered via the local cluster controller.
*
* @param clusterControllerId the channelId of the local cluster controller
* @param ttlMs the time to live of the freshness update message
*
* @returns an A+ promise
*/
public touch(clusterControllerId: string, ttlMs: number): Promise<void> {
return this.getGlobalCapabilitiesDirectoryProxy(ttlMs)
.then(globalCapabilitiesDirectoryProxy => {
return globalCapabilitiesDirectoryProxy.touch({ clusterControllerId });
})
.catch(error => {
throw new Error(`Error calling operation "touch" of GlobalCapabilitiesDirectory because: ${error}`);
});
}
/**
* This method removes a capability from the local and/or global capabilities directory according to the given registration
* strategy.
*
* @param participantId to remove
*
* @returns an A+ promise
*/
public remove(participantId: string): Promise<void> {
const discoveryEntries = this.localCapabilitiesStore.lookup({
participantId
});
this.localCapabilitiesStore.remove({
participantId
});
if (discoveryEntries === undefined || discoveryEntries.length !== 1) {
log.warn(
`remove(): no capability entry found in local capabilities store for participantId ${participantId}. Trying to remove the capability from global directory`
);
return this.removeParticipantIdFromGlobalCapabilitiesDirectory(participantId);
} else if (discoveryEntries[0].qos.scope === ProviderScope.LOCAL || discoveryEntries.length < 1) {
return Promise.resolve();
} else if (discoveryEntries[0].qos.scope === ProviderScope.GLOBAL) {
return this.removeParticipantIdFromGlobalCapabilitiesDirectory(participantId);
} else {
return Promise.reject(
new Error(`Encountered unknown ProviderQos scope "${discoveryEntries[0].qos.scope}"`)
);
}
}
}
export = CapabilityDiscovery; | the_stack |
import type { RouteMatch as _envoy_config_route_v3_RouteMatch, RouteMatch__Output as _envoy_config_route_v3_RouteMatch__Output } from '../../../../envoy/config/route/v3/RouteMatch';
import type { RouteAction as _envoy_config_route_v3_RouteAction, RouteAction__Output as _envoy_config_route_v3_RouteAction__Output } from '../../../../envoy/config/route/v3/RouteAction';
import type { RedirectAction as _envoy_config_route_v3_RedirectAction, RedirectAction__Output as _envoy_config_route_v3_RedirectAction__Output } from '../../../../envoy/config/route/v3/RedirectAction';
import type { Metadata as _envoy_config_core_v3_Metadata, Metadata__Output as _envoy_config_core_v3_Metadata__Output } from '../../../../envoy/config/core/v3/Metadata';
import type { Decorator as _envoy_config_route_v3_Decorator, Decorator__Output as _envoy_config_route_v3_Decorator__Output } from '../../../../envoy/config/route/v3/Decorator';
import type { DirectResponseAction as _envoy_config_route_v3_DirectResponseAction, DirectResponseAction__Output as _envoy_config_route_v3_DirectResponseAction__Output } from '../../../../envoy/config/route/v3/DirectResponseAction';
import type { HeaderValueOption as _envoy_config_core_v3_HeaderValueOption, HeaderValueOption__Output as _envoy_config_core_v3_HeaderValueOption__Output } from '../../../../envoy/config/core/v3/HeaderValueOption';
import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../../google/protobuf/Any';
import type { Tracing as _envoy_config_route_v3_Tracing, Tracing__Output as _envoy_config_route_v3_Tracing__Output } from '../../../../envoy/config/route/v3/Tracing';
import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from '../../../../google/protobuf/UInt32Value';
import type { FilterAction as _envoy_config_route_v3_FilterAction, FilterAction__Output as _envoy_config_route_v3_FilterAction__Output } from '../../../../envoy/config/route/v3/FilterAction';
/**
* A route is both a specification of how to match a request as well as an indication of what to do
* next (e.g., redirect, forward, rewrite, etc.).
*
* .. attention::
*
* Envoy supports routing on HTTP method via :ref:`header matching
* <envoy_api_msg_config.route.v3.HeaderMatcher>`.
* [#next-free-field: 18]
*/
export interface Route {
/**
* Route matching parameters.
*/
'match'?: (_envoy_config_route_v3_RouteMatch | null);
/**
* Route request to some upstream cluster.
*/
'route'?: (_envoy_config_route_v3_RouteAction | null);
/**
* Return a redirect.
*/
'redirect'?: (_envoy_config_route_v3_RedirectAction | null);
/**
* The Metadata field can be used to provide additional information
* about the route. It can be used for configuration, stats, and logging.
* The metadata should go under the filter namespace that will need it.
* For instance, if the metadata is intended for the Router filter,
* the filter name should be specified as *envoy.filters.http.router*.
*/
'metadata'?: (_envoy_config_core_v3_Metadata | null);
/**
* Decorator for the matched route.
*/
'decorator'?: (_envoy_config_route_v3_Decorator | null);
/**
* Return an arbitrary HTTP response directly, without proxying.
*/
'direct_response'?: (_envoy_config_route_v3_DirectResponseAction | null);
/**
* Specifies a set of headers that will be added to requests matching this
* route. Headers specified at this level are applied before headers from the
* enclosing :ref:`envoy_api_msg_config.route.v3.VirtualHost` and
* :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including details on
* header value syntax, see the documentation on :ref:`custom request headers
* <config_http_conn_man_headers_custom_request_headers>`.
*/
'request_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[];
/**
* Specifies a set of headers that will be added to responses to requests
* matching this route. Headers specified at this level are applied before
* headers from the enclosing :ref:`envoy_api_msg_config.route.v3.VirtualHost` and
* :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including
* details on header value syntax, see the documentation on
* :ref:`custom request headers <config_http_conn_man_headers_custom_request_headers>`.
*/
'response_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[];
/**
* Specifies a list of HTTP headers that should be removed from each response
* to requests matching this route.
*/
'response_headers_to_remove'?: (string)[];
/**
* Specifies a list of HTTP headers that should be removed from each request
* matching this route.
*/
'request_headers_to_remove'?: (string)[];
/**
* The typed_per_filter_config field can be used to provide route-specific
* configurations for filters. The key should match the filter name, such as
* *envoy.filters.http.buffer* for the HTTP buffer filter. Use of this field is filter
* specific; see the :ref:`HTTP filter documentation <config_http_filters>` for
* if and how it is utilized.
* [#comment: An entry's value may be wrapped in a
* :ref:`FilterConfig<envoy_api_msg_config.route.v3.FilterConfig>`
* message to specify additional options.]
*/
'typed_per_filter_config'?: ({[key: string]: _google_protobuf_Any});
/**
* Name for the route.
*/
'name'?: (string);
/**
* Presence of the object defines whether the connection manager's tracing configuration
* is overridden by this route specific instance.
*/
'tracing'?: (_envoy_config_route_v3_Tracing | null);
/**
* The maximum bytes which will be buffered for retries and shadowing.
* If set, the bytes actually buffered will be the minimum value of this and the
* listener per_connection_buffer_limit_bytes.
*/
'per_request_buffer_limit_bytes'?: (_google_protobuf_UInt32Value | null);
/**
* [#not-implemented-hide:]
* If true, a filter will define the action (e.g., it could dynamically generate the
* RouteAction).
* [#comment: TODO(samflattery): Remove cleanup in route_fuzz_test.cc when
* implemented]
*/
'filter_action'?: (_envoy_config_route_v3_FilterAction | null);
'action'?: "route"|"redirect"|"direct_response"|"filter_action";
}
/**
* A route is both a specification of how to match a request as well as an indication of what to do
* next (e.g., redirect, forward, rewrite, etc.).
*
* .. attention::
*
* Envoy supports routing on HTTP method via :ref:`header matching
* <envoy_api_msg_config.route.v3.HeaderMatcher>`.
* [#next-free-field: 18]
*/
export interface Route__Output {
/**
* Route matching parameters.
*/
'match': (_envoy_config_route_v3_RouteMatch__Output | null);
/**
* Route request to some upstream cluster.
*/
'route'?: (_envoy_config_route_v3_RouteAction__Output | null);
/**
* Return a redirect.
*/
'redirect'?: (_envoy_config_route_v3_RedirectAction__Output | null);
/**
* The Metadata field can be used to provide additional information
* about the route. It can be used for configuration, stats, and logging.
* The metadata should go under the filter namespace that will need it.
* For instance, if the metadata is intended for the Router filter,
* the filter name should be specified as *envoy.filters.http.router*.
*/
'metadata': (_envoy_config_core_v3_Metadata__Output | null);
/**
* Decorator for the matched route.
*/
'decorator': (_envoy_config_route_v3_Decorator__Output | null);
/**
* Return an arbitrary HTTP response directly, without proxying.
*/
'direct_response'?: (_envoy_config_route_v3_DirectResponseAction__Output | null);
/**
* Specifies a set of headers that will be added to requests matching this
* route. Headers specified at this level are applied before headers from the
* enclosing :ref:`envoy_api_msg_config.route.v3.VirtualHost` and
* :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including details on
* header value syntax, see the documentation on :ref:`custom request headers
* <config_http_conn_man_headers_custom_request_headers>`.
*/
'request_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[];
/**
* Specifies a set of headers that will be added to responses to requests
* matching this route. Headers specified at this level are applied before
* headers from the enclosing :ref:`envoy_api_msg_config.route.v3.VirtualHost` and
* :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including
* details on header value syntax, see the documentation on
* :ref:`custom request headers <config_http_conn_man_headers_custom_request_headers>`.
*/
'response_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[];
/**
* Specifies a list of HTTP headers that should be removed from each response
* to requests matching this route.
*/
'response_headers_to_remove': (string)[];
/**
* Specifies a list of HTTP headers that should be removed from each request
* matching this route.
*/
'request_headers_to_remove': (string)[];
/**
* The typed_per_filter_config field can be used to provide route-specific
* configurations for filters. The key should match the filter name, such as
* *envoy.filters.http.buffer* for the HTTP buffer filter. Use of this field is filter
* specific; see the :ref:`HTTP filter documentation <config_http_filters>` for
* if and how it is utilized.
* [#comment: An entry's value may be wrapped in a
* :ref:`FilterConfig<envoy_api_msg_config.route.v3.FilterConfig>`
* message to specify additional options.]
*/
'typed_per_filter_config': ({[key: string]: _google_protobuf_Any__Output});
/**
* Name for the route.
*/
'name': (string);
/**
* Presence of the object defines whether the connection manager's tracing configuration
* is overridden by this route specific instance.
*/
'tracing': (_envoy_config_route_v3_Tracing__Output | null);
/**
* The maximum bytes which will be buffered for retries and shadowing.
* If set, the bytes actually buffered will be the minimum value of this and the
* listener per_connection_buffer_limit_bytes.
*/
'per_request_buffer_limit_bytes': (_google_protobuf_UInt32Value__Output | null);
/**
* [#not-implemented-hide:]
* If true, a filter will define the action (e.g., it could dynamically generate the
* RouteAction).
* [#comment: TODO(samflattery): Remove cleanup in route_fuzz_test.cc when
* implemented]
*/
'filter_action'?: (_envoy_config_route_v3_FilterAction__Output | null);
'action': "route"|"redirect"|"direct_response"|"filter_action";
} | the_stack |
import React, { useState, useMemo, useRef, useEffect } from 'react';
import {
ICommandBarItemProps,
Stack,
CommandBar,
getTheme,
Breadcrumb,
Pivot,
PivotItem,
MessageBar,
Separator,
mergeStyleSets,
ContextualMenuItemType,
} from '@fluentui/react';
import { useDispatch, useSelector } from 'react-redux';
import Axios from 'axios';
import { useBoolean } from '@uifabric/react-hooks';
import { State } from 'RootStateType';
import { postImages, getImages, selectAllImages } from '../store/imageSlice';
import { imageItemSelectorFactory, relabelImageSelector, selectNonDemoPart } from '../store/selectors';
import { getParts } from '../store/partSlice';
import { selectNonDemoCameras } from '../store/cameraSlice';
import { Status } from '../store/project/projectTypes';
import { useInterval } from '../hooks/useInterval';
import { Url } from '../enums';
import LabelingPage from '../components/LabelingPage/LabelingPage';
import { CaptureDialog } from '../components/CaptureDialog';
import { Instruction } from '../components/Instruction';
import { FilteredImgList } from '../components/FilteredImgList';
import { EmptyAddIcon } from '../components/EmptyAddIcon';
const theme = getTheme();
const classes = mergeStyleSets({
seperator: {
margin: '20px 0px',
},
});
/**
* Use the factory to create selector here.
* If we put them inside the component,
* every time component rerender will return a different selector,
* which loose the benefit of memoization.
*/
const labeledImagesSelector = imageItemSelectorFactory(false);
const unlabeledImagesSelector = imageItemSelectorFactory(true);
const onToggleFilterItem = (targetItem: number) => (allItems: Record<number, boolean>) => ({
...allItems,
[targetItem]: !allItems[targetItem],
});
/**
* A hooks that return the command bar items of filter object and the selected filter object id
* @param selector The redux selector of the item
*/
function useFilterItems<T extends { id: number; name: string }>(
selector: (state: State) => T[],
): [ICommandBarItemProps[], string[]] {
const [filterItems, setFilterItems] = useState({});
const itemsInStore = useSelector(selector);
const items: ICommandBarItemProps[] = useMemo(
() =>
itemsInStore.map((c) => ({
key: c.id.toString(),
text: c.name,
canCheck: true,
checked: filterItems[c.id],
onClick: () => setFilterItems(onToggleFilterItem(c.id)),
})),
[itemsInStore, filterItems],
);
const filteredItems = useMemo(() => Object.keys(filterItems).filter((e) => filterItems[e]), [filterItems]);
return [items, filteredItems];
}
/**
* Tell server that the user is checking the re-label images,
* so it won't update the re-label images queue.
* @param isAlive The condition if the re-label images is being checked
*/
const useKeepAlive = (isAlive) => {
const nonDemoProjectId = useSelector((state: State) => state.trainingProject.nonDemo[0]);
useInterval(
() => {
Axios.post(`/api/projects/${nonDemoProjectId}/relabel_keep_alive/`);
},
isAlive ? 3000 : null,
);
};
export const Images: React.FC = () => {
const [isCaptureDialgOpen, { setTrue: openCaptureDialog, setFalse: closeCaptureDialog }] = useBoolean(
false,
);
const fileInputRef = useRef(null);
const dispatch = useDispatch();
const labeledImages = useSelector(labeledImagesSelector);
const unlabeledImages = useSelector(unlabeledImagesSelector);
// Re-labeled images stands for those images that is capture from the inference
const relabelImages = useSelector(relabelImageSelector);
const imageAddedButNoAnno = useSelector(
(state: State) => state.labelImages.ids.length > 0 && state.annotations.ids.length === 0,
);
const labeledImagesLessThanFifteen = useSelector(
(state: State) => state.annotations.ids.length > 0 && labeledImages.length < 15,
);
const imageIsEnoughForTraining = useSelector(
(state: State) => state.project.status === Status.None && labeledImages.length >= 15,
);
const relabelImgsReadyToTrain = useSelector(
(state: State) =>
selectAllImages(state).filter((e) => e.isRelabel && e.manualChecked && !e.uploaded).length,
);
const onUpload = () => {
fileInputRef.current.click();
};
function handleUpload(e: React.ChangeEvent<HTMLInputElement>): void {
for (let i = 0; i < e.target.files.length; i++) {
const formData = new FormData();
formData.append('image', e.target.files[i]);
dispatch(postImages(formData));
}
}
const commandBarItems: ICommandBarItemProps[] = useMemo(
() => [
{
key: 'uploadImages',
text: 'Upload images',
iconProps: {
iconName: 'Upload',
},
onClick: onUpload,
},
{
key: 'captureFromCamera',
text: 'Capture from camera',
iconProps: {
iconName: 'Camera',
},
onClick: openCaptureDialog,
},
],
[openCaptureDialog],
);
const [cameraItems, filteredCameras] = useFilterItems(selectNonDemoCameras);
const [partItems, filteredParts] = useFilterItems(selectNonDemoPart);
const commandBarFarItems: ICommandBarItemProps[] = useMemo(
() => [
{
key: 'filter',
iconOnly: true,
// Make the icon solid if there is a filter applied
iconProps: { iconName: filteredCameras.length || filteredParts.length ? 'FilterSolid' : 'Filter' },
subMenuProps: {
items: [
{
key: 'byPart',
text: 'Filter by object',
itemType: ContextualMenuItemType.Header,
},
...partItems,
{
key: 'byCamera',
text: 'Filter by camera',
itemType: ContextualMenuItemType.Header,
},
...cameraItems,
],
},
},
],
[cameraItems, filteredCameras.length, filteredParts.length, partItems],
);
useEffect(() => {
dispatch(getImages({ freezeRelabelImgs: true }));
// We need part info for image list items
dispatch(getParts());
}, [dispatch]);
useKeepAlive(relabelImages.length > 0);
const onRenderInstructionInsidePivot = () => (
<>
{imageAddedButNoAnno && (
<Instruction
title="Successfully added images!"
subtitle="Now identify what is in your images to start training your model."
smallIcon
/>
)}
{labeledImagesLessThanFifteen && (
<Instruction
title="Images have been tagged!"
subtitle="Continue adding and tagging more images to improve your model. We recommend at least 15 images per object."
smallIcon
/>
)}
</>
);
const onRenderUntaggedPivot = () => {
if (unlabeledImages.length === 0 && relabelImages.length === 0)
return (
<EmptyAddIcon
title="Looks like you don’t have any untagged images"
subTitle="Continue adding and tagging more images from your video streams to improve your model"
primary={{ text: 'Capture from camera', onClick: openCaptureDialog }}
secondary={{ text: 'Upload images', onClick: onUpload }}
/>
);
return (
<>
{relabelImages.length > 0 && (
<>
<Separator alignContent="start" className={classes.seperator}>
Deployment captures
</Separator>
<MessageBar styles={{ root: { margin: '12px 0px' } }}>
Images saved from the current deployment. Confirm or modify the objects identified to improve
your model.
</MessageBar>
<FilteredImgList
images={relabelImages}
filteredCameras={filteredCameras}
filteredParts={filteredParts}
/>
</>
)}
{unlabeledImages.length > 0 && (
<>
<Separator alignContent="start" className={classes.seperator}>
Manually added
</Separator>
<FilteredImgList
images={unlabeledImages}
filteredCameras={filteredCameras}
filteredParts={filteredParts}
/>
</>
)}
</>
);
};
const onRenderMain = () => {
if (labeledImages.length + unlabeledImages.length)
return (
<Pivot>
<PivotItem headerText="Untagged">
{onRenderInstructionInsidePivot()}
{onRenderUntaggedPivot()}
</PivotItem>
<PivotItem headerText="Tagged">
{onRenderInstructionInsidePivot()}
<FilteredImgList
images={labeledImages}
filteredCameras={filteredCameras}
filteredParts={filteredParts}
/>
</PivotItem>
</Pivot>
);
return (
<EmptyAddIcon
title="Add images"
subTitle="Capture images from your video streams and tag parts"
primary={{ text: 'Capture from camera', onClick: openCaptureDialog }}
secondary={{ text: 'Upload images', onClick: onUpload }}
/>
);
};
return (
<>
<Stack styles={{ root: { height: '100%' } }}>
<CommandBar
items={commandBarItems}
styles={{ root: { borderBottom: `solid 1px ${theme.palette.neutralLight}` } }}
farItems={commandBarFarItems}
/>
<Stack styles={{ root: { padding: '15px' } }} grow>
{imageIsEnoughForTraining && (
<Instruction
title="Successfully added and tagged enough photos!"
subtitle="Now you can start deploying your model."
button={{ text: 'Go to Home', to: Url.HOME_CUSTOMIZE }}
/>
)}
{relabelImgsReadyToTrain > 0 && (
<Instruction
title={`${relabelImgsReadyToTrain} images saved from the current deployment have been tagged!`}
subtitle="Update the deployment to retrain the model"
button={{
text: 'Update model',
to: Url.DEPLOYMENT,
}}
/>
)}
<Breadcrumb items={[{ key: 'images', text: 'Images' }]} />
{onRenderMain()}
</Stack>
</Stack>
<CaptureDialog isOpen={isCaptureDialgOpen} onDismiss={closeCaptureDialog} />
<LabelingPage onSaveAndGoCaptured={openCaptureDialog} />
<input
ref={fileInputRef}
type="file"
onChange={handleUpload}
accept="image/*"
multiple
style={{ display: 'none' }}
/>
</>
);
}; | the_stack |
import express from 'express';
import { Access, AccessField, Account, Transaction } from '../models';
import accountManager, { getUserSession, UserActionOrValue } from '../lib/accounts-manager';
import { fullPoll } from '../lib/poller';
import { bankVendorByUuid } from '../lib/bank-vendors';
import { registerStartupTask } from './all';
import * as AccountController from './accounts';
import { isDemoEnabled } from './instance';
import { IdentifiedRequest, PreloadedRequest } from './routes';
import { assert, asyncErr, getErrorCode, KError, makeLogger } from '../helpers';
import { hasMissingField, hasForbiddenField } from '../shared/validators';
const log = makeLogger('controllers/accesses');
// Preloads a bank access (sets @access).
export async function preloadAccess(
req: IdentifiedRequest<Access>,
res: express.Response,
nextHandler: () => void,
accessId: number
) {
try {
const { id: userId } = req.user;
const access = await Access.find(userId, accessId);
if (!access) {
throw new KError('bank access not found', 404);
}
req.preloaded = { access };
nextHandler();
} catch (err) {
asyncErr(res, err, 'when finding bank access');
}
}
export async function destroyWithData(userId: number, access: Access) {
log.info(`Removing access ${access.id} for bank ${access.vendorId}...`);
await Access.destroy(userId, access.id);
await AccountController.fixupDefaultAccount(userId);
log.info('Done!');
}
// Destroy a given access, including accounts, alerts and operations.
export async function destroy(req: PreloadedRequest<Access>, res: express.Response) {
try {
const {
user: { id: userId },
} = req;
if (await isDemoEnabled(userId)) {
throw new KError("access deletion isn't allowed in demo mode", 400);
}
await destroyWithData(userId, req.preloaded.access);
res.status(204).end();
} catch (err) {
asyncErr(res, err, 'when destroying an access');
}
}
export async function deleteSession(req: PreloadedRequest<Access>, res: express.Response) {
try {
const {
user: { id: userId },
} = req;
const { access } = req.preloaded;
const session = getUserSession(userId);
await session.reset(access);
res.status(204).end();
} catch (err) {
asyncErr(res, err, 'when deleting an access session');
}
}
export interface CreateAndRetrieveDataResult {
accessId: number;
accounts: Account[];
newOperations: Transaction[];
label: string;
}
export function extractUserActionFields(body: Record<string, string>) {
const fields = (body.userActionFields || null) as Record<string, string> | null;
delete body.userActionFields;
return fields;
}
export async function createAndRetrieveData(
userId: number,
params: Record<string, unknown>
): Promise<UserActionOrValue<CreateAndRetrieveDataResult>> {
const error =
hasMissingField(params, ['vendorId', 'login', 'password']) ||
hasForbiddenField(params, [
'vendorId',
'login',
'password',
'fields',
'customLabel',
'userActionFields',
]);
if (error) {
throw new KError(`when creating a new access: ${error}`, 400);
}
const userActionFields = extractUserActionFields(params as Record<string, string>);
let access: Access | null = null;
try {
if (userActionFields !== null) {
access = await Access.byCredentials(userId, {
uuid: params.vendorId as string,
login: params.login as string,
});
} else {
access = await Access.create(userId, params);
}
const accountResponse = await accountManager.retrieveAndAddAccountsByAccess(
userId,
access,
/* interactive */ true,
userActionFields
);
if (accountResponse.kind === 'user_action') {
// The whole system relies on the Access object existing (in
// particular, the session with 2fa information is tied to the
// Access), so we can't delete the Access object here.
//
// Unfortunately, because of 2fa, this means the user can abort the
// access creation and leave an inconsistent state in the database,
// where we have an Access but there's no Account/Transaction tied.
//
// So we register a special task that gets run on /api/all (= next
// loading of Kresus), which will clean the access if it has no
// associated accounts, as a proxy of meaning the 2fa has never
// completed.
const prevAccess: Access = access;
registerStartupTask(userId, async () => {
const accounts = await Account.byAccess(userId, prevAccess);
if (accounts.length === 0) {
log.info(`Cleaning up incomplete access with id ${prevAccess.id}`);
await Access.destroy(userId, prevAccess.id);
}
});
return accountResponse;
}
const transactionResponse = await accountManager.retrieveOperationsByAccess(
userId,
access,
/* ignoreLastFetchDate */ false,
/* isInteractive */ true,
userActionFields
);
assert(
transactionResponse.kind !== 'user_action',
'user action should have been requested when fetching accounts'
);
const { accounts, createdTransactions: newOperations } = transactionResponse.value;
return {
kind: 'value',
value: {
accessId: access.id,
accounts,
newOperations,
label: bankVendorByUuid(access.vendorId).name,
},
};
} catch (err) {
log.error('The access process creation failed, cleaning up...');
// Let sql remove all the dependent data for us.
if (access !== null) {
log.info('\tdeleting access...');
await Access.destroy(userId, access.id);
}
// Rethrow the error
throw err;
}
}
// Creates a new bank access (expecting at least (vendorId / login /
// password)), and retrieves its accounts and operations.
export async function create(req: IdentifiedRequest<any>, res: express.Response) {
try {
const {
user: { id: userId },
} = req;
if (await isDemoEnabled(userId)) {
throw new KError("access creation isn't allowed in demo mode", 400);
}
const data = await createAndRetrieveData(userId, req.body);
if (data.kind === 'user_action') {
res.status(200).json(data);
} else {
res.status(201).json(data.value);
}
} catch (err) {
asyncErr(res, err, 'when creating a bank access');
}
}
// Fetch operations using the backend and return the operations to the client.
export async function fetchOperations(req: PreloadedRequest<Access>, res: express.Response) {
try {
const { id: userId } = req.user;
const access = req.preloaded.access;
const bankVendor = bankVendorByUuid(access.vendorId);
if (!access.isEnabled() || bankVendor.deprecated) {
const errcode = getErrorCode('DISABLED_ACCESS');
throw new KError('disabled or deprecated access', 403, errcode);
}
const userActionFields = extractUserActionFields(req.body);
const transactionResponse = await accountManager.retrieveOperationsByAccess(
userId,
access,
/* ignoreLastFetchDate */ false,
/* isInteractive */ true,
userActionFields
);
if (transactionResponse.kind === 'user_action') {
res.status(200).json(transactionResponse);
return;
}
const { accounts, createdTransactions: newOperations } = transactionResponse.value;
res.status(200).json({
accounts,
newOperations,
});
} catch (err) {
asyncErr(res, err, 'when fetching operations');
}
}
// Fetch accounts, including new accounts, and operations using the backend and
// return both to the client.
export async function fetchAccounts(req: PreloadedRequest<Access>, res: express.Response) {
try {
const { id: userId } = req.user;
const access = req.preloaded.access;
const bankVendor = bankVendorByUuid(access.vendorId);
if (!access.isEnabled() || bankVendor.deprecated) {
const errcode = getErrorCode('DISABLED_ACCESS');
throw new KError('disabled access', 403, errcode);
}
const userActionFields = extractUserActionFields(req.body);
const accountResponse = await accountManager.retrieveAndAddAccountsByAccess(
userId,
access,
/* interactive */ true,
userActionFields
);
if (accountResponse.kind === 'user_action') {
res.status(200).json(accountResponse);
return;
}
const transactionResponse = await accountManager.retrieveOperationsByAccess(
userId,
access,
/* ignoreLastFetchDate */ true,
/* isInteractive */ true,
userActionFields
);
assert(
transactionResponse.kind !== 'user_action',
'user action should have been requested when fetching accounts'
);
const { accounts, createdTransactions: newOperations } = transactionResponse.value;
res.status(200).json({
accounts,
newOperations,
});
} catch (err) {
asyncErr(res, err, 'when fetching accounts');
}
}
// Fetch all the operations / accounts for all the accesses, as is done during
// any regular poll.
export async function poll(req: IdentifiedRequest<any>, res: express.Response) {
try {
const { id: userId } = req.user;
await fullPoll(userId);
res.status(200).json({
status: 'OK',
});
} catch (err) {
log.warn(`Error when doing a full poll: ${err.message}`);
res.status(500).json({
status: 'error',
message: err.message,
});
}
}
// Updates a bank access.
export async function update(req: PreloadedRequest<Access>, res: express.Response) {
try {
const { id: userId } = req.user;
const { access } = req.preloaded;
const attrs = req.body;
const error = hasForbiddenField(attrs, ['enabled', 'customLabel']);
if (error) {
throw new KError(`when updating an access: ${error}`, 400);
}
if (attrs.enabled === false) {
attrs.password = null;
delete attrs.enabled;
}
if (attrs.customLabel === '') {
attrs.customLabel = null;
}
await Access.update(userId, access.id, attrs);
res.status(201).json({ status: 'OK' });
} catch (err) {
asyncErr(res, err, 'when updating bank access');
}
}
export async function updateAndFetchAccounts(req: PreloadedRequest<Access>, res: express.Response) {
try {
const { id: userId } = req.user;
const { access } = req.preloaded;
const attrs = req.body;
const error = hasForbiddenField(attrs, ['login', 'password', 'fields', 'userActionFields']);
if (error) {
throw new KError(`when updating and polling an access: ${error}`, 400);
}
// Hack: temporarily remove userActionFields from the entity, so the
// ORM accepts it. Oh well.
const { userActionFields } = attrs;
delete attrs.userActionFields;
if (typeof attrs.fields !== 'undefined') {
const newFields = attrs.fields;
delete attrs.fields;
for (const { name, value } of newFields) {
const previous = access.fields.find(existing => existing.name === name);
if (value === null) {
// Delete the custom field if necessary.
if (typeof previous !== 'undefined') {
await AccessField.destroy(userId, previous.id);
}
} else if (typeof previous !== 'undefined') {
// Update the custom field if necessary.
if (previous.value !== value) {
await AccessField.update(userId, previous.id, { name, value });
}
} else {
// Create it.
await AccessField.create(userId, { name, value, accessId: access.id });
}
}
}
// The preloaded access needs to be updated before calling fetchAccounts.
req.preloaded.access = await Access.update(userId, access.id, attrs);
// Hack: reset userActionFields (see above comment).
req.body.userActionFields = userActionFields;
await fetchAccounts(req, res);
} catch (err) {
asyncErr(res, err, 'when updating and fetching bank access');
}
} | the_stack |
import React, { useEffect, useState } from 'react';
import { createStyles, FormControl, Grid, Input, InputLabel, makeStyles, MenuItem, Select, TextField, Theme, IconButton, Fab, Button, Chip, Tooltip} from '@material-ui/core';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import ClearIcon from '@material-ui/icons/Clear';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
formControl: {
margin: theme.spacing(1),
width: '100%'
},
selectFormControl: {
margin: theme.spacing(1),
width: 170
},
deleteIcon:{
marginTop:15,
color: theme.palette.error.main
},
autoCompleteControl: {
'& .MuiFormControl-marginNormal': {
marginTop: 0
}
},
redColor: {
color: theme.palette.error.main
}
})
);
type Props = {
changeHandler: any,
streamConfigsObj: Object,
columnName:Array<string>,
textDataObj: Array<TextObj>,
tableDataObj:any
};
type TextObj = {
name:string,
encodingType:string,
indexType:string
}
export default function MultiIndexingComponent({
changeHandler,
streamConfigsObj,
columnName,
tableDataObj,
textDataObj
}: Props) {
const classes = useStyles();
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 250,
},
},
};
const [jsonUpdated,setJsonUpdated] = useState(false);
const updateFieldForColumnName = (tempStreamConfigObj,values,Field,majorField) =>{
values.map((v)=>{
let valChanged = false;
tempStreamConfigObj.map((o)=>{
if(v === o.columnName){
if("Encoding" === majorField)
{
o[majorField] = Field;
}else{
o[majorField].push(Field);
}
valChanged = true;
}
})
if(!valChanged){
tempStreamConfigObj.push({
columnName : v,
Indexing : [],
Encoding: "",
[majorField] : "Encoding" === majorField ? Field : [Field]
})
}
})
return tempStreamConfigObj;
}
const convertInputToData = (input,isJsonUpdated) =>{
let tempStreamConfigObj = [];
Object.keys(input).map((o)=>{
switch(o){
case "invertedIndexColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"Inverted","Indexing");
break;
case "rangeIndexColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"Range","Indexing");
break;
case "sortedColumn":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"Sorted","Indexing");
break;
case "bloomFilterColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"bloomFilter","Indexing");
break;
case "noDictionaryColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"None","Encoding");
break;
case "DictionaryColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"Dictionary","Encoding");
break;
case "onHeapDictionaryColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"heapDictionary","Encoding");
break;
case "varLengthDictionaryColumns":
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,input[o],"varDictionary","Encoding");
break;
}
})
if(textDataObj && textDataObj.length){
textDataObj.map((o)=>{
tempStreamConfigObj = updateFieldForColumnName(tempStreamConfigObj,[o.name],"Text","Indexing");
})
}
return tempStreamConfigObj;
}
const [streamConfigObj, setStreamConfigObj] = useState(convertInputToData(streamConfigsObj,false));
const addButtonClick = ()=>{
let data = {
columnName : "",
Indexing : [],
Encoding: ""
};
let tempStreamConfigObj = [...streamConfigObj,data]
setStreamConfigObj(tempStreamConfigObj);
// changeHandler('tableIndexConfig',convertDataToInput(tempStreamConfigObj));
}
const convertDataToInput = async (input) => {
let outputData = {
invertedIndexColumns: [],
rangeIndexColumns : [],
sortedColumn : [],
noDictionaryColumns : [],
DictionaryColumns: [],
onHeapDictionaryColumns : [],
varLengthDictionaryColumns : [],
bloomFilterColumns : []
};
let fieldConfigList= [];
input.map((i)=>{
i.Indexing.map((o)=>{
switch(o){
case "Sorted":
outputData.sortedColumn.push(i.columnName);
break;
case "Inverted":
outputData.invertedIndexColumns.push(i.columnName);
break;
case "Range":
outputData.rangeIndexColumns.push(i.columnName);
break;
case "bloomFilter":
outputData.bloomFilterColumns.push(i.columnName);
break;
case "Text":
fieldConfigList.push({"name":i.columnName, "encodingType":"RAW", "indexType":"TEXT"})
break;
}
})
switch(i.Encoding){
case "None":
outputData.noDictionaryColumns.push(i.columnName);
break;
case "Dictionary":
outputData.DictionaryColumns.push(i.columnName);
break;
case "heapDictionary":
outputData.onHeapDictionaryColumns.push(i.columnName);
break;
case "varDictionary":
outputData.varLengthDictionaryColumns.push(i.columnName);
break;
}
});
return {
tableIndexConfig:outputData,
fieldConfigList
};
}
const keyChange = (input,index, value) =>{
let tempStreamConfigObj = [...streamConfigObj];
tempStreamConfigObj[index][input] = value;
setStreamConfigObj(tempStreamConfigObj);
}
const updateJson = async () =>{
changeHandler('tableIndexConfig',await convertDataToInput(streamConfigObj));
}
const deleteClick = async (ind) =>{
let tempStreamConfigObj = [...streamConfigObj];
tempStreamConfigObj.splice(ind,1);
setStreamConfigObj(tempStreamConfigObj);
changeHandler('tableIndexConfig',await convertDataToInput(tempStreamConfigObj));
}
useEffect(() => {
if(jsonUpdated){
setJsonUpdated(false);
}
else{
let value = convertInputToData(streamConfigsObj,true);
if(value.length >= streamConfigObj.length){
setStreamConfigObj(value);
}
setJsonUpdated(true);
}
}, [streamConfigsObj]);
return (
<Grid container spacing={2}>
{
streamConfigObj && streamConfigObj.map((o,i)=>{
return(
<Grid item xs={6}>
<div className="box-border">
<Grid container spacing={2}>
<Grid item xs={3}>
<FormControl className={classes.formControl}>
<InputLabel htmlFor={o.columnName}>Column Name</InputLabel>
<Select
labelId={o.columnName}
id={o.columnName}
value={o.columnName}
key={i+"columnName"}
onChange={(e)=> keyChange("columnName",i,e.target.value)}
onBlur={updateJson}
>
{columnName.map((val)=>{
return <MenuItem value={val}>{val}</MenuItem>
})}
</Select>
</FormControl>
</Grid>
<Grid item xs={4}>
<Tooltip title="Select a column encoding. By default, all columns are dictionary encoded." arrow placement="top-start">
<FormControl className={classes.formControl}>
<InputLabel htmlFor={o.Encoding}>Encoding</InputLabel>
<Select
labelId={o.Encoding}
id={o.Encoding}
key={i+"Encoding"}
value={o.Encoding}
onChange={(e)=> keyChange("Encoding",i,e.target.value)}
onBlur={updateJson}
>
<MenuItem value="None">None</MenuItem>
<MenuItem value="Dictionary">Dictionary</MenuItem>
<MenuItem value="varDictionary">Variable Length Dictionary</MenuItem>
<MenuItem value="heapDictionary">On Heap Dictionary</MenuItem>
</Select>
</FormControl>
</Tooltip>
</Grid>
<Grid item xs={4}>
<Tooltip title="Select indexes to apply. By default, no indexing is applied." arrow placement="top-start">
<FormControl className={classes.formControl}>
<InputLabel htmlFor={i+"keymulti"}>Indexing</InputLabel>
<Select
labelId={i+"keymulti"}
id={i+"keymulti"}
key={i+"Indexing"}
multiple
value={o.Indexing || []}
onChange={(e)=> keyChange("Indexing",i,e.target.value)}
input={<Input id="select-multiple-chip" />}
renderValue={(selected) => (
<div className={"chips"}>
{(selected as string[]).map((value) => (
<Chip key={value} label={value} className={"chip"} />
))}
</div>
)}
MenuProps={MenuProps}
onBlur={updateJson}>
<MenuItem value="None">None</MenuItem>
<MenuItem value="Sorted">Sorted</MenuItem>
<MenuItem value="Inverted">Inverted</MenuItem>
<MenuItem value="Range">Range</MenuItem>
<MenuItem value="Text">Text</MenuItem>
<MenuItem value="bloomFilter">Bloom filter</MenuItem>
</Select>
</FormControl>
</Tooltip>
</Grid>
<Grid item xs={1}>
<FormControl>
<IconButton aria-label="delete" className={classes.deleteIcon} onClick={()=>{
deleteClick(i)}}>
<ClearIcon />
</IconButton>
</FormControl>
</Grid>
</Grid>
</div>
</Grid>)
})
}
<Grid item xs={3}>
<FormControl className={classes.formControl}>
<Button
aria-label="plus"
variant="outlined"
color="primary"
onClick={addButtonClick}
startIcon={(<AddCircleIcon />)}
>
Add new Field
</Button>
</FormControl>
</Grid>
</Grid>
);
} | the_stack |
import { Position2D } from '../utilities/position2d';
import { DisplayImage } from './display-image';
import { StageImageProperties } from './stage-image-properties';
import { UserInputManager } from './user-input-manager';
/** handel the display / output of game, gui, ... */
export class Stage {
private stageCav: HTMLCanvasElement;
private gameImgProps: StageImageProperties;
private guiImgProps: StageImageProperties;
private controller: UserInputManager;
constructor(canvasForOutput: HTMLCanvasElement, zoom = 2) {
this.controller = new UserInputManager(canvasForOutput);
this.handleOnMouseUp();
this.handleOnMouseDown();
this.handleOnMouseMove();
this.handleOnDoubleClick();
this.handelOnZoom();
this.stageCav = canvasForOutput;
this.gameImgProps = new StageImageProperties(zoom);
this.guiImgProps = new StageImageProperties(zoom);
this.updateStageSize();
this.clear();
}
private calcPosition2D(stageImage: StageImageProperties, e: Position2D): Position2D {
const x = (stageImage.viewPoint.getSceneX(e.x - stageImage.x));
const y = (stageImage.viewPoint.getSceneY(e.y - stageImage.y));
return new Position2D(x, y);
}
private handleOnDoubleClick(): void {
this.controller.onDoubleClick.on((e) => {
if (!e) {
return;
}
const stageImage = this.getStageImageAt(e.x, e.y);
if ((stageImage == null) || (stageImage.display == null)) return;
stageImage.display.onDoubleClick.trigger(this.calcPosition2D(stageImage, e));
});
}
private handleOnMouseDown(): void {
this.controller.onMouseDown.on((e) => {
if (!e) {
return;
}
const stageImage = this.getStageImageAt(e.x, e.y);
if ((stageImage == null) || (stageImage.display == null)) {
return;
}
stageImage.display.onMouseDown.trigger(this.calcPosition2D(stageImage, e));
});
}
private handleOnMouseUp(): void {
this.controller.onMouseUp.on((e) => {
if (!e) {
return;
}
const stageImage = this.getStageImageAt(e.x, e.y);
if ((stageImage == null) || (stageImage.display == null)) {
return;
}
const pos = this.calcPosition2D(stageImage, e);
stageImage.display.onMouseUp.trigger(pos);
});
}
private handleOnMouseMove(): void {
this.controller.onMouseMove.on((e) => {
if (!e) {
return;
}
if (e.button) {
const stageImage = this.getStageImageAt(e.mouseDownX, e.mouseDownY);
if (stageImage == null) {
return;
}
if (stageImage == this.gameImgProps) {
this.updateViewPoint(stageImage, e.deltaX, e.deltaY, 0);
}
}
else {
const stageImage = this.getStageImageAt(e.x, e.y);
if ((stageImage == null) || (stageImage.display == null)) {
return;
}
const x = e.x - stageImage.x;
const y = e.y - stageImage.y;
stageImage.display.onMouseMove.trigger(new Position2D(stageImage.viewPoint.getSceneX(x), stageImage.viewPoint.getSceneY(y)));
}
});
}
private handelOnZoom(): void {
this.controller.onZoom.on((e) => {
if (!e) {
return;
}
const stageImage = this.getStageImageAt(e.x, e.y);
if (stageImage == null) {
return;
}
this.updateViewPoint(stageImage, 0, 0, e.deltaZoom);
});
}
private updateViewPoint(stageImage: StageImageProperties, deltaX: number, deltaY: number, deltaZoom: number) {
if (!stageImage.display) {
return;
}
stageImage.viewPoint.scale += deltaZoom * 0.5;
stageImage.viewPoint.scale = this.limitValue(0.5, stageImage.viewPoint.scale, 10);
stageImage.viewPoint.x += deltaX / stageImage.viewPoint.scale;
stageImage.viewPoint.y += deltaY / stageImage.viewPoint.scale;
stageImage.viewPoint.x = this.limitValue(0, stageImage.viewPoint.x, stageImage.display.getWidth() - stageImage.width / stageImage.viewPoint.scale);
stageImage.viewPoint.y = this.limitValue(0, stageImage.viewPoint.y, stageImage.display.getHeight() - stageImage.height / stageImage.viewPoint.scale);
/// redraw
this.clear(stageImage);
const gameImg = stageImage.display.getImageData();
if (!gameImg) {
return;
}
this.draw(stageImage, gameImg);
}
private limitValue(minLimit: number, value: number, maxLimit: number): number {
const useMax = Math.max(minLimit, maxLimit);
return Math.min(Math.max(minLimit, value), useMax);
}
public updateStageSize() {
const ctx = this.stageCav.getContext('2d');
if (!ctx) {
return;
}
const stageHeight = ctx.canvas.height;
const stageWidth = ctx.canvas.width;
this.gameImgProps.y = 0;
this.gameImgProps.height = stageHeight - 100;
this.gameImgProps.width = stageWidth;
this.guiImgProps.y = stageHeight - 100;
this.guiImgProps.height = 100;
this.guiImgProps.width = stageWidth;
}
public getStageImageAt(x: number, y: number): StageImageProperties | null {
if (this.isPositionInStageImage(this.gameImgProps, x, y)) {
return this.gameImgProps;
}
if (this.isPositionInStageImage(this.guiImgProps, x, y)) {
return this.guiImgProps;
}
return null;
}
private isPositionInStageImage(stageImage: StageImageProperties, x: number, y: number) {
return ((stageImage.x <= x) && ((stageImage.x + stageImage.width) >= x)
&& (stageImage.y <= y) && ((stageImage.y + stageImage.height) >= y));
}
public getGameDisplay(): DisplayImage {
if (this.gameImgProps.display) {
return this.gameImgProps.display;
}
this.gameImgProps.display = new DisplayImage(this);
return this.gameImgProps.display;
}
public getGuiDisplay(): DisplayImage {
if (this.guiImgProps.display) {
return this.guiImgProps.display;
}
this.guiImgProps.display = new DisplayImage(this);
return this.guiImgProps.display;
}
/** set the position of the view point for the game display */
public setGameViewPointPosition(x: number, y: number): void {
this.gameImgProps.viewPoint.x = x;
this.gameImgProps.viewPoint.y = y;
}
/** redraw everything */
public redraw() {
if (this.gameImgProps.display) {
const gameImg = this.gameImgProps.display.getImageData();
if (gameImg) {
this.draw(this.gameImgProps, gameImg);
}
}
if (this.guiImgProps.display) {
const guiImg = this.guiImgProps.display.getImageData();
if (guiImg) {
this.draw(this.guiImgProps, guiImg);
}
}
}
public createImage(display: DisplayImage, width: number, height: number): ImageData | null {
if (display == this.gameImgProps.display) {
return this.gameImgProps.createImage(width, height);
}
else {
return this.guiImgProps.createImage(width, height);
}
}
/** clear the stage/display/output */
public clear(stageImage?: StageImageProperties) {
const ctx = this.stageCav.getContext('2d');
if (!ctx) {
return;
}
ctx.fillStyle = '#000000';
if (stageImage == null) {
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
else {
ctx.fillRect(stageImage.x, stageImage.y, stageImage.width, stageImage.height);
}
}
private fadeTimer = 0;
private fadeAlpha = 0;
public resetFade() {
this.fadeAlpha = 0;
if (this.fadeTimer != 0) {
clearInterval(this.fadeTimer);
this.fadeTimer = 0;
}
}
public startFadeOut() {
this.resetFade();
this.fadeTimer = setInterval(() => {
this.fadeAlpha = Math.min(this.fadeAlpha + 0.02, 1);
if (this.fadeAlpha <= 0) {
clearInterval(this.fadeTimer);
}
}, 40);
}
/** draw everything to the stage/display */
private draw(display: StageImageProperties, img: ImageData) {
if (!display.ctx) {
return;
}
/// write image to context
display.ctx.putImageData(img, 0, 0);
const ctx = this.stageCav.getContext('2d');
if (!ctx) {
return;
}
ctx.imageSmoothingEnabled = false;
const outH = display.height;
const outW = display.width;
ctx.globalAlpha = 1;
//- Display Layers
let dW = img.width - display.viewPoint.x; //- display width
if ((dW * display.viewPoint.scale) > outW) {
dW = outW / display.viewPoint.scale;
}
let dH = img.height - display.viewPoint.y; //- display height
if ((dH * display.viewPoint.scale) > outH) {
dH = outH / display.viewPoint.scale;
}
if (!display.cav) {
return;
}
//- drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh)
ctx.drawImage(display.cav,
display.viewPoint.x, display.viewPoint.y, dW, dH,
display.x, display.y, Math.trunc(dW * display.viewPoint.scale), Math.trunc(dH * display.viewPoint.scale));
//- apply fading
if (this.fadeAlpha != 0) {
ctx.globalAlpha = this.fadeAlpha;
ctx.fillStyle = 'black';
ctx.fillRect(display.x, display.y, Math.trunc(dW * display.viewPoint.scale), Math.trunc(dH * display.viewPoint.scale));
}
}
} | the_stack |
import * as crypto from "crypto";
import * as debug from "debug";
import * as fs from "fs";
import * as http from "http";
import * as path from "path";
import * as stream from "stream";
import { URL } from "url";
import { MindConnectAgent } from "../../..";
import { TokenRotation } from "../../mindconnect-base";
import { retry, throwError } from "../../utils";
import { SdkClient } from "./sdk-client";
import _ = require("lodash");
const mime = require("mime-types");
const log = debug("multipart-uploader");
export type fileUploadOptionalParameters = {
/**
* Multipart/upload part.
*
* @type {(number | undefined)}
*/
part?: number | undefined;
/**
* File timestamp in mindsphere.
*
* @type {(Date | undefined)}
*/
timestamp?: Date | undefined;
/**
* Description in mindsphere.
*
* @type {(string | undefined)}
*/
description?: string | undefined;
/**
* Mime type in mindsphere.
*
* @type {(string | undefined)}
*/
type?: string | undefined;
/**
* chunkSize. It must be bigger than 5 MB. Default 8 MB.
*
* @type {(number | undefined)}
*/
chunkSize?: number | undefined;
/**
* Number of retries.
*
* @type {(number | undefined)}
*/
retry?: number | undefined;
/**
* log function is called every time a retry happens
*
* @type {(Function | undefined)}
*/
logFunction?: Function | undefined;
/**
* verboseLog for CLI
*
* @type {(Function | undefined)}
*/
verboseFunction?: Function | undefined;
/**
* enables multipart/upload
*
* @type {(boolean | undefined)}
*/
chunk?: boolean | undefined;
/**
* max paralell uploads for parts (default: 3)
*
* @type {(number | undefined)}
*/
parallelUploads?: number | undefined;
/**
* The etag for the upload. if not set the agent will try to guess it.
*
* @type {(number | undefined)}
*/
ifMatch?: number | undefined;
};
type uploadChunkParameters = {
description: string;
chunks: number;
totalChunks: number;
fileType: string;
timeStamp: Date;
uploadPath: string;
entityId: string;
buffer: Uint8Array;
ifMatch?: number;
};
/**
* The multipart uploader handles the upload of the files to the mindsphere
* This class is shared between the MindConnectAgent and the IotFileClient
*
* @export
* @class MultipartUploader
* @extends {MindConnectBase}
*/
export class MultipartUploader {
private getTotalChunks(fileLength: number, chunkSize: number, optional: fileUploadOptionalParameters) {
let totalChunks = Math.ceil(fileLength / chunkSize);
if (totalChunks > 1) {
totalChunks = Math.ceil(fileLength / (Math.floor(chunkSize / this.highWatermark) * this.highWatermark));
}
!optional.chunk &&
totalChunks > 1 &&
throwError("File is too big. Enable chunked/multipart upload (CLI: --chunked) to upload it.");
optional.chunk && totalChunks > 1 && log("WARN: Chunking is experimental!");
return totalChunks;
}
private getTimeStamp(optional: fileUploadOptionalParameters, file: string | Buffer) {
return optional.timestamp || (file instanceof Buffer ? new Date() : fs.statSync(file).ctime);
}
private getFileType(optional: fileUploadOptionalParameters, file: string | Buffer) {
return (
optional.type ||
(file instanceof Buffer ? "application/octet-stream" : `${mime.lookup(file)}` || "application/octet-stream")
);
}
private highWatermark = 1 * 1024 * 1024;
private getStreamFromFile(file: string | Buffer, chunksize: number) {
return file instanceof Buffer
? (() => {
const bufferStream = new stream.PassThrough({ highWaterMark: this.highWatermark });
for (let index = 0; index < file.length; ) {
const end = Math.min(index + chunksize, file.length);
bufferStream.write(file.slice(index, end));
index = end;
}
bufferStream.end();
return bufferStream;
})()
: fs.createReadStream(path.resolve(file), { highWaterMark: this.highWatermark });
}
private addDataToBuffer(current: Uint8Array, data: Buffer) {
const newLength = current.byteLength + data.byteLength;
const newBuffer = new Uint8Array(newLength);
newBuffer.set(current, 0);
newBuffer.set(data, current.byteLength);
current = newBuffer;
return current;
}
private getBareUrl(url: string) {
const parsedUrl = new URL(url);
const bareUrl = url.replace(parsedUrl.search, "");
return bareUrl;
}
private fix_iotFileUpload_3_2_0(result: string | boolean, previousEtag: number | undefined) {
// ! guess etag for the upload
// ! in may 2019 mindsphere was not returning eTags for multipart uploads in the header
// ! but was still expecting them for the new upload
// ! this fix guesses the new value of the eTag
return typeof result === "boolean"
? previousEtag !== undefined
? (previousEtag + 1).toString()
: "0"
: result;
}
private setIfMatch(url: string, headers: any): number | undefined {
let result;
const bareUrl = this.getBareUrl(url);
if (this.agent) {
const config = this.GetConfiguration() as any;
if (config.urls && config.urls[bareUrl]) {
const eTag = config.urls[bareUrl];
const etagNumber = parseInt(eTag);
result = etagNumber;
(<any>headers)["If-Match"] = etagNumber;
}
}
return result;
}
private addUrl(url: string, result: string) {
if (!this.agent) return;
const config = this.GetConfiguration() as any;
if (!config.urls) {
config.urls = {};
}
const entry = this.getBareUrl(url);
config.urls[entry] = result;
}
private async MultipartOperation({
mode,
entityId,
uploadPath,
ifMatch,
description,
fileType,
timeStamp,
}: {
mode: "start" | "complete" | "abort";
entityId: string;
description?: string;
fileType?: string;
uploadPath?: string;
timeStamp?: Date;
ifMatch?: number;
}) {
const url = `/api/iotfile/v3/files/${entityId}/${uploadPath}?upload=${mode}`;
const token = await this.GetToken();
const headers = {
description: description,
type: fileType,
};
timeStamp && ((headers as any).timeStamp = timeStamp.toISOString());
ifMatch !== undefined && ((headers as any)["If-Match"] = ifMatch);
this.setIfMatch(`${this.GetGateway()}${url}`, headers);
const result = await this.GetAuthorizer().HttpAction({
verb: "PUT",
authorization: token,
gateway: this.GetGateway(),
baseUrl: url,
octetStream: true,
additionalHeaders: headers,
noResponse: true,
returnHeaders: true,
body: Buffer.alloc(0),
});
return result;
}
private async UploadChunk({
description,
chunks,
totalChunks,
fileType,
timeStamp,
uploadPath,
entityId,
buffer,
ifMatch,
}: uploadChunkParameters): Promise<boolean> {
if (buffer.length <= 0) return false;
const headers = {
description: description,
type: fileType,
timestamp: timeStamp.toISOString(),
};
ifMatch !== undefined && ((headers as any)["If-Match"] = ifMatch);
let part = totalChunks === 1 ? "" : `?part=${chunks}`;
if (part === `?part=${totalChunks}`) {
part = `?upload=complete`;
}
const url = `/api/iotfile/v3/files/${entityId}/${uploadPath}${part}`;
const previousEtag = this.setIfMatch(`${this.GetGateway()}${url}`, headers);
const token = await this.GetToken();
const gateway = this.GetGateway();
const resultHeaders = (await this.GetAuthorizer().HttpAction({
verb: "PUT",
baseUrl: url,
gateway: gateway,
authorization: token,
body: buffer,
octetStream: true,
additionalHeaders: headers,
noResponse: true,
returnHeaders: true,
})) as Headers;
const result = resultHeaders.get("ETag") || true;
// * only set the eTag after the upload is complete
if (totalChunks > 1 && !url.endsWith(`upload=complete`)) {
return true;
}
const newEtag = this.fix_iotFileUpload_3_2_0(result, previousEtag);
this.addUrl(`${gateway}${url}`, newEtag);
return true;
}
/**
* Abort the multipart operation.
*
* @param {string} entityId
* @param {string} filePath
*
* @memberOf MultipartUploader
*/
public async AbortUpload(entityId: string, filePath: string) {
await this.MultipartOperation({ mode: "abort", entityId: entityId, uploadPath: filePath });
}
/**
* Upload file to MindSphere IOTFileService
*
* @param {string} entityId - asset id or agent.ClientId() for agent
* @param {string} filepath - mindsphere file path
* @param {(string | Buffer)} file - local path or Buffer
* @param {fileUploadOptionalParameters} [optional] - optional parameters: enable chunking, define retries etc.
* @returns {Promise<string>} - md5 hash of the file
*
* @memberOf MultipartUploader
*
*/
public async UploadFile(
entityId: string,
filepath: string,
file: string | Buffer,
optional?: fileUploadOptionalParameters
): Promise<string> {
let storedError;
let aborted = false;
optional = optional || {};
const verboseFunction = optional.verboseFunction;
try {
const result = await this._UploadFile(entityId, filepath, file, optional);
return result;
} catch (error) {
try {
storedError = error;
await this.AbortUpload(entityId, filepath);
verboseFunction && verboseFunction("Aborting previous upload...");
aborted = true;
} catch {}
}
// console.log(storedError, aborted);
storedError &&
aborted &&
throwError(
`Error occurred uploading the file. (Multipart upload was automatically aborted).\n Previous error: ${storedError.message} `
);
storedError && !aborted && throwError(storedError.message);
// typescript issue: https://github.com/microsoft/TypeScript/issues/13958
return "";
}
private async _UploadFile(
entityId: string,
filepath: string,
file: string | Buffer,
optional?: fileUploadOptionalParameters
): Promise<string> {
optional = optional || {};
const chunkSize = optional.chunkSize || 8 * 1024 * 1024;
optional.chunk &&
chunkSize < 5 * 1024 * 1024 &&
throwError("The chunk size must be at least 5 MB for multipart upload.");
const fileLength = file instanceof Buffer ? file.length : fs.statSync(file).size;
const totalChunks = this.getTotalChunks(fileLength, chunkSize, optional);
const shortFileName = path.basename(filepath);
const fileInfo = {
description: optional.description || shortFileName,
timeStamp: this.getTimeStamp(optional, file),
fileType: this.getFileType(optional, file),
uploadPath: filepath,
totalChunks: totalChunks,
entityId: entityId,
ifMatch: optional.ifMatch,
};
const RETRIES = optional.retry || 1;
const logFunction = optional.logFunction;
const verboseFunction = optional.verboseFunction;
const mystream = this.getStreamFromFile(file, chunkSize);
const hash = crypto.createHash("md5");
const promises: any[] = [];
let current = new Uint8Array(0);
let chunks = 0;
if (verboseFunction) verboseFunction(`file upload started for ${file}`);
const multipartLog = logFunction ? logFunction("multipart") : undefined;
if (verboseFunction)
verboseFunction(
totalChunks > 1
? `starting multipart upload: There are: ${totalChunks} total parts.`
: `the file is small enough for normal upload`
);
let startMultipart: { (): Promise<any>; (): void };
if (optional.chunk && totalChunks > 1) {
startMultipart = () =>
retry(
RETRIES,
() =>
this.MultipartOperation({
mode: "start",
...fileInfo,
}),
300,
multipartLog
);
}
return new Promise((resolve, reject) => {
mystream
.on("error", (err) => reject(err))
.on("data", async (data: Buffer) => {
if (current.byteLength + data.byteLength <= chunkSize) {
current = this.addDataToBuffer(current, data);
} else {
if (current.byteLength > 0) {
const currentBuffer = Buffer.from(current);
const uploadLog = logFunction ? logFunction(`part upload (${chunks} part)`) : undefined;
chunks++;
const currentChunk = new Number(chunks).valueOf();
verboseFunction &&
verboseFunction(
`reading chunk number ${chunks} with buffersize : ${(
currentBuffer.length /
(1024 * 1024)
).toFixed(2)} MB`
);
promises.push(() =>
retry(
RETRIES,
() =>
this.UploadChunk({
...fileInfo,
chunks: currentChunk,
buffer: currentBuffer,
}),
300,
uploadLog
)
);
}
current = new Uint8Array(data.byteLength);
current.set(data, 0);
}
})
.on("end", () => {
const currentBuffer = Buffer.from(current);
const uploadLog = logFunction ? logFunction(`part upload (last part)`) : undefined;
chunks++;
verboseFunction &&
verboseFunction(`reading chunk number ${chunks} with buffersize, ${currentBuffer.length}`);
const currentChunk = new Number(chunks).valueOf();
promises.push(() =>
retry(
RETRIES,
() =>
this.UploadChunk({
...fileInfo,
chunks: currentChunk,
buffer: currentBuffer,
}),
300,
uploadLog
)
);
})
.pipe(hash)
.on("finish", async () => {
try {
// * this is the last promise (for multipart) the one which completes the upload
// * this has to be awaited last.
startMultipart &&
(await startMultipart()) &&
verboseFunction &&
verboseFunction("starting multipart upload");
const lastPromise = promises.pop();
// * the chunks before last can be uploaded in paralell to mindsphere
const maxParalellUploads = (optional && optional.parallelUploads) || 3;
http.globalAgent.maxSockets = 50;
const splitedPromises = _.chunk(promises, maxParalellUploads);
if (verboseFunction) verboseFunction(`max parallel uploads ${maxParalellUploads}`);
for (const partPromises of splitedPromises) {
const uploadParts: any = [];
partPromises.forEach(async (f) => {
uploadParts.push(f());
});
if (verboseFunction) verboseFunction(`uploading next ${uploadParts.length} part(s)`);
await Promise.all(uploadParts);
if (verboseFunction) verboseFunction(`uploaded ${uploadParts.length} part(s)`);
}
// * for non-multipart-upload this is the only promise which is ever resolved
// ! don't retry as this is already a retry operation! (from uploadchunk push)
if (verboseFunction)
verboseFunction(
totalChunks > 1 ? `uploading last chunk of ${totalChunks} parts.` : `uploading file`
);
await lastPromise();
const md5 = hash.read().toString("hex");
if (verboseFunction) verboseFunction(`uploaded file. md5 hash: ${md5}`);
resolve(md5);
} catch (err) {
reject(new Error("upload failed: " + err));
}
});
});
}
private async GetToken() {
!this.agent && !this.sdkClient && throwError("invalid conifguraiton for multipart upload");
if (this.agent) {
return await this.agent.GetAgentToken();
}
if (this.sdkClient) {
return await this.sdkClient.GetToken();
}
return "";
}
private GetGateway() {
!this.agent && !this.sdkClient && throwError("invalid conifguraiton for multipart upload");
if (this.agent) {
return `${this.agent.GetMindConnectConfiguration().content.baseUrl}`;
}
if (this.sdkClient) {
return this.sdkClient.GetGateway();
}
return "";
}
private GetConfiguration() {
!this.agent && !this.sdkClient && throwError("invalid conifguraiton for multipart upload");
if (this.agent) {
return this.agent.GetMindConnectConfiguration();
}
}
private GetAuthorizer() {
return (this.agent || this.sdkClient) as TokenRotation;
}
constructor(private agent?: MindConnectAgent, private sdkClient?: SdkClient) {
!agent && !sdkClient && throwError("you have to specify either agent or sdkclient");
}
} | the_stack |
import Shader from "./Shader";
import BindGroupLayout from "./BindGroupLayout.js";
import Uniform from "./Uniform.js";
import Struct from "./Struct.js";
import { formatLowerFirst, formatUpperFirst } from "../utils.js";
import {
AccessMode,
BindingType,
StorageClass,
GPUShaderStage,
GPUTextureSampleType,
} from "../constants.js";
import {
ShaderStageName,
BindGroupLayoutEntry,
Language,
GLSLStorageQualifier,
} from "../types.js";
const isBindingVisible = (
uniformOrBinding: Uniform | BindGroupLayoutEntry,
stage: GPUShaderStageFlags
): boolean =>
!uniformOrBinding.visibility || uniformOrBinding.visibility === stage;
class Program {
constructor(
public bindGroupLayouts: BindGroupLayout[],
public shaders: { [key in ShaderStageName]?: Shader },
public language: Language
) {}
public init(): void {
const headers = this.bindGroupLayouts?.map((bindGroupLayout, index) =>
this[`get${this.language.toUpperCase()}Headers`](
index,
bindGroupLayout.entries
)
);
for (const [key, shader] of Object.entries(this.shaders)) {
shader.init(
headers?.map((header) => header[key as ShaderStageName]).join("\n")
);
}
}
public getWGSLBufferString(
binding: BindGroupLayoutEntry,
bindingIndex: number,
uniforms: Uniform[],
set: number,
storageClass: StorageClass,
accesMode?: AccessMode
): string {
const structName = `${binding.name}${formatUpperFirst(storageClass)}`;
const params = new Struct(structName, uniforms).getWGSLString();
const referenceType = [storageClass, accesMode].filter(Boolean).join(",");
return /* wgsl */ `${params}
[[group(${set}), binding(${bindingIndex})]] var<${referenceType}> ${formatLowerFirst(
binding.name
)}: ${structName};
`;
}
public getWGSLHeaders(
set: number,
entries: BindGroupLayoutEntry[]
): { [key in ShaderStageName]?: string } {
let vertex = "";
let fragment = "";
let compute = "";
for (let i = 0; i < entries.length; i++) {
const binding = entries[i];
if (binding.buffer) {
if (
!binding.buffer.type ||
binding.buffer.type === BindingType.Uniform
) {
let vertexUniforms;
let fragmentUniforms;
if (
isBindingVisible(
binding,
GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT
)
) {
vertexUniforms = binding.uniforms;
fragmentUniforms = binding.uniforms;
} else {
vertexUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.VERTEX)
);
fragmentUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.FRAGMENT)
);
}
const computeUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.COMPUTE)
);
if (vertexUniforms.length) {
vertex += this.getWGSLBufferString(
binding,
i,
vertexUniforms,
set,
StorageClass.Uniform
);
}
if (fragmentUniforms.length) {
fragment += this.getWGSLBufferString(
binding,
i,
fragmentUniforms,
set,
StorageClass.Uniform
);
}
if (computeUniforms.length) {
compute += this.getWGSLBufferString(
binding,
i,
computeUniforms,
set,
StorageClass.Uniform
);
}
} else if (
(
[
BindingType.Storage,
BindingType.ReadonlyStorage,
] as GPUBufferBindingType[]
).includes(binding.buffer.type)
) {
const computeVariables = binding.members.filter(() =>
isBindingVisible(binding, GPUShaderStage.COMPUTE)
) as Uniform[];
compute += this.getWGSLBufferString(
binding,
i,
computeVariables,
set,
StorageClass.Storage,
binding.buffer.type === BindingType.ReadonlyStorage
? AccessMode.Read
: AccessMode.Write
);
}
} else if (binding.sampler) {
const samplerLayout = /* wgsl*/ `[[group(${set}), binding(${i})]] var ${binding.name}: sampler;`;
if (isBindingVisible(binding, GPUShaderStage.VERTEX)) {
vertex += `${samplerLayout}\n`;
}
if (isBindingVisible(binding, GPUShaderStage.FRAGMENT)) {
fragment += `${samplerLayout}\n`;
}
} else if (binding.texture) {
const referenceType =
GPUTextureSampleType[binding.texture.sampleType] || "f32";
const textureLayout = /* wgsl*/ `[[group(${set}), binding(${i})]] var ${binding.name}: texture_${binding.dimension}<${referenceType}>;`;
if (isBindingVisible(binding, GPUShaderStage.VERTEX)) {
vertex += `${textureLayout}\n`;
}
if (isBindingVisible(binding, GPUShaderStage.FRAGMENT)) {
fragment += `${textureLayout}\n`;
}
} else if (binding.storageTexture) {
const referenceType = [
binding.storageTexture.format,
binding.storageTexture.access,
]
.filter(Boolean)
.join(",");
const storageTextureLayout = /* wgsl*/ `[[group(${set}), binding(${i})]] var ${binding.name}: texture_storage_${binding.dimension}<${referenceType}>;`;
if (isBindingVisible(binding, GPUShaderStage.VERTEX)) {
vertex += `${storageTextureLayout}\n`;
}
if (isBindingVisible(binding, GPUShaderStage.FRAGMENT)) {
fragment += `${storageTextureLayout}\n`;
}
}
}
return { vertex, fragment, compute };
}
public getGLSLBufferString(
binding: BindGroupLayoutEntry,
bindingIndex: number,
uniforms: Uniform[],
set: number,
bindingType: GLSLStorageQualifier,
layoutQualifierString: string
): string {
const structName = `${binding.name}${formatUpperFirst(bindingType)}`;
return `layout(${layoutQualifierString}set = ${set}, binding = ${bindingIndex}) ${bindingType} ${structName} {
${uniforms
.map(
(uniform) =>
`${uniform.glslType} ${formatLowerFirst(uniform.name)}${
uniform.arrayCount ? `[${uniform.arrayCount}]` : ""
};`
)
.join("\n ")}
} ${formatLowerFirst(binding.name)};\n\n`;
}
public getGLSLHeaders(
set: number,
entries: BindGroupLayoutEntry[]
): { [key in ShaderStageName]?: string } {
let vertex = "";
let fragment = "";
let compute = "";
for (let i = 0; i < entries.length; i++) {
const binding = entries[i];
const layoutQualifierString = binding.qualifiers?.layout
? `${binding.qualifiers.layout || ""}, `
: "";
// GPUBufferBinding
if (binding.buffer) {
// uniform-buffer
if (
!binding.buffer.type ||
binding.buffer.type === StorageClass.Uniform
) {
let vertexUniforms;
let fragmentUniforms;
if (
isBindingVisible(
binding,
GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT
)
) {
vertexUniforms = binding.uniforms;
fragmentUniforms = binding.uniforms;
} else {
vertexUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.VERTEX)
);
fragmentUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.FRAGMENT)
);
}
const computeUniforms = binding.uniforms.filter(() =>
isBindingVisible(binding, GPUShaderStage.COMPUTE)
);
// Vertex
if (vertexUniforms.length) {
vertex += this.getGLSLBufferString(
binding,
i,
vertexUniforms,
set,
"uniform",
layoutQualifierString
);
}
// Fragment
if (fragmentUniforms.length) {
fragment += this.getGLSLBufferString(
binding,
i,
fragmentUniforms,
set,
"uniform",
layoutQualifierString
);
}
if (computeUniforms.length) {
compute += this.getGLSLBufferString(
binding,
i,
computeUniforms,
set,
"uniform",
layoutQualifierString
);
}
} else if (binding.buffer.type === StorageClass.Storage) {
const computeVariables = binding.members.filter(() =>
isBindingVisible(binding, GPUShaderStage.COMPUTE)
) as Uniform[];
compute += this.getGLSLBufferString(
binding,
i,
computeVariables,
set,
"buffer",
layoutQualifierString
);
}
} else if (binding.sampler) {
const samplerLayout = `layout(set = ${set}, binding = ${i}) uniform sampler${
binding.samplerType || ""
} ${binding.name};`;
if (isBindingVisible(binding, GPUShaderStage.VERTEX)) {
vertex += `${samplerLayout}\n`;
}
if (isBindingVisible(binding, GPUShaderStage.FRAGMENT)) {
fragment += `${samplerLayout}\n`;
}
} else if (binding.texture) {
const textureLayout = `layout(set = ${set}, binding = ${i}) uniform texture${binding.dimension.toUpperCase()} ${
binding.name
};`;
if (isBindingVisible(binding, GPUShaderStage.VERTEX)) {
vertex += `${textureLayout}\n`;
}
if (isBindingVisible(binding, GPUShaderStage.FRAGMENT)) {
fragment += `${textureLayout}\n`;
}
} else if (binding.storageTexture) {
// TODO:
}
}
return { vertex, fragment, compute };
}
}
export default Program; | the_stack |
import * as defs from "./types/jsonx/index";
declare global {
interface window {
[index: string]: any;
}
namespace NodeJS {
interface Global {
document: Document;
window: Window;
navigator: Navigator;
}
}
}
export declare const STRIP_COMMENTS: RegExp;
export declare const ARGUMENT_NAMES: RegExp;
/**
* returns the names of parameters from a function declaration
* @example
* const arrowFunctionAdd = (a,b)=>a+b;
* function regularFunctionAdd(c,d){return c+d;}
* getParamNames(arrowFunctionAdd) // => ['a','b']
* getParamNames(regularFunctionAdd) // => ['c','d']
* @param {Function} func
* @todo write tests
*/
export declare function getParamNames(func: defs.functionParam): RegExpMatchArray;
/**
* It uses traverse on a traverseObject to returns a resolved object on propName. So if you're making an ajax call and want to pass properties into a component, you can assign them using asyncprops and reference object properties by an array of property paths
* @param {Object} [traverseObject={}] - the object that contains values of propName
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @param {Object} [options.propName='asyncprops'] - Property on JSONX to resolve values onto, i.e (asyncprops,thisprops,windowprops)
* @returns {Object} resolved object
* @example
const traverseObject = {
user: {
name: 'jsonx',
description: 'react withouth javascript',
},
stats: {
logins: 102,
comments: 3,
},
authentication: 'OAuth2',
};
const testJSONX = {
component: 'div',
props: {
id: 'generatedJSONX',
className:'jsonx',
},
asyncprops:{
auth: [ 'authentication', ],
username: [ 'user', 'name', ],
},
children: [
{
component: 'p',
props: {
style: {
color: 'red',
fontWeight:'bold',
},
},
children:'hello world',
},
],
};
const JSONXP = getJSONXProps({ jsonx: testJSONX, traverseObject, });
// => {
// auth: 'OAuth2',
// username: 'jsonx'
// }
//finally resolves:
const testJSONX = {
component: 'div',
props: {
id: 'generatedJSONX',
className:'jsonx',
auth: 'OAuth2',
username: 'jsonx',
},
children: [
{
component: 'p',
props: {
style: {
color: 'red',
fontWeight:'bold',
},
},
children:'hello world',
},
],
};
*/
export declare function getJSONXProps(options?: defs.dynamicFunctionParams): defs.jsonxResourceProps;
/**
* returns children jsonx components defined on __spreadComponent spread over an array on props.__spread
* @param {*} options
*/
export declare function getChildrenComponents(this: defs.Context, options?: {
allProps?: any;
jsonx?: defs.jsonx;
}): {
children: string;
_children?: undefined;
} | {
children: undefined;
_children?: undefined;
} | {
_children: any;
children?: undefined;
};
/**
* registers an input to a reactHookForm register function
* @param {*} options
* @returns {object} - returns name, ref, onBlur, onChange
*/
export declare function useFormRegisterHandler(this: {
reactHookForm: {
register: (ref: string) => {
name: string;
ref: HTMLElement;
onBlur: () => void;
onChange: () => void;
};
};
}, options?: {
jsonx?: defs.jsonx;
}): {
name: string;
ref: HTMLElement;
onBlur: () => void;
onChange: () => void;
};
/**
* returns a reducer function that returns values ot bind to an eval function. This function is used when values need to be passed from a hook function to a prop that is a function
* @param {object} this
* @param {object} jsonx
* @returns {function}
*/
export declare function boundArgsReducer(this: defs.Context, jsonx?: defs.jsonx): (args: any, arg: string) => any;
/**
* Used to evalute javascript and set those variables as props. getEvalProps evaluates __dangerouslyEvalProps and __dangerouslyBindEvalProps properties with eval, this is used when component properties are functions, __dangerouslyBindEvalProps is used when those functions require that this is bound to the function. For __dangerouslyBindEvalProps it must resolve an expression, so functions should be wrapped in (). I.e. (function f(x){ return this.minimum+x;})
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @returns {Object} returns resolved object with evaluated javascript
* @example
const testVals = {
auth: 'true',
username: '(user={})=>user.name',
};
const testJSONX = Object.assign({}, sampleJSONX, {
__dangerouslyEvalProps: testVals, __dangerouslyBindEvalProps: {
email: '(function getUser(user={}){ return this.testBound(); })',
},
});
const JSONXP = getEvalProps.call({ testBound: () => 'bounded', }, { jsonx: testJSONX, });
const evalutedComputedFunc = JSONXP.username({ name: 'bob', });
const evalutedComputedBoundFunc = JSONXP.email({ email:'test@email.domain', });
// expect(JSONXP.auth).to.be.true;
// expect(evalutedComputedFunc).to.eql('bob');
// expect(evalutedComputedBoundFunc).to.eql('bounded');
*/
export declare function getEvalProps(this: defs.Context, options?: {
jsonx: defs.jsonx;
}): {};
/**
* Resolves jsonx.__dangerouslyInsertComponents into an object that turns each value into a React components. This is typically used in a library like Recharts where you pass custom components for chart ticks or plot points.
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @param {Object} [options.resources={}] - object to use for resourceprops(asyncprops), usually a result of an asynchronous call
* @returns {Object} resolved object of React Components
*/
export declare function getComponentProps(this: defs.Context, options?: defs.Config): defs.jsonxResourceProps;
/**
* Used to create components from jsonx as props
* @param this
* @param options
*/
export declare function getReactComponents(this: defs.Context, options: defs.Config): defs.jsonxResourceProps;
/**
* Resolves jsonx.__dangerouslyInsertReactComponents into an object that turns each value into a React components. This is typically used in a library like Recharts where you pass custom components for chart ticks or plot points.
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
// * @param {Object} [options.resources={}] - object to use for asyncprops, usually a result of an asynchronous call
* @returns {Object} resolved object of React Components
*/
export declare function getReactComponentProps(this: defs.Context, options?: {
jsonx: defs.jsonx;
}): defs.jsonxResourceProps | undefined;
/**
* Takes a function string and returns a function on either this.props or window. The function can only be 2 levels deep
* @param {Object} options
* @param {String} [options.propFunc='func:'] - function string, like func:window.LocalStorage.getItem or func:this.props.onClick or func:inline.myInlineFunction
* @param {Object} [options.allProps={}] - merged computed props, Object.assign({ key: renderIndex, }, thisprops, jsonx.props, resourceprops, asyncprops, windowprops, evalProps, insertedComponents);
* @returns {Function} returns a function from this.props or window functions
* @example
* getFunctionFromProps({ propFunc='func:this.props.onClick', }) // => this.props.onClick
* @deprecated
*/
export declare function getFunctionFromProps(this: defs.Context, options?: {
propFunc?: string;
propBody: string;
jsonx: defs.jsonx;
functionProperty?: string;
}): any;
/**
* Returns a resolved object from function strings that has functions pulled from jsonx.__functionProps
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @param {Object} [options.allProps={}] - merged computed props, Object.assign({ key: renderIndex, }, thisprops, jsonx.props, asyncprops, windowprops, evalProps, insertedComponents);
* @returns {Object} resolved object of functions from function strings
*/
export declare function getFunctionProps(this: defs.Context, options?: {
allProps?: any;
jsonx: defs.jsonx;
}): any;
/**
* Returns a resolved object that has React Components pulled from window.__jsonx_custom_elements
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @param {Object} [options.allProps={}] - merged computed props, Object.assign({ key: renderIndex, }, thisprops, jsonx.props, asyncprops, windowprops, evalProps, insertedComponents);
* @returns {Object} resolved object of with React Components from a window property window.__jsonx_custom_elements
*/
export declare function getWindowComponents(this: defs.Context, options?: {
allProps?: any;
jsonx: defs.jsonx;
}): any;
/**
* Returns computed properties for React Components and any property that's prefixed with __ is a computedProperty
* @param {Object} options
* @param {Object} options.jsonx - Valid JSONX JSON
* @param {Object} [options.resources={}] - object to use for asyncprops, usually a result of an asynchronous call
* @param {Number} options.renderIndex - number used for React key prop
* @param {function} [options.logError=console.error] - error logging function
* @param {Object} [options.componentLibraries] - react components to render with JSONX
* @param {Boolean} [options.useReduxState=true] - use redux props in this.props
* @param {Boolean} [options.ignoreReduxPropsInComponentLibraries=true] - ignore redux props in this.props for component libraries, this is helpful incase these properties collide with component library element properties
* @param {boolean} [options.debug=false] - use debug messages
* @example
const testJSONX = { component: 'div',
props: { id: 'generatedJSONX', className: 'jsonx' },
children: [ [Object] ],
asyncprops: { auth: [Array], username: [Array] },
__dangerouslyEvalProps: { getUsername: '(user={})=>user.name' },
__dangerouslyInsertComponents: { myComponent: [Object] }
const resources = {
user: {
name: 'jsonx',
description: 'react withouth javascript',
},
stats: {
logins: 102,
comments: 3,
},
authentication: 'OAuth2',
};
const renderIndex = 1;
getComputedProps.call({}, {
jsonx: testJSONX,
resources,
renderIndex,
});
computedProps = { key: 1,
id: 'generatedJSONX',
className: 'jsonx',
auth: 'OAuth2',
username: 'jsonx',
getUsername: [Function],
myComponent:
{ '$$typeof': Symbol(react.element),
type: 'p',
key: '8',
ref: null,
props: [Object],
_owner: null,
_store: {} } } }
*
*/
export declare function getComputedProps(this: defs.Context, options?: {
jsonx?: defs.jsonx;
resources?: defs.jsonxResourceProps;
renderIndex?: number;
logError?: any;
useReduxState?: boolean;
ignoreReduxPropsInComponentLibraries?: boolean;
disableRenderIndexKey?: boolean;
debug?: boolean;
componentLibraries?: defs.jsonxLibrary;
}): any; | the_stack |
import { getEle } from "../../../utility/dom/getEle";
import { convertPairToCSSText } from "../../../utility/dom/convertPairToCSSText";
import { getAllEle } from "../../../utility/dom/getAllEle";
import { setCss } from "../../../utility/dom/setCss";
import { addClass } from "../../../utility/dom/addClass";
import { removeClass } from "../../../utility/dom/removeClass";
import { setAttr } from "../../../utility/dom/setAttr";
export interface ISortDraggableProps {
container: string;
dataSource?: IStaticDataSourceParams[];
animate?: boolean;
dragWrapperStyle?: Partial<CSSStyleDeclaration>;
dragOriginStyle?: Partial<CSSStyleDeclaration>;
dragOriginActiveStyle?: Partial<CSSStyleDeclaration>;
dragTargetActiveStyle?: Partial<CSSStyleDeclaration>;
onDragStartHook?: (origin: HTMLElement) => void;
onDragEnterHook?: (origin: HTMLElement, target: HTMLElement) => void;
onDragLeaveHook?: (origin: HTMLElement, target: HTMLElement) => void;
onDragOverHook?: (origin: HTMLElement, target: HTMLElement) => void;
onDropHook?: (origin: HTMLElement) => void;
};
export interface IStaticDataSourceParams {
titleText?: string;
contentText?: string;
};
export class SortDraggable {
public static _aidedFindIndex(
node: Element | null,
count: number,
): any {
if (!node) {
return count;
}
return this._aidedFindIndex(
node.previousElementSibling,
++count
);
}
public static readonly defaultProps = {
container: 'body',
dataSource: [
{
titleText: '1',
contentText: '第一项的内容',
},
{
titleText: '2',
contentText: '第二项的内容',
},
{
titleText: '3',
contentText: '第三项的内容',
},
{
titleText: '4',
contentText: '第四项的内容',
},
{
titleText: '5',
contentText: '第五项的内容',
},
],
dragWrapperStyle: {
backgroundColor: '#fff',
},
dragOriginStyle: {
margin: '8px 0',
border: '1px solid #ebeef5',
borderRadius: '4px',
boxShadow: '0 2px 12px 0 rgba(0, 0, 0, .1)',
},
dragOriginActiveStyle: {
boxShadow: '0 2px 12px 0 rgba(0, 0, 0, .4)',
},
dragTargetActiveStyle: {
opacity: '.5',
},
animate: true,
onDragStartHook(_origin: HTMLElement) { },
onDragEnterHook(_origin: HTMLElement, _target: HTMLElement) { },
onDragLeaveHook(_origin: HTMLElement, _target: HTMLElement) { },
onDragOverHook(_origin: HTMLElement, _target: HTMLElement) { },
onDropHook(_origin: HTMLElement) { },
};
public constructor(
props: ISortDraggableProps,
) {
this.__init__(props);
}
// 拖拽容器, origin任意父级
private dragContainer: HTMLElement = (
document.createElement('ul')
);
// 拖拽列表
private dragItems: HTMLElement[] = [
document.createElement('li'),
];
// 保存被拖拽元素
private origin: HTMLElement = (
document.createElement('div')
);
// 储存拖拽前后, origin & target位置信息
private position = {
originBeforeRect: {
top: 0,
},
originAfterRect: {
top: 0,
},
targetBeforeRect: {
top: 0,
},
targetAfterRect: {
top: 0,
},
};
private __init__(
props: ISortDraggableProps,
): void {
this._initProps(props);
this.render();
}
private _initProps(
props: ISortDraggableProps,
): void {
for (const key in props) {
if (props.hasOwnProperty(key)) {
const value = Reflect.get(props, key);
Reflect.set(SortDraggable.defaultProps, key, value);
}
}
}
private aidedCreateDOM(): string {
const {
dataSource,
} = SortDraggable.defaultProps;
let tempStr: string = '';
dataSource.forEach((v, i) => {
tempStr += `
<li class="ddzy-drag-list-item ddzy-drag-item-${i}">
<div class="ddzy-drag-item-title-box">
<div class="ddzy-drag-item-title">
${v.titleText}
</div>
</div>
<div class="ddzy-drag-item-content-box">
<div class="ddzy-drag-item-content">
${v.contentText}
</div>
</div>
</li>
`;
});
const dom: string = `
<div id="ddzy-drag-wrapper">
<div class="ddzy-drag-main">
<ul class="ddzy-drag-main-list">
${tempStr}
</ul>
</div>
</div>
`;
return dom;
}
private aidedMountDOM(
dom: string,
): void {
const {
container,
} = SortDraggable.defaultProps;
const mountWrapper = getEle(container);
if (mountWrapper) {
mountWrapper.innerHTML += dom;
} else {
throw new TypeError('Please enter an existing selector.');
}
}
private aidedCreateStyle(): string {
const {
dragWrapperStyle,
dragOriginStyle,
dragOriginActiveStyle,
dragTargetActiveStyle,
} = SortDraggable.defaultProps;
const tempWrapperStyle = convertPairToCSSText(dragWrapperStyle);
const tempOriginStyle = convertPairToCSSText(dragOriginStyle);
const tempOriginActiveStyle = convertPairToCSSText(dragOriginActiveStyle);
const tempTargetActiveStyle = convertPairToCSSText(dragTargetActiveStyle);
const style: string = `
body, ul, li {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
#ddzy-drag-wrapper div {
box-sizing: border-box;
overflow: hidden;
}
#ddzy-drag-wrapper {
height: 100%;
${tempWrapperStyle}
}
.ddzy-drag-main {
heigth: 100%;
padding: 0.625rem;
}
.ddzy-drag-main-list {
display: flex;
flex-direction: column;
}
.ddzy-drag-list-item {
/* TODO: 传入配置 - gap */
display: flex;
flex-direction: row;
overflow: hidden;
cursor: move;
min-height: 2.5rem;
margin: 0.5rem 0;
background-color: #fff;
color: #303133;
${tempOriginStyle}
transition: .3s all ease;
}
.ddzy-drag-item-title-box {
flex: 1;
background-color: #d50;
pointer-events: none;
}
.ddzy-drag-item-title {
height: 100%;
line-height: 2.5;
color: #fff;
text-align: center;
}
.ddzy-drag-item-title img {
display: block;
max-width: 100%;
height: 100%;
}
.ddzy-drag-item-content-box {
flex: 5;
pointer-events: none;
}
.ddzy-drag-item-content {
padding-left: 0.5rem;
line-height: 2.5;
color: #666;
}
/* Active Classes(Configurations) */
.ddzy-drag-origin-active {
${tempOriginActiveStyle}
}
.ddzy-drag-target-active {
${tempTargetActiveStyle}
}
`;
return style;
}
private aidedMountStyle(
style: string,
): void {
let oStyle = document.querySelector('style');
if (oStyle) {
oStyle.innerText += `
/* Create by SortDraggable */
${style}
`;
}
else {
oStyle = document.createElement('style') as HTMLStyleElement;
oStyle.innerText += oStyle.innerText += `
/* Create by SortDraggable */
${style}
`;;
document.head.appendChild(oStyle);
}
}
private handleRenderDOM(): void {
const dom = this.aidedCreateDOM();
this.aidedMountDOM(dom);
}
private handleRenderStyle(): void {
const style = this.aidedCreateStyle();
this.aidedMountStyle(style);
}
/**
* drag相关的变量提取, 考虑到后续可能会用到
*/
private handleInitDragVarible(): void {
this.dragContainer = getEle(
'.ddzy-drag-main-list'
) as HTMLUListElement;
this.dragItems = Array.from(
getAllEle(
'.ddzy-drag-list-item'
) as ArrayLike<HTMLLIElement>
);
}
private handleDragAnimation(
target: HTMLElement,
): void {
const originDiffDistance = this.position.originAfterRect.top - this.position.originBeforeRect.top;
const targetDiffDistance = this.position.targetAfterRect.top - this.position.targetBeforeRect.top;
// ?: [animate] - 先置origin & target于原位(animate配置项必须)
setCss(this.origin, {
transition: 'none',
transform: `translateY(${-originDiffDistance}px)`,
});
setCss(target, {
transition: 'none',
transform: `translateY(${-targetDiffDistance}px)`,
});
addClass(target, 'ddzy-drag-target-active');
// ?: 由于origin移动到了新位置, 所以此处需更新其beforeRect
this.position.originBeforeRect = this.position.originAfterRect;
setTimeout(() => {
setCss(this.origin, {
transition: `all .3s ease`,
transform: `translateY(${0}px)`,
});
setCss(target, {
transition: `all .3s ease`,
transform: `translateY(${0}px)`,
});
}, 0);
}
private handleDragStart(
target: HTMLElement,
): void {
// 存储被拖拽元素
this.origin = target;
this.position.originBeforeRect = this.origin.getBoundingClientRect();
addClass(this.origin, 'ddzy-drag-origin-active');
}
private handleDragEnter(
target: HTMLElement,
): void {
const {
dragContainer,
} = this;
this.position.targetBeforeRect = target.getBoundingClientRect();
// 排序依据(移动方向)有两种方式
// 1. 递归(迭代)DOM树, 找origin & target的位置(√)
// 2. 维护一个DOM排序数组
const originIndex = SortDraggable._aidedFindIndex(this.origin, 0);
const targetIndex = SortDraggable._aidedFindIndex(target, 0);
const diff = targetIndex - originIndex;
diff > 0
? (
dragContainer.insertBefore(this.origin, (
target.nextElementSibling as HTMLLIElement
))
)
: (
dragContainer.insertBefore(this.origin, target)
);
// ?: insert后的新位置, `animate`时只需交换两者位置信息即可
this.position.originAfterRect = this.origin.getBoundingClientRect();
this.position.targetAfterRect = target.getBoundingClientRect();
}
private handleDragLeave(
target: HTMLElement,
): void {
removeClass(target, 'ddzy-drag-target-active');
}
private handleDragOver(
e: DragEvent,
): void {
e.preventDefault();
}
private handleDrop(): void {
removeClass(this.origin, 'ddzy-drag-origin-active');
removeClass(this.origin, 'ddzy-drag-target-active');
}
/**
* 处理拖拽相关
*/
private handleDrag(): void {
this.handleInitDragVarible();
const { dragItems } = this;
const {
animate,
onDragStartHook,
onDragEnterHook,
onDragOverHook,
onDragLeaveHook,
onDropHook,
} = SortDraggable.defaultProps;
dragItems.forEach((target) => {
setAttr(target, {
draggable: 'true',
});
target.addEventListener('dragstart', () => {
this.handleDragStart(target);
onDragStartHook(this.origin);
});
target.addEventListener('dragenter', () => {
this.handleDragEnter(target);
// ?: 是否启用过渡
animate && this.handleDragAnimation(target);
onDragEnterHook(this.origin, target);
});
target.addEventListener('dragleave', () => {
this.handleDragLeave(target);
onDragLeaveHook(this.origin, target);
});
target.addEventListener('dragover', (e) => {
this.handleDragOver(e);
onDragOverHook(this.origin, target);
});
target.addEventListener('drop', () => {
this.handleDrop();
onDropHook(this.origin);
});
});
}
private render(): void {
this.handleRenderDOM();
this.handleRenderStyle();
this.handleDrag();
}
}; | the_stack |
import { EJSON } from "bson";
import { promises } from "fs";
import { anything, capture, instance, mock, when } from "ts-mockito";
import { EventStream, Response, StitchRequestClient, Transport} from "../../../src";
import { BasicRequest } from "../../../src/internal/net/BasicRequest";
import ContentTypes from "../../../src/internal/net/ContentTypes";
import Headers from "../../../src/internal/net/Headers";
import Method from "../../../src/internal/net/Method";
import { StitchDocRequest } from "../../../src/internal/net/StitchDocRequest";
import { StitchRequest } from "../../../src/internal/net/StitchRequest";
import StitchError from "../../../src/StitchError";
import StitchServiceError from "../../../src/StitchServiceError";
import { StitchServiceErrorCode } from "../../../src/StitchServiceErrorCode";
/** @hidden */
// Mockito does not yet support mocking interfaces but it will soon
// - https://github.com/NagRock/ts-mockito/issues/117
export default class FakeTransport implements Transport {
public roundTrip(request: BasicRequest): Promise<Response> {
return Promise.reject("")
}
public stream(request: BasicRequest, open = true, retryRequest?: () => Promise<EventStream>): Promise<EventStream> {
return Promise.reject("")
}
}
describe("StitchRequestClientUnitTests", () => {
it("should doRequest", () => {
const domain = "http://domain.com";
const transportMock = mock(FakeTransport);
const transport = instance(transportMock);
const stitchRequestClient = new StitchRequestClient(domain, transport);
// A bad response should throw an exception
when(transportMock.roundTrip(anything())).thenResolve({
body: undefined,
headers: {},
statusCode: 500
});
const path = "/path";
const builder = new StitchRequest.Builder()
.withPath(path)
.withMethod(Method.GET);
return stitchRequestClient
.doRequest(builder.build())
.catch(error => {
expect(error instanceof StitchServiceError).toBeTruthy();
})
.then(() => {
const [actualRequest] = capture(transportMock.roundTrip).first();
const expectedRequest = new BasicRequest.Builder()
.withMethod(Method.GET)
.withUrl(domain + path)
.build();
expect(expectedRequest).toEqual(actualRequest);
// A normal response should be able to be decoded
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"hello": "world", "a": 42}',
headers: {},
statusCode: 200
});
return stitchRequestClient.doRequest(builder.build());
})
.then(response => {
expect(response.statusCode).toBe(200);
const expected = {
a: 42,
hello: "world"
};
expect(expected).toEqual(EJSON.parse(response.body!, { relaxed: true }));
// Error responses should be handled
when(transportMock.roundTrip(anything())).thenResolve({
headers: {},
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toContain("received unexpected status");
})
.then(() => {
when(transportMock.roundTrip(anything())).thenResolve({
body: "whoops",
headers: {},
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toEqual("whoops");
})
.then(() => {
const headers = {
[Headers.CONTENT_TYPE]: ContentTypes.APPLICATION_JSON
};
when(transportMock.roundTrip(anything())).thenResolve({
body: "whoops",
headers,
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toEqual("whoops");
})
.then(() => {
const headers = {
[Headers.CONTENT_TYPE]: ContentTypes.APPLICATION_JSON
};
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"error": "bad", "error_code": "InvalidSession"}',
headers,
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.InvalidSession);
expect(error.message).toEqual("bad");
})
.then(() => {
when(transport.roundTrip(anything())).thenReject(new StitchError());
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: Error) => {
expect(error).toBeDefined();
});
});
it("should test doJSONRequestWithDoc", () => {
const domain = "http://domain.com";
const transportMock = mock(FakeTransport);
const transport = instance(transportMock);
const stitchRequestClient = new StitchRequestClient(domain, transport);
const path = "/path";
const document = { my: 24 };
const builder = new StitchDocRequest.Builder();
builder.withDocument(document);
builder.withPath(path).withMethod(Method.PATCH);
// A bad response should throw an exception
when(transportMock.roundTrip(anything())).thenResolve({
headers: {},
statusCode: 500
});
return stitchRequestClient
.doRequest(builder.build())
.catch((error: StitchServiceError) => {
expect(error instanceof StitchServiceError).toBeTruthy();
const [actualRequest] = capture(transportMock.roundTrip).first();
const expectedHeaders = {
[Headers.CONTENT_TYPE_CANON]: ContentTypes.APPLICATION_JSON
};
const expectedRequest = new BasicRequest.Builder()
.withMethod(Method.PATCH)
.withUrl(domain + path)
.withBody('{"my":{"$numberInt":"24"}}')
.withHeaders(expectedHeaders)
.build();
expect(actualRequest).toEqual(expectedRequest);
// A normal response should be able to be decoded
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"hello": "world", "a": 42}',
headers: {},
statusCode: 200
});
return stitchRequestClient.doRequest(builder.build());
})
.then(response => {
expect(response.statusCode).toEqual(200);
const expected = {
a: 42,
hello: "world"
};
expect(EJSON.parse(response.body!, { relaxed: true })).toEqual(expected);
// Error responses should be handled
when(transportMock.roundTrip(anything())).thenResolve({
headers: {},
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toContain("received unexpected status");
})
.then(() => {
// Error responses should be handled
when(transportMock.roundTrip(anything())).thenResolve({
body: "whoops",
headers: {},
statusCode: 500
});
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toEqual("whoops");
})
.then(() => {
const headers = {
[Headers.CONTENT_TYPE]: ContentTypes.APPLICATION_JSON
};
when(transportMock.roundTrip(anything())).thenResolve({
body: "whoops",
headers,
statusCode: 500
});
stitchRequestClient.doRequest(builder.build());
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.Unknown);
expect(error.message).toEqual("whoops");
})
.then(() => {
const headers = {
[Headers.CONTENT_TYPE]: ContentTypes.APPLICATION_JSON
};
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"error": "bad", "error_code": "InvalidSession"}',
headers,
statusCode: 500
});
})
.catch((error: StitchServiceError) => {
expect(error.errorCode).toEqual(StitchServiceErrorCode.InvalidSession);
expect(error.message).toEqual("bad");
})
.then(() => {
when(transport.roundTrip(anything())).thenReject(new StitchError());
return stitchRequestClient.doRequest(builder.build());
})
.catch((error: Error) => {
expect(error).toBeDefined();
});
});
it("should handle non canonical headers", () => {
const domain = "http://domain.com";
const transportMock = mock(FakeTransport);
const transport = instance(transportMock);
const stitchRequestClient = new StitchRequestClient(domain, transport);
// A bad response should throw an exception
when(transportMock.roundTrip(anything())).thenResolve({
headers: {},
statusCode: 500
});
const path = "/path";
const builder = new StitchRequest.Builder()
.withPath(path)
.withMethod(Method.GET);
const headers = {
[Headers.CONTENT_TYPE]: ContentTypes.APPLICATION_JSON
};
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"error": "bad", "error_code": "InvalidSession"}',
headers,
statusCode: 502
});
expect(stitchRequestClient.doRequest(builder.build())).rejects.toEqual(
new StitchServiceError("bad", StitchServiceErrorCode.InvalidSession)
);
headers[Headers.CONTENT_TYPE_CANON] = ContentTypes.APPLICATION_JSON;
// A bad response should throw an exception
when(transportMock.roundTrip(anything())).thenResolve({
body: '{"error": "bad", "error_code": "InvalidSession"}',
headers,
statusCode: 500
});
expect(stitchRequestClient.doRequest(builder.build())).rejects.toEqual(
new StitchServiceError("bad", StitchServiceErrorCode.InvalidSession)
);
});
}); | the_stack |
import { FilterConditionType, FilterRelationType } from 'app/constants';
import { FilterSqlOperator } from 'globalConstants';
import ChartFilterCondition, {
ConditionBuilder,
} from '../ChartFilterCondition';
describe('ChartFilterCondition Tests', () => {
let initCondition;
beforeEach(() => {
initCondition = new ChartFilterCondition();
initCondition.name = 'init-condition';
initCondition.type = FilterConditionType.Filter;
initCondition.visualType = 'STRING';
initCondition.operator = FilterSqlOperator.In;
});
test('should init filter condition model', () => {
const condition = new ChartFilterCondition();
expect(condition).not.toBeNull();
expect(condition.name).toEqual('');
expect(condition.type).toEqual(FilterConditionType.Filter);
expect(condition.value).toEqual(undefined);
expect(condition.visualType).toEqual('');
expect(condition.operator).toEqual(undefined);
expect(condition.children).toEqual(undefined);
});
test('should init filter condition model with default filter type', () => {
initCondition.type = undefined;
const condition = new ChartFilterCondition(initCondition);
expect(condition.type).toEqual(FilterConditionType.Filter);
});
test('should set condition model value', () => {
const condition = new ChartFilterCondition();
condition.setValue('value');
expect(condition.value).toEqual('value');
condition.setType(FilterConditionType.List);
expect(condition.type).toEqual(FilterConditionType.List);
condition.setOperator('IN');
expect(condition.operator).toEqual('IN');
});
test('should init filter condition model by old condition', () => {
const grandsonCondition = new ChartFilterCondition();
grandsonCondition.name = 'grandson-condition';
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
childCondition.children = [grandsonCondition];
const oldCondition = new ChartFilterCondition();
oldCondition.name = 'condition';
oldCondition.visualType = 'STRING';
oldCondition.setValue('old');
oldCondition.setType(FilterConditionType.Time);
oldCondition.setOperator('EQ');
oldCondition.children = [childCondition];
const condition = new ChartFilterCondition(oldCondition);
expect(condition.name).toEqual('condition');
expect(condition.children?.[0].name).toEqual('child-condition');
expect(condition.children?.[0].children?.[0].name).toEqual(
'grandson-condition',
);
});
test('should append into condition when condition is relation type and no child', () => {
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.appendChild();
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.children?.length).toEqual(1);
expect(condition.children?.[0].name).toEqual('init-condition');
expect(condition.children?.[0].type).toEqual(FilterConditionType.Filter);
});
test('should append into condition when condition is relation type', () => {
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [childCondition];
condition.appendChild(1);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.children?.length).toEqual(2);
expect(condition.children?.[0].name).toEqual('child-condition');
expect(condition.children?.[0].type).toEqual(FilterConditionType.Filter);
});
test('should expand filter into two children when condition is not relation type', () => {
const condition = initCondition;
condition.setType(FilterConditionType.List);
condition.value = 'a';
condition.appendChild();
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.value).toEqual(FilterRelationType.AND);
expect(condition.children?.length).toEqual(2);
expect(condition.children?.[0].name).toEqual('init-condition');
expect(condition.children?.[0].type).toEqual(FilterConditionType.Filter);
expect(condition.children?.[0].value).toEqual('a');
expect(condition.children?.[0].operator).toEqual('IN');
expect(condition.children?.[1].name).toEqual('init-condition');
expect(condition.children?.[1].type).toEqual(FilterConditionType.Filter);
expect(condition.children?.[1].value).toEqual('a');
expect(condition.children?.[1].operator).toEqual('IN');
});
test('should not append into condition when index below zero', () => {
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [childCondition];
condition.appendChild(-1);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.children?.length).toEqual(1);
expect(condition.children?.[0].name).toEqual(childCondition.name);
expect(condition.children?.[0].type).toEqual(childCondition.type);
});
test('should update condition child by index', () => {
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
const newChildCondition = new ChartFilterCondition();
newChildCondition.name = 'new-child-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [childCondition, childCondition];
condition.updateChild(1, newChildCondition);
expect(condition.children?.length).toEqual(2);
expect(condition.children?.[0].name).toEqual('child-condition');
expect(condition.children?.[0].type).toEqual(FilterConditionType.Filter);
expect(condition.children?.[1].name).toEqual('new-child-condition');
expect(condition.children?.[0].type).toEqual(FilterConditionType.Filter);
});
test('should not update condition child when child is empty', () => {
const newChildCondition = new ChartFilterCondition();
newChildCondition.name = 'new-child-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.updateChild(1, newChildCondition);
expect(condition.children?.length).toEqual(undefined);
});
test('should replace current condition by child when only two children', () => {
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
const newChildCondition = new ChartFilterCondition();
newChildCondition.name = 'new-child-condition';
newChildCondition.operator = 'BETWEEN';
newChildCondition.value = '1';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [childCondition, newChildCondition];
condition.removeChild(0);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Filter);
expect(condition.operator).toEqual(newChildCondition.operator);
expect(condition.value).toEqual(newChildCondition.value);
expect(condition.children?.length).toEqual(0);
});
test('should replace current condition by child when children more than two', () => {
const firstCondition = new ChartFilterCondition();
firstCondition.name = 'first-condition';
const secondCondition = new ChartFilterCondition();
secondCondition.name = 'second-condition';
const thirdCondition = new ChartFilterCondition();
secondCondition.name = 'third-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [firstCondition, secondCondition, thirdCondition];
condition.removeChild(0);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.operator).toEqual(condition.operator);
expect(condition.value).toEqual(condition.value);
expect(condition.children?.length).toEqual(2);
expect(condition.children?.[0]).toEqual(secondCondition);
expect(condition.children?.[1]).toEqual(thirdCondition);
});
test('should not remove anything when child is less than two', () => {
const firstCondition = new ChartFilterCondition();
firstCondition.name = 'first-condition';
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.children = [firstCondition];
condition.removeChild(0);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.operator).toEqual(condition.operator);
expect(condition.value).toEqual(condition.value);
expect(condition.children?.length).toEqual(1);
expect(condition.children?.[0]).toEqual(firstCondition);
});
test('should not remove anything when child is empty', () => {
const condition = initCondition;
condition.setType(FilterConditionType.Relation);
condition.removeChild(0);
expect(condition.name).toEqual('init-condition');
expect(condition.type).toEqual(FilterConditionType.Relation);
expect(condition.operator).toEqual(condition.operator);
expect(condition.value).toEqual(condition.value);
expect(condition.children?.length).toEqual(undefined);
});
});
describe('ConditionBuilder Tests', () => {
let initCondition;
beforeEach(() => {
initCondition = new ChartFilterCondition();
initCondition.name = 'init-condition';
initCondition.type = FilterConditionType.Filter;
initCondition.visualType = 'STRING';
initCondition.operator = FilterSqlOperator.In;
});
test('should init builder', () => {
const builder = new ConditionBuilder();
builder.setName('filter');
builder.setSqlType('NUMERIC');
builder.setValue(1);
builder.setOperator('IN');
const condition = builder.asSelf();
expect(condition.name).toEqual('filter');
expect(condition.visualType).toEqual('NUMERIC');
expect(condition.value).toEqual(1);
expect(condition.operator).toEqual('IN');
});
test('should init builder by condition filter', () => {
const childCondition = new ChartFilterCondition();
childCondition.name = 'child-condition';
const condition = new ChartFilterCondition(initCondition);
condition.setType(FilterConditionType.Relation);
condition.children = [childCondition];
const builder = new ConditionBuilder(condition);
expect(builder.asSelf().name).toEqual(condition.name);
expect(builder.asSelf().visualType).toEqual(condition.visualType);
expect(builder.asSelf().type).toEqual(condition.type);
expect(builder.asSelf().value).toEqual(condition.value);
expect(builder.asSelf().operator).toEqual(condition.operator);
expect(builder.asSelf().children).toEqual(condition.children);
});
test('should get condition from asFilter', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asFilter();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Filter);
});
test('should get condition from asFilter with condition type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asFilter(FilterConditionType.RangeTime);
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.RangeTime);
});
test('should get condition from asRelation', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRelation();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Relation);
});
test('should get condition from asRelation with value and children', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRelation('value', [initCondition]);
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.value).toEqual('value');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Relation);
expect(newCondition.children).toEqual([initCondition]);
});
test('should get condition from asRangeTime', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRangeTime();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(FilterSqlOperator.Between);
expect(newCondition.type).toEqual(FilterConditionType.RangeTime);
});
test('should get condition from asRangeTime with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRangeTime('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(FilterSqlOperator.Between);
expect(newCondition.type).toEqual(FilterConditionType.RangeTime);
});
test('should get condition from asRecommendTime', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRecommendTime();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(FilterSqlOperator.Between);
expect(newCondition.type).toEqual(FilterConditionType.RecommendTime);
});
test('should get condition from asRecommendTime with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asRecommendTime('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(FilterSqlOperator.Between);
expect(newCondition.type).toEqual(FilterConditionType.RecommendTime);
});
test('should get condition from asGeneral', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asGeneral();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.List);
});
test('should get condition from asGeneral with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asGeneral('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.List);
});
test('should get condition from asCustomize', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asCustomize();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Customize);
});
test('should get condition from asCustomize with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asCustomize('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Customize);
});
test('should get condition from asCondition', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asCondition();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Condition);
});
test('should get condition from asCondition with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asCondition('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Condition);
});
test('should get condition from asSingleOrRangeValue when init condition type is not between like', () => {
initCondition.operator = FilterSqlOperator.Contain;
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asSingleOrRangeValue();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Value);
});
test('should get condition from asSingleOrRangeValue when init condition type is BETWEEN', () => {
initCondition.operator = FilterSqlOperator.Between;
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asSingleOrRangeValue();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.RangeValue);
});
test('should get condition from asSingleOrRangeValue when init condition type is NOT_BETWEEN', () => {
initCondition.operator = FilterSqlOperator.NotBetween;
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asSingleOrRangeValue();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.RangeValue);
});
test('should get condition from asSingleOrRangeValue with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asSingleOrRangeValue('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Value);
});
test('should get condition from asTree', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asTree();
expect(newCondition.name).toEqual(initCondition.name);
expect(newCondition.visualType).toEqual(initCondition.visualType);
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Tree);
});
test('should get condition from asTree with name and sql type', () => {
const builder = new ConditionBuilder(initCondition);
const newCondition = builder.asTree('newName', 'NUMERIC');
expect(newCondition.name).toEqual('newName');
expect(newCondition.visualType).toEqual('NUMERIC');
expect(newCondition.operator).toEqual(initCondition.operator);
expect(newCondition.type).toEqual(FilterConditionType.Tree);
});
}); | the_stack |
import { camelcaseKeysDeep } from 'messaging-api-common';
import { Event } from '../context/Event';
import {
EventAccountLinking,
EventAppRoles,
EventBrandedCamera,
EventCheckoutUpdate,
EventDelivery,
EventGamePlay,
EventMessage,
EventMessageAttachment,
EventMessageQuickReply,
EventOptin,
EventPassThreadControl,
EventPayment,
EventPolicyEnforcement,
EventPostback,
EventPreCheckout,
EventReaction,
EventRead,
EventReferral,
EventRequestThreadControl,
EventTakeThreadControl,
FallbackAttachment,
LocationAttachmentPayload,
MediaAttachmentPayload,
MessengerEventOptions,
MessengerRawEvent,
} from './MessengerTypes';
export default class MessengerEvent implements Event<MessengerRawEvent> {
_rawEvent: MessengerRawEvent;
_isStandby: boolean;
_pageId: string | null;
constructor(
rawEvent: MessengerRawEvent,
options: MessengerEventOptions = {}
) {
this._rawEvent = rawEvent;
this._isStandby = options.isStandby || false;
this._pageId = options.pageId || null;
}
/**
* Underlying raw event from Messenger.
*
*/
get rawEvent(): MessengerRawEvent {
return this._rawEvent;
}
/**
* The timestamp when the event was sent.
*
*/
get timestamp(): number {
return this._rawEvent.timestamp;
}
/**
* Determine if the event is a message event.
*
*/
get isMessage(): boolean {
return (
'message' in this._rawEvent && typeof this._rawEvent.message === 'object'
);
}
/**
* The message object from Messenger raw event.
*
*/
get message(): EventMessage | null {
if ('message' in this._rawEvent) {
return this._rawEvent.message;
}
return null;
}
/**
* Determine if the event is a message event which includes text.
*
*/
get isText(): boolean {
return this.isMessage && typeof this.message!.text === 'string';
}
/**
* The text string from Messenger raw event.
*
*/
get text(): string | null {
if (this.isText) {
return this.message!.text || null;
}
return null;
}
/**
* Determine if the event has any attachments.
*
*/
get hasAttachment(): boolean {
return (
this.isMessage &&
!!this.message!.attachments &&
this.message!.attachments.length > 0
);
}
/**
* The attachments array from Messenger raw event.
*
*/
get attachments(): EventMessageAttachment[] | null {
if (this.message && this.message.attachments) {
return this.message.attachments;
}
return null;
}
/**
* Determine if the event is a message event which includes image attachment.
*
*/
get isImage(): boolean {
return this.hasAttachment && this.attachments![0].type === 'image';
}
/**
* The image attachment from Messenger raw event.
*
*/
get image(): MediaAttachmentPayload | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'image') {
return attachment.payload;
}
return null;
}
/**
* Determine if the event is a message event which includes audio attachment.
*
*/
get isAudio(): boolean {
return this.hasAttachment && this.attachments![0].type === 'audio';
}
/**
* The audio attachment from Messenger raw event.
*
*/
get audio(): MediaAttachmentPayload | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'audio') {
return attachment.payload;
}
return null;
}
/**
* Determine if the event is a message event which includes video attachment.
*
*/
get isVideo(): boolean {
return this.hasAttachment && this.attachments![0].type === 'video';
}
/**
* The video attachment from Messenger raw event.
*
*/
get video(): MediaAttachmentPayload | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'video') {
return attachment.payload;
}
return null;
}
/**
* Determine if the event is a message event which includes location attachment.
*
*/
get isLocation(): boolean {
return this.hasAttachment && this.attachments![0].type === 'location';
}
/**
* The location attachment from Messenger raw event.
*
*/
get location(): LocationAttachmentPayload | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'location') {
return attachment.payload;
}
return null;
}
/**
* Determine if the event is a message event which includes file attachment.
*
*/
get isFile(): boolean {
return this.hasAttachment && this.attachments![0].type === 'file';
}
/**
* The file attachment from Messenger raw event.
*
*/
get file(): MediaAttachmentPayload | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'file') {
return attachment.payload;
}
return null;
}
/**
* Determine if the event is a message event which includes fallback attachment.
*
*/
get isFallback(): boolean {
return this.hasAttachment && this.attachments![0].type === 'fallback';
}
/**
* The fallback attachment from Messenger raw event.
*
*/
get fallback(): FallbackAttachment | null {
if (!this.hasAttachment) {
return null;
}
const attachment = this.attachments![0];
if (attachment.type === 'fallback') {
return attachment;
}
return null;
}
/**
* Determine if the event is a message event which includes sticker.
*
*/
get isSticker(): boolean {
return this.isMessage && typeof this.message!.stickerId === 'number';
}
/**
* The stickerId from Messenger raw event.
*
*/
get sticker(): number | null {
if (this.isSticker) {
return this.message!.stickerId || null;
}
return null;
}
/**
* Determine if the event is a message event which includes 'like' sticker.
* id 369239263222822 is a small like sticker
* id 369239263222814 is a large like sticker
* id 369239263222810 is a huge like sticker
*/
get isLikeSticker(): boolean {
return (
this.isSticker &&
(this.message!.stickerId === 369239263222822 ||
this.message!.stickerId === 369239343222814 ||
this.message!.stickerId === 369239383222810)
);
}
/**
* Determine if the event is a message event triggered from quick reply.
*
*/
get isQuickReply(): boolean {
return (
this.isMessage &&
!!this.message!.quickReply &&
typeof this.message!.quickReply === 'object'
);
}
/**
* The quick reply object from Messenger raw event.
*
*/
get quickReply(): EventMessageQuickReply | null {
if (this.message && this.message.quickReply) {
return this.message.quickReply;
}
return null;
}
/**
* Determine if the event is a message event sent from our side.
*
*/
get isEcho(): boolean {
return this.isMessage && !!this.message!.isEcho;
}
/**
* Determine if the event is a postback event.
*
*/
get isPostback(): boolean {
return (
'postback' in this._rawEvent &&
typeof this._rawEvent.postback === 'object'
);
}
/**
* The postback object from Messenger raw event.
*
*/
get postback(): EventPostback | null {
if ('postback' in this._rawEvent) {
return this._rawEvent.postback;
}
return null;
}
/**
* Determine if the event is a game_play event.
*
*/
get isGamePlay(): boolean {
return (
'gamePlay' in this._rawEvent &&
typeof this._rawEvent.gamePlay === 'object'
);
}
/**
* The gamePlay object from Messenger raw event.
*
*/
get gamePlay(): EventGamePlay | null {
if (!('gamePlay' in this._rawEvent)) {
return null;
}
const rawGamePlay = this._rawEvent.gamePlay;
let payload;
try {
const parsed = JSON.parse(rawGamePlay.payload);
payload =
parsed && typeof parsed === 'object'
? camelcaseKeysDeep(parsed)
: parsed;
} catch (err) {
payload = rawGamePlay.payload;
}
return {
...rawGamePlay,
payload,
};
}
/**
* Determine if the event is an opt-in event.
*
*/
get isOptin(): boolean {
return (
'optin' in this._rawEvent && typeof this._rawEvent.optin === 'object'
);
}
/**
* The optin object from Messenger raw event.
*
*/
get optin(): EventOptin | null {
if ('optin' in this._rawEvent) {
return this._rawEvent.optin;
}
return null;
}
/**
* Determine if the event is a payment event.
*
*/
get isPayment(): boolean {
return (
'payment' in this._rawEvent && typeof this._rawEvent.payment === 'object'
);
}
/**
* The payment object from Messenger raw event.
*
*/
get payment(): EventPayment | null {
if ('payment' in this._rawEvent) {
return this._rawEvent.payment;
}
return null;
}
/**
* Determine if the event is a checkout update event.
*
*/
get isCheckoutUpdate(): boolean {
return (
'checkoutUpdate' in this._rawEvent &&
typeof this._rawEvent.checkoutUpdate === 'object'
);
}
/**
* The checkoutUpdate object from Messenger raw event.
*
*/
get checkoutUpdate(): EventCheckoutUpdate | null {
if ('checkoutUpdate' in this._rawEvent) {
return this._rawEvent.checkoutUpdate;
}
return null;
}
/**
* Determine if the event is a pre-checkout event.
*
*/
get isPreCheckout(): boolean {
return (
'preCheckout' in this._rawEvent &&
typeof this._rawEvent.preCheckout === 'object'
);
}
/**
* The preCheckout object from Messenger raw event.
*
*/
get preCheckout(): EventPreCheckout | null {
if ('preCheckout' in this._rawEvent) {
return this._rawEvent.preCheckout;
}
return null;
}
/**
* Determine if the event is a message read event.
*
*/
get isRead(): boolean {
return 'read' in this._rawEvent && typeof this._rawEvent.read === 'object';
}
/**
* The read object from Messenger raw event.
*
*/
get read(): EventRead | null {
if ('read' in this._rawEvent) {
return this._rawEvent.read;
}
return null;
}
/**
* Determine if the event is a message delivery event.
*
*/
get isDelivery(): boolean {
return (
'delivery' in this._rawEvent &&
typeof this._rawEvent.delivery === 'object'
);
}
/**
* The delivery object from Messenger raw event.
*
*/
get delivery(): EventDelivery | null {
if ('delivery' in this._rawEvent) {
return this._rawEvent.delivery;
}
return null;
}
/**
* Determine if the event is a postback or quick reply which includes payload.
*
*/
get isPayload(): boolean {
return (
(!!this.postback && typeof this.postback.payload === 'string') ||
(!!this.quickReply && typeof this.quickReply.payload === 'string')
);
}
/**
* The payload received from postback or quick reply.
*
*/
get payload(): string | null {
if (!!this.postback && this.isPayload) {
return this.postback.payload || null;
}
if (!!this.quickReply && this.isPayload) {
return this.quickReply.payload || null;
}
return null;
}
/**
* Determine if the event is a policy enforcement event.
*
*/
get isPolicyEnforcement(): boolean {
return (
'policy-enforcement' in this._rawEvent &&
typeof this._rawEvent['policy-enforcement'] === 'object'
);
}
/**
* The policy enforcement object from Messenger raw event.
*
*/
get policyEnforcement(): EventPolicyEnforcement | null {
if ('policy-enforcement' in this._rawEvent) {
return this._rawEvent['policy-enforcement'];
}
return null;
}
/**
* Determine if the event is an app roles event.
*
*/
get isAppRoles(): boolean {
return (
'appRoles' in this._rawEvent &&
typeof this._rawEvent.appRoles === 'object'
);
}
/**
* The app roles object from Messenger raw event.
*
*/
get appRoles(): EventAppRoles | null {
if ('appRoles' in this._rawEvent) {
return this._rawEvent.appRoles;
}
return null;
}
/**
* Determine if the event is a standby event.
*
*/
get isStandby(): boolean {
return this._isStandby;
}
/**
* Determine if the event is a pass thread control event.
*
*/
get isPassThreadControl(): boolean {
return (
'passThreadControl' in this._rawEvent &&
typeof this._rawEvent.passThreadControl === 'object'
);
}
/**
* The pass thread control object from Messenger raw event.
*
*/
get passThreadControl(): EventPassThreadControl | null {
if ('passThreadControl' in this._rawEvent) {
return this._rawEvent.passThreadControl;
}
return null;
}
/**
* Determine if the event is a take thread control event.
*
*/
get isTakeThreadControl(): boolean {
return (
'takeThreadControl' in this._rawEvent &&
typeof this._rawEvent.takeThreadControl === 'object'
);
}
/**
* The take thread control object from Messenger raw event.
*
*/
get takeThreadControl(): EventTakeThreadControl | null {
if ('takeThreadControl' in this._rawEvent) {
return this._rawEvent.takeThreadControl;
}
return null;
}
/**
* Determine if the event is a request thread control event.
*
*/
get isRequestThreadControl(): boolean {
return (
'requestThreadControl' in this._rawEvent &&
typeof this._rawEvent.requestThreadControl === 'object'
);
}
/**
* Determine if the event is a request thread control event sent by facebook integrated 'Page Inbox' (appId is 263902037430900).
*
*/
get isRequestThreadControlFromPageInbox(): boolean {
return (
'requestThreadControl' in this._rawEvent &&
typeof this._rawEvent.requestThreadControl === 'object' &&
this._rawEvent.requestThreadControl.requestedOwnerAppId ===
263902037430900
);
}
/**
* The take thread control object from Messenger raw event.
*
*/
get requestThreadControl(): EventRequestThreadControl | null {
if ('requestThreadControl' in this._rawEvent) {
return this._rawEvent.requestThreadControl;
}
return null;
}
/**
* Determine if the event is from customer chat plugin.
*
*/
get isFromCustomerChatPlugin(): boolean {
const isMessageFromCustomerChatPlugin = !!(
this.isMessage &&
'tags' in this.message! &&
this.message!.tags!.length !== 0 &&
this.message!.tags!.some((tag) => tag.source === 'customer_chat_plugin')
);
const isReferralFromCustomerChatPlugin = !!(
this.isReferral &&
this.referral &&
this.referral.source === 'CUSTOMER_CHAT_PLUGIN'
);
return isMessageFromCustomerChatPlugin || isReferralFromCustomerChatPlugin;
}
/**
* Determine if the event is a referral event.
*
*/
get isReferral(): boolean {
return !!(
'referral' in this._rawEvent ||
('postback' in this._rawEvent && this._rawEvent.postback.referral)
);
}
/**
* The referral object from Messenger event.
*
*/
get referral(): EventReferral | null {
if (!this.isReferral) {
return null;
}
if ('referral' in this._rawEvent) {
return this._rawEvent.referral;
}
if ('postback' in this._rawEvent && 'referral' in this._rawEvent.postback) {
return this._rawEvent.postback.referral || null;
}
return null;
}
/**
* The ref string from Messenger event.
*
*/
get ref(): string | null {
if (!this.isReferral) {
return null;
}
return this.referral && this.referral.ref;
}
/**
* The pageId of the Page where this Messenger event is happening on.
*
*/
get pageId(): string | null {
return this._pageId || null;
}
/**
* Determine if the event is a branded_camera event.
*
*/
get isBrandedCamera(): boolean {
return (
'brandedCamera' in this._rawEvent &&
typeof this._rawEvent.brandedCamera === 'object'
);
}
/**
* The brandedCamera object from Messenger event.
*
*/
get brandedCamera(): EventBrandedCamera | null {
if ('brandedCamera' in this._rawEvent) {
return this._rawEvent.brandedCamera;
}
return null;
}
/**
* Determine if the event is a account_linking event.
*
*/
get isAccountLinking(): boolean {
return (
'accountLinking' in this._rawEvent &&
typeof this._rawEvent.accountLinking === 'object'
);
}
/**
* The accountLinking object from Messenger event.
*
*/
get accountLinking(): EventAccountLinking | null {
if ('accountLinking' in this._rawEvent) {
return this._rawEvent.accountLinking;
}
return null;
}
/**
* Determine if the event is a reaction event.
*
*/
get isReaction(): boolean {
return (
'reaction' in this._rawEvent &&
typeof this._rawEvent.reaction === 'object'
);
}
/**
* The reaction object from Messenger event.
*
*/
get reaction(): EventReaction | null {
if ('reaction' in this._rawEvent) {
return this._rawEvent.reaction;
}
return null;
}
} | the_stack |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Components, registerComponent, mergeWithComponents } from '../../lib/vulcan-lib';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import SimpleSchema from 'simpl-schema';
import { isEmptyValue, getNullValue } from '../../lib/vulcan-forms/utils';
import Tooltip from '@material-ui/core/Tooltip';
class FormComponent extends Component<any,any> {
constructor(props) {
super(props);
this.state = {};
}
UNSAFE_componentWillMount() {
if (this.showCharsRemaining()) {
const value = this.getValue();
this.updateCharacterCount(value);
}
}
shouldComponentUpdate(nextProps, nextState) {
// allow custom controls to determine if they should update
if (this.isCustomInput(this.getInputType(nextProps))) {
return true;
}
const { currentValues, deletedValues, errors } = nextProps;
const path = this.getPath(this.props);
// when checking for deleted values, both current path ('foo') and child path ('foo.0.bar') should trigger updates
const includesPathOrChildren = deletedValues =>
deletedValues.some(deletedPath => deletedPath.includes(path));
const valueChanged =
!isEqual(get(currentValues, path), get(this.props.currentValues, path));
const errorChanged = !isEqual(this.getErrors(errors), this.getErrors());
const deleteChanged =
includesPathOrChildren(deletedValues) !==
includesPathOrChildren(this.props.deletedValues);
const charsChanged = nextState.charsRemaining !== this.state.charsRemaining;
const disabledChanged = nextProps.disabled !== this.props.disabled;
const shouldUpdate =
valueChanged ||
errorChanged ||
deleteChanged ||
charsChanged ||
disabledChanged;
return shouldUpdate;
}
/*
If this is an intl input, get _intl field instead
*/
getPath = (props?: any) => {
const p = props || this.props;
return p.path;
};
/*
Returns true if the passed input type is a custom
*/
isCustomInput = inputType => {
const isStandardInput = [
'nested',
'number',
'url',
'email',
'textarea',
'checkbox',
'checkboxgroup',
'select',
'datetime',
'date',
'text'
].includes(inputType);
return !isStandardInput;
};
/*
Function passed to form controls (always controlled) to update their value
*/
handleChange = value => {
// if value is an empty string, delete the field
if (value === '') {
value = null;
}
// if this is a number field, convert value before sending it up to Form
if (this.getFieldType() === Number && value != null) {
value = Number(value);
}
const updateValue = this.props.locale
? { locale: this.props.locale, value }
: value;
this.props.updateCurrentValues({ [this.getPath()]: updateValue });
// for text fields, update character count on change
if (this.showCharsRemaining()) {
this.updateCharacterCount(value);
}
};
/*
Updates the state of charsCount and charsRemaining as the users types
*/
updateCharacterCount = value => {
const characterCount = value ? value.length : 0;
this.setState({
charsRemaining: this.props.max - characterCount,
charsCount: characterCount
});
};
/*
Get value from Form state through document and currentValues props
*/
getValue = (props?: any, context?: any) => {
const p = props || this.props;
const c = context || this.context;
const { locale, defaultValue, deletedValues, formType, datatype } = p;
const path = locale ? `${this.getPath(p)}.value` : this.getPath(p);
const currentDocument = c.getDocument();
let value = get(currentDocument, path);
// note: force intl fields to be treated like strings
const nullValue = locale ? '' : getNullValue(datatype);
// handle deleted & empty value
if (deletedValues.includes(path)) {
value = nullValue;
} else if (isEmptyValue(value)) {
// replace empty value by the default value from the schema if it exists – for new forms only
value = formType === 'new' && defaultValue ? defaultValue : nullValue;
}
return value;
};
/*
Whether to keep track of and show remaining chars
*/
showCharsRemaining = (props?: any) => {
const p = props || this.props;
return (
p.max && ['url', 'email', 'textarea', 'text'].includes(this.getInputType(p))
);
};
/*
Get errors from Form state through context
Note: we use `includes` to get all errors from nested components, which have longer paths
*/
getErrors = (errors?: any) => {
errors = errors || this.props.errors;
const fieldErrors = errors.filter(
error => error.path && error.path.includes(this.props.path)
);
return fieldErrors;
};
/*
Get form input type, either based on input props, or by guessing based on form field type
*/
getInputType = (props?: any) => {
const p = props || this.props;
const fieldType = this.getFieldType();
const autoType =
fieldType === Number
? 'number'
: fieldType === Boolean
? 'checkbox'
: fieldType === Date
? 'date'
: 'text';
return p.input || autoType;
};
/*
Function passed to form controls to clear their contents (set their value to null)
*/
clearField = event => {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.props.updateCurrentValues({ [this.props.path]: null });
if (this.showCharsRemaining()) {
this.updateCharacterCount(null);
}
};
/*
Function passed to FormComponentInner to help with rendering the component
*/
getFormInput = () => {
const inputType = this.getInputType();
const FormComponents = mergeWithComponents(this.props.formComponents);
// if input is a React component, use it
if (typeof this.props.input === 'function') {
const InputComponent = this.props.input;
return InputComponent;
} else {
// else pick a predefined component
switch (inputType) {
case 'text':
return FormComponents.FormComponentDefault;
case 'number':
return FormComponents.FormComponentNumber;
case 'url':
return FormComponents.FormComponentUrl;
case 'email':
return FormComponents.FormComponentEmail;
case 'textarea':
return FormComponents.FormComponentTextarea;
case 'checkbox':
return FormComponents.FormComponentCheckbox;
case 'checkboxgroup':
return FormComponents.FormComponentCheckboxGroup;
case 'radiogroup':
return FormComponents.FormComponentRadioGroup
case 'select':
return FormComponents.FormComponentSelect;
case 'datetime':
return FormComponents.FormComponentDateTime;
case 'date':
return FormComponents.FormComponentDate;
default:
if (this.props.input && FormComponents[this.props.input]) {
return FormComponents[this.props.input];
} else if (this.isArrayField()) {
return Components.FormNestedArray;
} else if (this.isObjectField()) {
return FormComponents.FormNestedObject;
} else {
return FormComponents.FormComponentDefault;
}
}
}
};
/*
Get field field value type
*/
getFieldType = () => {
return this.props.datatype[0].type;
};
isArrayField = () => {
return this.getFieldType() === Array;
};
isObjectField = () => {
return this.getFieldType() instanceof SimpleSchema;
};
render() {
const FormComponents = mergeWithComponents(this.props.formComponents);
if (!this.props.input && this.props.nestedInput) {
if (this.isArrayField()) {
return (
<FormComponents.FormNestedArray
{...this.props}
formComponents={FormComponents}
errors={this.getErrors()}
value={this.getValue()}
/>
);
} else if (this.isObjectField()) {
return (
<FormComponents.FormNestedObject
{...this.props}
formComponents={FormComponents}
errors={this.getErrors()}
value={this.getValue()}
/>
);
}
}
const formComponent = (
<FormComponents.FormComponentInner
{...this.props}
{...this.state}
inputType={this.getInputType()}
value={this.getValue()}
errors={this.getErrors()}
document={this.context.getDocument()}
showCharsRemaining={!!this.showCharsRemaining()}
onChange={this.handleChange}
clearField={this.clearField}
formInput={this.getFormInput()}
formComponents={FormComponents}
/>
);
if (this.props.tooltip) {
return <Tooltip title={this.props.tooltip} placement="left-start">
<div>{ formComponent }</div>
</Tooltip>
} else {
return formComponent;
}
}
}
(FormComponent as any).propTypes = {
document: PropTypes.object,
name: PropTypes.string.isRequired,
label: PropTypes.string,
value: PropTypes.any,
placeholder: PropTypes.string,
prefilledValue: PropTypes.any,
options: PropTypes.any,
input: PropTypes.any,
datatype: PropTypes.any,
path: PropTypes.string.isRequired,
disabled: PropTypes.bool,
nestedSchema: PropTypes.object,
currentValues: PropTypes.object.isRequired,
deletedValues: PropTypes.array.isRequired,
throwError: PropTypes.func.isRequired,
updateCurrentValues: PropTypes.func.isRequired,
errors: PropTypes.array.isRequired,
addToDeletedValues: PropTypes.func,
clearFieldErrors: PropTypes.func.isRequired,
currentUser: PropTypes.object,
tooltip: PropTypes.string,
};
(FormComponent as any).contextTypes = {
getDocument: PropTypes.func.isRequired
};
const FormComponentComponent = registerComponent('FormComponent', FormComponent);
declare global {
interface ComponentTypes {
FormComponent: typeof FormComponentComponent
}
} | the_stack |
import { dirname, join, basename } from "path";
import { readJSON, pathExists, pathExistsSync } from "fs-extra";
import { Nullable } from "../../../shared/types";
import {
Texture, SceneLoader, Light, Node, Material, ShadowGenerator, CascadedShadowGenerator,
Camera, SerializationHelper, Mesh, MultiMaterial, TransformNode, ParticleSystem, Sound, CubeTexture,
AnimationGroup, Constants, MorphTargetManager, Matrix, SceneLoaderFlags, BaseTexture,
} from "babylonjs";
import { MeshesAssets } from "../assets/meshes";
import { PrefabAssets } from "../assets/prefabs";
import { GraphAssets } from "../assets/graphs";
import { Editor } from "../editor";
import { Overlay } from "../gui/overlay";
import { Tools } from "../tools/tools";
import { KTXTools } from "../tools/ktx";
import { SceneSettings } from "../scene/settings";
import { Project } from "./project";
import { IProject } from "./typings";
import { FilesStore } from "./files";
import { WorkSpace } from "./workspace";
import { ProjectHelpers } from "./helpers";
import { Assets } from "../components/assets";
export class ProjectImporter {
/**
* Imports the project located at the given path.
* @param editor the editor reference.
* @param path the path of the project to import.
*/
public static async ImportProject(editor: Editor, path: string): Promise<void> {
try {
await this._ImportProject(editor, path);
} catch (e) {
// TODO.
this._RefreshEditor(editor);
}
}
/**
* Imports the project located at the given path.
*/
private static async _ImportProject(editor: Editor, path: string): Promise<void> {
// Log
editor.console.logSection("Loading Project");
// Prepare overlay
Overlay.Show("Importing Project...", true);
// Configure Serialization Helper
this._OverrideTextureParser();
// Configure editor project
Project.Path = path;
Project.DirPath = `${dirname(path)}/`;
// Read project file
const project = await readJSON(path) as IProject;
const rootUrl = join(Project.DirPath!, "/");
Overlay.SetSpinnervalue(0);
const spinnerStep = 1 / (
project.textures.length + project.materials.length + project.meshes.length + project.lights.length +
project.cameras.length + (project.particleSystems?.length ?? 0) + (project.sounds?.length ?? 0) +
(project.transformNodes?.length ?? 0) + (project.scene.morphTargetManagers?.length ?? 0)
);
let spinnerValue = 0;
let loadPromises: Promise<void>[] = [];
// Register files
project.filesList.forEach((f) => {
const path = join(Project.DirPath!, "files", f);
FilesStore.List[path] = { path, name: basename(f) };
});
// Configure assets
project.assets.meshes.forEach((m) => MeshesAssets.Meshes.push({ name: m, path: join(Project.DirPath!, "assets", "meshes", m) }));
if (project.assets.prefabs) {
project.assets.prefabs.forEach((p) => PrefabAssets.Prefabs.push({ name: p, path: join(Project.DirPath!, "prefabs", p) }));
}
if (project.assets.graphs) {
project.assets.graphs.forEach((g) => GraphAssets.Graphs.push({ name: g, path: join(Project.DirPath!, "graphs", g) }));
}
// Configure scene
ProjectHelpers.ImportSceneSettings(editor.scene!, project.scene, rootUrl);
const physicsEngine = editor.scene!.getPhysicsEngine();
if (physicsEngine) {
// Remove physics engine steps
physicsEngine._step = () => { };
}
// Configure camera
SceneSettings.ConfigureFromJson(project.project.camera, editor);
// Morph targets
Overlay.SetMessage("Creating Morph Target Managers");
if (project.morphTargetManagers) {
for (const mtm of project.morphTargetManagers) {
loadPromises.push(new Promise<void>(async (resolve) => {
try {
const json = await readJSON(join(Project.DirPath!, "morphTargets", mtm));
MorphTargetManager.Parse(json, editor.scene!);
} catch (e) {
editor.console.logError(`Failed to load morph target manager "${mtm}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
resolve();
}));
}
await Promise.all(loadPromises);
loadPromises = [];
}
// Load all meshes
Overlay.SetMessage("Creating Meshes...");
for (const m of project.meshes) {
loadPromises.push(new Promise<void>(async (resolve) => {
try {
const json = await readJSON(join(Project.DirPath!, "meshes", m));
const result = await this.ImportMesh(editor, m, json, Project.DirPath!, join("meshes", m));
if (physicsEngine) {
result.meshes.forEach((m) => {
try {
m.physicsImpostor = physicsEngine.getImpostorForPhysicsObject(m);
m.physicsImpostor?.sleep();
editor.console.logInfo(`Parsed physics impostor for mesh "${m.name}"`);
// Retrieve physics impostors for instances as well
if (m instanceof Mesh) {
m.instances.forEach((i) => {
i.physicsImpostor = physicsEngine.getImpostorForPhysicsObject(i);
i.physicsImpostor?.sleep();
editor.console.logInfo(`Parsed physics impostor for instance "${i.name}" of mesh "${m.name}"`);
});
}
} catch (e) {
editor.console.logError(`Failed to set physics impostor for mesh "${m.name}"`);
}
});
}
} catch (e) {
editor.console.logError(`Failed to load mesh "${m}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
resolve();
}));
}
await Promise.all(loadPromises);
loadPromises = [];
// Load all transform nodes
Overlay.SetMessage("Creating Transform Nodes");
for (const t of project.transformNodes ?? []) {
loadPromises.push(new Promise<void>(async (resolve) => {
try {
const json = await readJSON(join(Project.DirPath!, "transform", t));
const transform = TransformNode.Parse(json, editor.scene!, rootUrl);
transform.metadata = transform.metadata ?? {};
transform.metadata._waitingParentId = json.parentId;
} catch (e) {
editor.console.logError(`Failed to load transform node "${t}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
resolve();
}));
}
await Promise.all(loadPromises);
loadPromises = [];
// Load all materials
Overlay.SetMessage("Creating Materials...");
for (const m of project.materials) {
try {
const json = await readJSON(join(Project.DirPath, "materials", m.json));
const materialRootUrl = json.customType === "BABYLON.NodeMaterial" ? undefined : rootUrl;
const material = m.isMultiMaterial ? MultiMaterial.ParseMultiMaterial(json, editor.scene!) : Material.Parse(json, editor.scene!, materialRootUrl!);
if (material && json.metadata) {
material.metadata = json.metadata;
}
editor.console.logInfo(`Parsed material "${m.json}"`);
m.bindedMeshes.forEach((bm) => {
const mesh = editor.scene!.getMeshByID(bm);
if (mesh) {
mesh.material = material;
} else {
editor.console.logWarning(`Failed to attach material ${m.json} on mesh with id "${bm}"`);
}
});
} catch (e) {
editor.console.logError(`Failed to parse material "${m.json}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
}
// Load all textures
Overlay.SetMessage("Creating Textures...");
for (const t of project.textures) {
try {
const json = await readJSON(join(Project.DirPath, "textures", t));
const existing = editor.scene!.textures.find((t) => {
return t.metadata && json.metadata && t.metadata.editorId === json.metadata.editorId;
}) ?? null;
if (existing) { continue; }
if (json.isCube && !json.isRenderTarget && json.files && json.metadata?.isPureCube) {
// Replace Urls
json.files.forEach((f, index) => {
json.files[index] = join(Project.DirPath!, f);
});
const cube = CubeTexture.Parse(json, editor.scene!, rootUrl);
cube.name = cube.url = basename(cube.name);
} else {
Texture.Parse(json, editor.scene!, rootUrl);
}
editor.console.logInfo(`Parsed texture "${t}"`);
} catch (e) {
editor.console.logError(`Failed to parse texture "${t}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
}
// Load all lights
Overlay.SetMessage("Creating Lights...");
for (const l of project.lights) {
loadPromises.push(new Promise<void>(async (resolve) => {
try {
const json = await readJSON(join(Project.DirPath!, "lights", l.json));
const light = Light.Parse(json, editor.scene!)!;
light.metadata = light.metadata ?? {};
light.metadata._waitingParentId = json.parentId;
editor.console.logInfo(`Parsed light "${l.json}"`);
if (l.shadowGenerator) {
const json = await readJSON(join(Project.DirPath!, "shadows", l.shadowGenerator));
if (json.className === CascadedShadowGenerator.CLASSNAME) {
CascadedShadowGenerator.Parse(json, editor.scene!);
} else {
ShadowGenerator.Parse(json, editor.scene!);
}
editor.console.logInfo(`Parsed shadows for light "${l.json}"`);
}
// Handled excluded meshes
if (light._excludedMeshesIds?.length) {
light._excludedMeshesIds.forEach((emid) => {
const excludedMesh = editor.scene!.getMeshByID(emid);
if (excludedMesh) { light.excludedMeshes.push(excludedMesh); }
});
light._excludedMeshesIds = [];
}
// Handle included only meshes
if (light._includedOnlyMeshesIds) {
light._includedOnlyMeshesIds.forEach((imid) => {
const excludedMesh = editor.scene!.getMeshByID(imid);
if (excludedMesh) { light.includedOnlyMeshes.push(excludedMesh); }
});
light._includedOnlyMeshesIds = [];
}
} catch (e) {
editor.console.logError(`Failed to parse light "${l}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
resolve();
}));
}
await Promise.all(loadPromises);
loadPromises = [];
// Load all cameras
Overlay.SetMessage("Creating Cameras...");
for (const c of project.cameras) {
try {
const json = await readJSON(join(Project.DirPath, "cameras", c));
const camera = Camera.Parse(json, editor.scene!);
camera.metadata = camera.metadata ?? {};
camera.metadata._waitingParentId = json.parentId;
editor.console.logInfo(`Parsed camera "${c}"`);
} catch (e) {
editor.console.logError(`Failed to parse camera "${c}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
}
// Load all particle systems
Overlay.SetMessage("Creating Particle Systems...");
for (const ps of project.particleSystems ?? []) {
try {
const json = await readJSON(join(Project.DirPath, "particleSystems", ps));
ParticleSystem.Parse(json, editor.scene!, rootUrl);
} catch (e) {
editor.console.logError(`Failed to parse particle system "${ps}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
}
// Load all sounds
Overlay.SetMessage("Creating Sounds...");
for (const s of project.sounds ?? []) {
try {
const json = await readJSON(join(Project.DirPath, "sounds", s));
Sound.Parse(json, editor.scene!, join(rootUrl, "files", "/"));
} catch (e) {
editor.console.logError(`Failed to parse sound "${s}"`);
}
Overlay.SetSpinnervalue(spinnerValue += spinnerStep);
}
// Post-Processes
Overlay.SetMessage("Configuring Rendering...");
if (project.postProcesses.ssao?.json) {
SerializationHelper.Parse(() => SceneSettings.SSAOPipeline, project.postProcesses.ssao.json, editor.scene!, rootUrl);
SceneSettings.SetSSAOEnabled(editor, project.postProcesses.ssao.enabled);
}
if (project.postProcesses.screenSpaceReflections?.json) {
SceneSettings.SetScreenSpaceReflectionsEnabled(editor, project.postProcesses.screenSpaceReflections.enabled);
if (SceneSettings.ScreenSpaceReflectionsPostProcess) {
SerializationHelper.Parse(() => SceneSettings.ScreenSpaceReflectionsPostProcess, project.postProcesses.screenSpaceReflections?.json, editor.scene!, "");
}
}
if (project.postProcesses.default?.json) {
SerializationHelper.Parse(() => SceneSettings.DefaultPipeline, project.postProcesses.default.json, editor.scene!, rootUrl);
SceneSettings.SetDefaultPipelineEnabled(editor, project.postProcesses.default.enabled);
}
if (project.postProcesses.motionBlur?.json) {
SceneSettings.SetMotionBlurEnabled(editor, project.postProcesses.motionBlur.enabled);
if (SceneSettings.MotionBlurPostProcess) {
SerializationHelper.Parse(() => SceneSettings.MotionBlurPostProcess, project.postProcesses.motionBlur?.json, editor.scene!, "");
}
}
// Animation groups
if (project.scene.animationGroups) {
for (const g of project.scene.animationGroups) {
const animationGroup = AnimationGroup.Parse(g, editor.scene!);
animationGroup.play();
animationGroup.goToFrame(animationGroup.from);
animationGroup.stop();
}
}
// Configure and save project
project.physicsEnabled ??= true;
Project.Project = project;
// Update cache
Overlay.SetMessage("Loading Cache...");
const assetsCachePath = join(Project.DirPath, "assets", "cache.json");
if ((await pathExists(assetsCachePath))) {
Assets.SetCachedData(await readJSON(assetsCachePath));
}
// Parent Ids
const scene = editor.scene!;
scene.meshes.forEach((m) => this._SetWaitingParent(m));
scene.lights.forEach((l) => this._SetWaitingParent(l));
scene.cameras.forEach((c) => this._SetWaitingParent(c));
scene.transformNodes.forEach((tn) => this._SetWaitingParent(tn));
// Geometry Ids
scene.meshes.forEach((m) => {
if (m instanceof Mesh) {
if (m.metadata?._waitingGeometryId && m.geometry) {
m.geometry.id = m.metadata._waitingGeometryId;
delete m.metadata._waitingGeometryId;
}
}
});
// Notify
editor.console.logInfo(`Imported project located at ${path}`);
// Refresh
this._RefreshEditor(editor);
}
/**
* Imports the given mesh according to its rooturl, name and json configuration.
* @param editor the editor reference.
* @param name the name of the mesh (used by logs).
* @param json the json representation of the mesh.
* @param rootUrl the root url of the mesh loader.
* @param filename the name of the mesh file to load.
*/
public static async ImportMesh(editor: Editor, name: string, json: any, rootUrl: string, filename: string): Promise<ReturnType<typeof SceneLoader.ImportMeshAsync>> {
SceneLoaderFlags.ForceFullSceneLoadingForIncremental = true;
const result = await SceneLoader.ImportMeshAsync("", rootUrl, filename, editor.scene, null, ".babylon");
editor.console.logInfo(`Parsed mesh "${name}"`);
const allMeshes: { mesh: Mesh; geometryId: string; parentId?: string; instances?: string[]; }[] = [];
result.meshes.forEach((mesh, index) => {
if (!(mesh instanceof Mesh)) { return; }
if (mesh.skeleton && mesh.metadata?.basePoseMatrix) {
mesh.updatePoseMatrix(Matrix.FromArray(mesh.metadata.basePoseMatrix));
}
allMeshes.push({
mesh,
geometryId: json.meshes[index].geometryId,
parentId: json.meshes[index].parentId,
instances: json.meshes[index].instances?.map((i) => i.parentId) ?? [],
});
});
// Lods
for (const lod of json.lods) {
try {
lod.mesh.meshes[0].delayLoadingFile = join(Project.DirPath!, lod.mesh.meshes[0].delayLoadingFile);
const blob = new Blob([JSON.stringify(lod.mesh)]);
const url = URL.createObjectURL(blob);
const lodResult = await SceneLoader.ImportMeshAsync("", "", url, editor.scene, null, ".babylon");
const mesh = lodResult.meshes[0];
if (!mesh || !(mesh instanceof Mesh)) { continue; }
allMeshes.push({ mesh, geometryId: lod.mesh.meshes[0].geometryId });
(result.meshes[0] as Mesh).addLODLevel(lod.distance, mesh);
URL.revokeObjectURL(url);
editor.console.logInfo(`Parsed LOD level "${lod.mesh.meshes[0].name}" for mesh "${name}"`);
} catch (e) {
editor.console.logError(`Failed to load LOD for "${result.meshes[0].name}"`);
}
}
while (allMeshes.find((m) => m.mesh.delayLoadState && m.mesh.delayLoadState !== Constants.DELAYLOADSTATE_LOADED)) {
await Tools.Wait(150);
}
await Tools.Wait(0);
// Parent
allMeshes.forEach((m) => {
m.mesh.metadata = m.mesh.metadata ?? {};
m.mesh.metadata._waitingParentId = m.parentId;
m.mesh.metadata._waitingGeometryId = m.geometryId;
m.mesh.renderingGroupId = m.mesh.metadata.renderingGroupId ?? m.mesh.renderingGroupId;
if (m.instances) {
m.mesh.instances?.forEach((i, instanceIndex) => {
i.metadata = i.metadata ?? {};
i.metadata._waitingParentId = m.instances![instanceIndex];
});
}
if (m.mesh.hasThinInstances) {
m.mesh.thinInstanceRefreshBoundingInfo(true);
}
});
return result as any;
}
/**
* Sets the parent of the given node waiting for it.
*/
private static _SetWaitingParent(n: Node): void {
if (!n.metadata?._waitingParentId) { return; }
n.parent = n.getScene().getNodeByID(n.metadata._waitingParentId) ?? n.getScene().getTransformNodeByID(n.metadata._waitingParentId);
delete n.metadata._waitingParentId;
n._waitingParentId = null;
}
/**
* Refreshes the editor.
*/
private static _RefreshEditor(editor: Editor): void {
editor.assets.refresh();
editor.graph.refresh();
Overlay.Hide();
}
/**
* Overrides the current texture parser available in Babylon.JS Scene Loader.
*/
private static _OverrideTextureParser(): void {
const textureParser = SerializationHelper._TextureParser;
SerializationHelper._TextureParser = (source, scene, rootUrl) => {
if (source.metadata?.editorName) {
const texture = scene.textures.find((t) => t.metadata && t.metadata.editorName === source.metadata.editorName);
if (texture) { return texture; }
// Cube texture?
if (source.isCube && !source.isRenderTarget && source.files && source.metadata?.isPureCube) {
// Replace Urls for files in case of pure cube texture
source.files.forEach((f, index) => {
if (f.indexOf("files") !== 0) { return; }
source.files[index] = join(Project.DirPath!, f);
});
}
}
let texture: Nullable<BaseTexture> = null;
const supportedFormat = KTXTools.GetSupportedKtxFormat(scene.getEngine());
const ktx2CompressedTextures = WorkSpace.Workspace?.ktx2CompressedTextures;
if (supportedFormat && ktx2CompressedTextures?.enabled && ktx2CompressedTextures?.enabledInPreview) {
const ktxTextureName = basename(KTXTools.GetKtxFileName(source.name, supportedFormat));
const ktxFileExists = pathExistsSync(join(Project.DirPath!, "files/compressed_textures", ktxTextureName));
if (ktxFileExists) {
const oldName = source.name;
source.name = join("files/compressed_textures", ktxTextureName);
texture = textureParser(source, scene, rootUrl);
if (texture) {
texture.name = oldName;
texture.metadata ??= {};
texture.metadata.ktx2CompressedTextures ??= {};
texture.metadata.ktx2CompressedTextures.isUsingCompressedTexture = true;
}
}
}
if (!texture) {
texture = textureParser(source, scene, rootUrl);
if (texture) {
texture.metadata ??= {};
texture.metadata.ktx2CompressedTextures ??= {};
texture.metadata.ktx2CompressedTextures.isUsingCompressedTexture = false;
}
}
if (source.metadata?.editorName && source.metadata?.isPureCube) {
// Cube texture?
if (source.isCube && !source.isRenderTarget && source.files && source.metadata?.isPureCube) {
// Restore Urls for files in case of pure cube texture
source.files.forEach((f, index) => {
if (f.indexOf("files") === 0) { return; }
source.files[index] = join("files", basename(f));
});
}
}
return texture;
};
}
} | the_stack |
import { configListeners, getHasConfigured, setConfig } from './conf'
import { THEME_CLASSNAME_PREFIX } from './constants/constants'
import { isWeb } from './constants/platform'
import { Variable, createVariable, isVariable } from './createVariable'
import { createVariables } from './createVariables'
import { createTamaguiProvider } from './helpers/createTamaguiProvider'
import { getInsertedRules } from './helpers/insertStyleRule'
import {
registerCSSVariable,
tokenRules,
tokensValueToVariable,
} from './helpers/registerCSSVariable'
import { configureMedia } from './hooks/useMedia'
import { parseFont, registerFontVariables } from './insertFont'
import {
AnimationDriver,
CreateTamaguiConfig,
GenericTamaguiConfig,
MediaQueryKey,
TamaguiInternalConfig,
ThemeObject,
} from './types'
export type CreateTamaguiProps =
// user then re-defines the types after createTamagui returns the typed object they want
Partial<Omit<GenericTamaguiConfig, 'themes' | 'tokens' | 'animations'>> & {
animations?: AnimationDriver<any>
tokens: GenericTamaguiConfig['tokens']
themes: {
[key: string]: {
[key: string]: string | number | Variable
}
}
// for the first render, determines which media queries are true
// useful for SSR
mediaQueryDefaultActive?: MediaQueryKey[]
// what's between each CSS style rule, set to "\n" to be easier to read
// defaults: "\n" when NODE_ENV=development, "" otherwise
cssStyleSeparator?: string
// (Advanced)
// on the web, tamagui treats `dark` and `light` themes as special and
// generates extra CSS to avoid having to re-render the entire page.
// this CSS relies on specificity hacks that multiply by your sub-themes.
// this sets the maxiumum number of nested dark/light themes you can do
// defaults to 3 for a balance, but can be higher if you nest them deeply.
maxDarkLightNesting?: number
// adds @media(prefers-color-scheme) media queries for dark/light
shouldAddPrefersColorThemes?: boolean
// only if you put the theme classname on the html element we have to generate diff
themeClassNameOnRoot?: boolean
}
// config is re-run by the @tamagui/static, dont double validate
const createdConfigs = new WeakMap<any, boolean>()
export type InferTamaguiConfig<Conf extends CreateTamaguiProps> = Conf extends Partial<
CreateTamaguiConfig<infer A, infer B, infer C, infer D, infer E, infer F>
>
? TamaguiInternalConfig<A, B, C, D, E, F>
: unknown
export function createTamagui<Conf extends CreateTamaguiProps>(
config: Conf
): InferTamaguiConfig<Conf> {
if (createdConfigs.has(config)) {
return config as any
}
if (process.env.NODE_ENV === 'development') {
if (!config.tokens) {
throw new Error(`No tokens provided to Tamagui config`)
}
if (!config.themes) {
throw new Error(`No themes provided to Tamagui config`)
}
if (!config.fonts) {
throw new Error(`No fonts provided to Tamagui config`)
}
}
// test env loads a few times as it runs diff tests
if (getHasConfigured()) {
console.warn(`Warning: createTamagui called twice (maybe HMR)`)
}
configureMedia({
queries: config.media as any,
defaultActive: config.mediaQueryDefaultActive,
})
const fontTokens = createVariables(config.fonts!)
const fontsParsed = (() => {
const res = {} as typeof fontTokens
for (const familyName in fontTokens) {
res[`$${familyName}`] = parseFont(fontTokens[familyName])
}
return res!
})()
const themeConfig = (() => {
const themes = { ...config.themes }
let cssRules: string[] = []
if (isWeb) {
for (const key in config.tokens) {
for (const skey in config.tokens[key]) {
const val = config.tokens[key][skey]
registerCSSVariable(val)
}
}
for (const key in fontsParsed) {
const val = fontsParsed[key]
registerFontVariables(val)
}
const sep = process.env.NODE_ENV === 'development' ? config.cssStyleSeparator || ' ' : ''
cssRules.push(`:root {${sep}${[...tokenRules].join(`;${sep}`)}${sep}}`)
}
// special case for SSR
const hasDarkLight = 'light' in config.themes && 'dark' in config.themes
const CNP = `.${THEME_CLASSNAME_PREFIX}`
// dedupe themes to avoid duplicate CSS generation
type DedupedTheme = {
names: string[]
theme: ThemeObject
}
const dedupedThemes: {
[key: string]: DedupedTheme
} = {}
const existing = new WeakMap<ThemeObject, DedupedTheme>()
// first, de-dupe and parse them
for (const themeName in themes) {
const rawTheme = themes[themeName]
// if existing, avoid
if (existing.has(rawTheme)) {
const e = existing.get(rawTheme)!
themes[themeName] = e.theme
e.names.push(themeName)
continue
}
// parse into variables
const theme = { ...config.themes[themeName] }
for (const key in theme) {
// make sure properly names theme variables
ensureThemeVariable(theme, key)
}
themes[themeName] = theme
// set deduped
dedupedThemes[themeName] = {
names: [themeName],
theme,
}
existing.set(config.themes[themeName], dedupedThemes[themeName])
}
// then, generate from de-duped
if (isWeb) {
for (const themeName in dedupedThemes) {
const { theme, names } = dedupedThemes[themeName]
let vars = ''
for (const themeKey in theme) {
const variable = theme[themeKey] as Variable
let value: any = null
if (variable.isFloating || !tokensValueToVariable.has(variable.val)) {
value = variable.val
} else {
value = tokensValueToVariable.get(variable.val)!.variable
}
vars += `--${themeKey}:${value};`
}
const isDarkOrLightBase = themeName === 'dark' || themeName === 'light'
const isDark = themeName.startsWith('dark')
const selectors = names.map((name) => {
return `${CNP}${name}`
})
// since we dont specify dark/light in classnames we have to do an awkward specificity war
// use config.maxDarkLightNesting to determine how deep you can nest until it breaks
if (hasDarkLight) {
for (const subName of names) {
const childSelector = `${CNP}${subName.replace('dark_', '').replace('light_', '')}`
const order = isDark ? ['dark', 'light'] : ['light', 'dark']
if (isDarkOrLightBase) {
order.reverse()
}
const [stronger, weaker] = order
const max = config.maxDarkLightNesting ?? 3
new Array(max * 2).fill(undefined).forEach((_, pi) => {
if (pi % 2 === 1) return
const parents = new Array(pi + 1).fill(undefined).map((_, psi) => {
return `${CNP}${psi % 2 === 0 ? stronger : weaker}`
})
selectors.push(
`${(parents.length > 1 ? parents.slice(1) : parents).join(' ')} ${childSelector}`
)
})
}
}
const rootSep = config.themeClassNameOnRoot ? '' : ' '
cssRules.push(`${selectors.map((x) => `:root${rootSep}${x}`).join(', ')} {${vars}}`)
if (config.shouldAddPrefersColorThemes ?? true) {
// add media prefers for dark/light base
if (isDarkOrLightBase) {
cssRules.push(
`@media(prefers-color-scheme: ${isDark ? 'dark' : 'light'}) {
body { background:${theme.background}; color: ${theme.color} }
:root {${vars} }
}`
)
}
}
}
}
// proxy upwards to get parent variables (themes are subset going down)
for (const themeName in themes) {
// we could test if this is better as just a straight object spread or fancier proxy
const cur: string[] = []
// if theme is dark_blue_alt1_Button
// this will be the parent names in order: ['dark', 'dark_blue', 'dark_blue_alt1"]
const parents = themeName
.split('_')
.slice(0, -1)
.map((part) => {
cur.push(part)
return cur.join('_')
})
if (!parents.length) continue
themes[themeName] = new Proxy(themes[themeName], {
get(target, key) {
if (Reflect.has(target, key)) {
return Reflect.get(target, key)
}
// check parents
for (let i = parents.length - 1; i >= 0; i--) {
const parent = themes[parents[i]]
if (!parent) {
continue
}
if (Reflect.has(parent, key)) {
return Reflect.get(parent, key)
}
}
},
})
}
tokensValueToVariable.clear()
Object.freeze(cssRules)
const css = cssRules.join('\n')
return {
themes,
cssRules,
css,
}
})()
// faster lookups token keys become $keys to match input
const tokensParsed: any = parseTokens(config.tokens)
const getCSS = () => {
return `${themeConfig.css}\n${getInsertedRules().join('\n')}`
}
if (config.shorthands) {
for (const key in config.shorthands) {
reversedShorthands[config.shorthands[key]] = key
}
}
const next: TamaguiInternalConfig = {
fonts: {},
animations: {} as any,
shorthands: {},
media: {},
...config,
themes: themeConfig.themes,
Provider: createTamaguiProvider({
getCSS,
defaultTheme: 'light',
...config,
themes: themeConfig.themes,
}),
fontsParsed,
themeConfig,
tokensParsed,
parsed: true,
getCSS,
}
setConfig(next)
if (configListeners.size) {
configListeners.forEach((cb) => cb(next))
configListeners.clear()
}
createdConfigs.set(next, true)
// @ts-expect-error
return next
}
export const reversedShorthands: Record<string, string> = {}
const parseTokens = (tokens: any) => {
const res: any = {}
for (const key in tokens) {
res[key] = {}
for (const skey in tokens[key]) {
res[key][`$${skey}`] = tokens[key][skey]
}
}
return res
}
// mutates, freeze after
// shared by createTamagui so extracted here
function ensureThemeVariable(theme: any, key: string) {
const val = theme[key]
const themeKey = key
if (!isVariable(val)) {
theme[key] = createVariable({
key: themeKey,
name: themeKey,
val,
})
} else {
if (val.name !== themeKey) {
// rename to theme name
theme[key] = createVariable({
key: val.name,
name: themeKey,
val: val.val,
})
}
}
}
// for quick testing types:
// const x = createTamagui({
// shorthands: {},
// media: {},
// themes: {},
// tokens: {
// font: {},
// color: {},
// radius: {},
// size: {},
// space: {},
// zIndex: {},
// },
// }) | the_stack |
import { Components, registerComponent } from '../../lib/vulcan-lib';
import React from 'react';
import { Link } from '../../lib/reactRouterWrapper';
import { postGetPageUrl, postGetLastCommentedAt, postGetLastCommentPromotedAt, postGetCommentCount } from "../../lib/collections/posts/helpers";
import { sequenceGetPageUrl } from "../../lib/collections/sequences/helpers";
import { collectionGetPageUrl } from "../../lib/collections/collections/helpers";
import withErrorBoundary from '../common/withErrorBoundary';
import CloseIcon from '@material-ui/icons/Close';
import { useCurrentUser } from "../common/withUser";
import classNames from 'classnames';
import { useRecordPostView } from '../common/withRecordPostView';
import { NEW_COMMENT_MARGIN_BOTTOM } from '../comments/CommentsListSection'
import { AnalyticsContext } from "../../lib/analyticsEvents";
import { cloudinaryCloudNameSetting } from '../../lib/publicSettings';
import { getReviewPhase, postEligibleForReview, postIsVoteable, REVIEW_YEAR } from '../../lib/reviewUtils';
export const MENU_WIDTH = 18
export const KARMA_WIDTH = 42
export const styles = (theme: ThemeType): JssStyles => ({
root: {
position: "relative",
[theme.breakpoints.down('xs')]: {
width: "100%"
},
'&:hover $actions': {
opacity: .2,
}
},
background: {
width: "100%",
background: theme.palette.panelBackground.default,
},
translucentBackground: {
width: "100%",
background: theme.palette.panelBackground.translucent,
backdropFilter: "blur(1px)"
},
postsItem: {
display: "flex",
position: "relative",
paddingTop: 10,
paddingBottom: 10,
alignItems: "center",
flexWrap: "nowrap",
[theme.breakpoints.down('xs')]: {
flexWrap: "wrap",
paddingTop: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
paddingLeft: 5
},
},
withGrayHover: {
'&:hover': {
backgroundColor: theme.palette.panelBackground.postsItemHover,
},
},
hasSmallSubtitle: {
'&&': {
top: -5,
}
},
bottomBorder: {
borderBottom: theme.palette.border.itemSeparatorBottom,
},
commentsBackground: {
backgroundColor: theme.palette.panelBackground.postsItemExpandedComments,
[theme.breakpoints.down('xs')]: {
paddingLeft: theme.spacing.unit/2,
paddingRight: theme.spacing.unit/2
}
},
karma: {
width: KARMA_WIDTH,
justifyContent: "center",
[theme.breakpoints.down('xs')]:{
width: "unset",
justifyContent: "flex-start",
marginLeft: 2,
marginRight: theme.spacing.unit
}
},
title: {
minHeight: 26,
flexGrow: 1,
flexShrink: 1,
overflow: "hidden",
textOverflow: "ellipsis",
marginRight: 12,
[theme.breakpoints.up('sm')]: {
position: "relative",
top: 3,
},
[theme.breakpoints.down('xs')]: {
order:-1,
height: "unset",
maxWidth: "unset",
width: "100%",
paddingRight: theme.spacing.unit
},
'&:hover': {
opacity: 1,
}
},
author: {
justifyContent: "flex",
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis", // I'm not sure this line worked properly?
marginRight: theme.spacing.unit*1.5,
zIndex: theme.zIndexes.postItemAuthor,
[theme.breakpoints.down('xs')]: {
justifyContent: "flex-end",
width: "unset",
marginLeft: 0,
flex: "unset"
}
},
event: {
maxWidth: 250,
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis", // I'm not sure this line worked properly?
marginRight: theme.spacing.unit*1.5,
[theme.breakpoints.down('xs')]: {
width: "unset",
marginLeft: 0,
}
},
newCommentsSection: {
width: "100%",
paddingLeft: theme.spacing.unit*2,
paddingRight: theme.spacing.unit*2,
paddingTop: theme.spacing.unit,
cursor: "pointer",
marginBottom: NEW_COMMENT_MARGIN_BOTTOM,
[theme.breakpoints.down('xs')]: {
padding: 0,
}
},
actions: {
opacity: 0,
display: "flex",
position: "absolute",
top: 0,
right: -MENU_WIDTH - 6,
width: MENU_WIDTH,
height: "100%",
cursor: "pointer",
alignItems: "center",
justifyContent: "center",
[theme.breakpoints.down('sm')]: {
display: "none"
}
},
mobileSecondRowSpacer: {
[theme.breakpoints.up('sm')]: {
display: "none",
},
flexGrow: 1,
},
mobileActions: {
cursor: "pointer",
width: MENU_WIDTH,
opacity: .5,
marginRight: theme.spacing.unit,
display: "none",
[theme.breakpoints.down('xs')]: {
display: "block"
}
},
nonMobileIcons: {
[theme.breakpoints.up('sm')]: {
display: "none"
}
},
mobileDismissButton: {
display: "none",
opacity: 0.75,
verticalAlign: "middle",
position: "relative",
cursor: "pointer",
right: 10,
[theme.breakpoints.down('xs')]: {
display: "inline-block"
}
},
subtitle: {
color: theme.palette.grey[700],
fontFamily: theme.typography.commentStyle.fontFamily,
[theme.breakpoints.up('sm')]: {
position: "absolute",
left: 42,
bottom: 5,
zIndex: theme.zIndexes.nextUnread,
},
[theme.breakpoints.down('xs')]: {
order: -1,
width: "100%",
marginTop: -2,
marginBottom: 3,
marginLeft: 1,
},
"& a": {
color: theme.palette.primary.main,
},
},
sequenceImage: {
position: "relative",
marginLeft: -60,
opacity: 0.6,
height: 48,
width: 146,
// Negative margins that are the opposite of the padding on postsItem, since
// the image extends into the padding.
marginTop: -12,
marginBottom: -12,
[theme.breakpoints.down('xs')]: {
marginTop: 0,
marginBottom: 0,
position: "absolute",
overflow: 'hidden',
right: 0,
bottom: 0,
height: "100%",
},
// Overlay a white-to-transparent gradient over the image
"&:after": {
content: "''",
position: "absolute",
width: "100%",
height: "100%",
left: 0,
top: 0,
background: `linear-gradient(to right, ${theme.palette.panelBackground.default} 0%, ${theme.palette.panelBackground.translucent2} 60%, transparent 100%)`,
}
},
sequenceImageImg: {
height: 48,
width: 146,
[theme.breakpoints.down('xs')]: {
height: "100%",
width: 'auto'
},
},
reviewCounts: {
width: 50
},
noReviews: {
color: theme.palette.grey[400]
},
dense: {
paddingTop: 7,
paddingBottom:8
},
withRelevanceVoting: {
marginLeft: 28
},
bookmark: {
marginLeft: theme.spacing.unit/2,
marginRight: theme.spacing.unit*1.5,
position: "relative",
top: 2,
},
isRead: {
// this is just a placeholder, enabling easier theming.
}
})
const dismissRecommendationTooltip = "Don't remind me to finish reading this sequence unless I visit it again";
const cloudinaryCloudName = cloudinaryCloudNameSetting.get()
const isSticky = (post: PostsList, terms: PostsViewTerms) => {
if (post && terms && terms.forum) {
return (
post.sticky ||
(terms.af && post.afSticky) ||
(terms.meta && post.metaSticky)
)
}
}
const PostsItem2 = ({
// post: The post displayed.
post,
// tagRel: (Optional) The relationship between this post and a tag. If
// provided, UI will be shown with the score and voting on this post's
// relevance to that tag.
tagRel=null,
// defaultToShowComments: (bool) If set, comments will be expanded by default.
defaultToShowComments=false,
// sequenceId, chapter: If set, these will be used for making a nicer URL.
sequenceId, chapter,
// index: If this is part of a list of PostsItems, its index (starting from
// zero) into that list. Used for special casing some styling at start of
// the list.
index,
// terms: If this is part of a list generated from a query, the terms of that
// query. Used for figuring out which sticky icons to apply, if any.
terms,
// resumeReading: If this is a Resume Reading suggestion, the corresponding
// partiallyReadSequenceItem (see schema in users/custom_fields). Used for
// the sequence-image background.
resumeReading,
// dismissRecommendation: If this is a Resume Reading suggestion, a callback
// to dismiss it.
dismissRecommendation,
showBottomBorder=true,
showQuestionTag=true,
showDraftTag=true,
showIcons=true,
showPostedAt=true,
defaultToShowUnreadComments=false,
// dense: (bool) Slightly reduce margins to make this denser. Used on the
// All Posts page.
dense=false,
// bookmark: (bool) Whether this is a bookmark. Adds a clickable bookmark
// icon.
bookmark=false,
// showNominationCount: (bool) whether this should display it's number of Review nominations
showNominationCount=false,
showReviewCount=false,
hideAuthor=false,
classes,
curatedIconLeft=false,
translucentBackground=false,
forceSticky=false
}: {
post: PostsList,
tagRel?: WithVoteTagRel|null,
defaultToShowComments?: boolean,
sequenceId?: string,
chapter?: any,
index?: number,
terms?: any,
resumeReading?: any,
dismissRecommendation?: any,
showBottomBorder?: boolean,
showQuestionTag?: boolean,
showDraftTag?: boolean,
showIcons?: boolean,
showPostedAt?: boolean,
defaultToShowUnreadComments?: boolean,
dense?: boolean,
bookmark?: boolean,
showNominationCount?: boolean,
showReviewCount?: boolean,
hideAuthor?: boolean,
classes: ClassesType,
curatedIconLeft?: boolean,
translucentBackground?: boolean,
forceSticky?: boolean
}) => {
const [showComments, setShowComments] = React.useState(defaultToShowComments);
const [readComments, setReadComments] = React.useState(false);
const [markedVisitedAt, setMarkedVisitedAt] = React.useState<Date|null>(null);
const { isRead, recordPostView } = useRecordPostView(post);
const currentUser = useCurrentUser();
const toggleComments = React.useCallback(
() => {
recordPostView({post, extraEventProperties: {type: "toggleComments"}})
setShowComments(!showComments);
setReadComments(true);
},
[post, recordPostView, setShowComments, showComments, setReadComments]
);
const markAsRead = () => {
recordPostView({post, extraEventProperties: {type: "markAsRead"}})
setMarkedVisitedAt(new Date())
}
const compareVisitedAndCommentedAt = (lastVisitedAt, lastCommentedAt) => {
const newComments = lastVisitedAt < lastCommentedAt;
return (isRead && newComments && !readComments)
}
const hasUnreadComments = () => {
const lastCommentedAt = postGetLastCommentedAt(post)
const lastVisitedAt = markedVisitedAt || post.lastVisitedAt
return compareVisitedAndCommentedAt(lastVisitedAt, lastCommentedAt)
}
const hasNewPromotedComments = () => {
const lastVisitedAt = markedVisitedAt || post.lastVisitedAt
const lastCommentPromotedAt = postGetLastCommentPromotedAt(post)
return compareVisitedAndCommentedAt(lastVisitedAt, lastCommentPromotedAt)
}
const hadUnreadComments = () => {
const lastCommentedAt = postGetLastCommentedAt(post)
return compareVisitedAndCommentedAt(post.lastVisitedAt, lastCommentedAt)
}
const { PostsItemComments, PostsItemKarma, PostsTitle, PostsUserAndCoauthors, LWTooltip,
PostsPageActions, PostsItemIcons, PostsItem2MetaInfo, PostsItemTooltipWrapper,
BookmarkButton, PostsItemDate, PostsItemNewCommentsWrapper, AnalyticsTracker,
AddToCalendarButton, PostsItemReviewVote, ReviewPostButton } = (Components as ComponentTypes)
const postLink = postGetPageUrl(post, false, sequenceId || chapter?.sequenceId);
const renderComments = showComments || (defaultToShowUnreadComments && hadUnreadComments())
const condensedAndHiddenComments = defaultToShowUnreadComments && !showComments
const dismissButton = (currentUser && resumeReading &&
<LWTooltip title={dismissRecommendationTooltip} placement="right">
<CloseIcon onClick={() => dismissRecommendation()}/>
</LWTooltip>
)
const commentTerms: CommentsViewTerms = {
view:"postsItemComments",
limit:7,
postId: post._id,
after: (defaultToShowUnreadComments && !showComments) ? post.lastVisitedAt : null
}
const reviewCountsTooltip = `${post.nominationCount2019 || 0} nomination${(post.nominationCount2019 === 1) ? "" :"s"} / ${post.reviewCount2019 || 0} review${(post.nominationCount2019 === 1) ? "" :"s"}`
return (
<AnalyticsContext pageElementContext="postItem" postId={post._id} isSticky={isSticky(post, terms)}>
<div className={classNames(
classes.root,
{
[classes.background]: !translucentBackground,
[classes.translucentBackground]: translucentBackground,
[classes.bottomBorder]: showBottomBorder,
[classes.commentsBackground]: renderComments,
[classes.isRead]: isRead
})}
>
<PostsItemTooltipWrapper
post={post}
className={classNames(
classes.postsItem,
classes.withGrayHover, {
[classes.dense]: dense,
[classes.withRelevanceVoting]: !!tagRel
}
)}
>
{tagRel && <Components.PostsItemTagRelevance tagRel={tagRel} post={post} />}
<PostsItem2MetaInfo className={classes.karma}>
{post.isEvent ? <AddToCalendarButton post={post} /> : <PostsItemKarma post={post} />}
</PostsItem2MetaInfo>
<span className={classNames(classes.title, {[classes.hasSmallSubtitle]: !!resumeReading})}>
<AnalyticsTracker
eventType={"postItem"}
captureOnMount={(eventData) => eventData.capturePostItemOnMount}
captureOnClick={false}
>
<PostsTitle
postLink={postLink}
post={post}
read={isRead}
sticky={isSticky(post, terms) || forceSticky}
showQuestionTag={showQuestionTag}
showDraftTag={showDraftTag}
curatedIconLeft={curatedIconLeft}
/>
</AnalyticsTracker>
</span>
{(resumeReading?.sequence || resumeReading?.collection) &&
<div className={classes.subtitle}>
{resumeReading.numRead ? "Next unread in " : "First post in "}<Link to={
resumeReading.sequence
? sequenceGetPageUrl(resumeReading.sequence)
: collectionGetPageUrl(resumeReading.collection)
}>
{resumeReading.sequence ? resumeReading.sequence.title : resumeReading.collection?.title}
</Link>
{" "}
{(resumeReading.numRead>0) && <span>({resumeReading.numRead}/{resumeReading.numTotal} read)</span>}
</div>
}
{ post.isEvent && !post.onlineEvent && <PostsItem2MetaInfo className={classes.event}>
<Components.EventVicinity post={post} />
</PostsItem2MetaInfo>}
{ !post.isEvent && !hideAuthor && <PostsItem2MetaInfo className={classes.author}>
<PostsUserAndCoauthors post={post} abbreviateIfLong={true} newPromotedComments={hasNewPromotedComments()}/>
</PostsItem2MetaInfo>}
{showPostedAt && !resumeReading && <PostsItemDate post={post} />}
<div className={classes.mobileSecondRowSpacer}/>
{<div className={classes.mobileActions}>
{!resumeReading && <PostsPageActions post={post} />}
</div>}
{showIcons && <div className={classes.nonMobileIcons}>
<PostsItemIcons post={post}/>
</div>}
{!resumeReading && <PostsItemComments
small={false}
commentCount={postGetCommentCount(post)}
onClick={toggleComments}
unreadComments={hasUnreadComments()}
newPromotedComments={hasNewPromotedComments()}
/>}
{getReviewPhase() === "NOMINATIONS" && <PostsItemReviewVote post={post}/>}
{postEligibleForReview(post) && postIsVoteable(post) && getReviewPhase() === "REVIEWS" && <ReviewPostButton post={post} year={REVIEW_YEAR+""} reviewMessage={<LWTooltip title={<div><div>What was good about this post? How it could be improved? Does it stand the test of time?</div><p><em>{post.reviewCount || "No"} review{post.reviewCount !== 1 && "s"}</em></p></div>} placement="bottom">
Review
</LWTooltip>}/>}
{(showNominationCount || showReviewCount) && <LWTooltip title={reviewCountsTooltip} placement="top">
<PostsItem2MetaInfo className={classes.reviewCounts}>
{showNominationCount && <span>{post.nominationCount2019 || 0}</span>}
{/* TODO:(Review) still 2019 */}
{showReviewCount && <span>{" "}<span className={classes.noReviews}>{" "}•{" "}</span>{post.reviewCount2019 || <span className={classes.noReviews}>0</span>}</span>}
</PostsItem2MetaInfo>
</LWTooltip>}
{bookmark && <div className={classes.bookmark}>
<BookmarkButton post={post}/>
</div>}
<div className={classes.mobileDismissButton}>
{dismissButton}
</div>
{resumeReading &&
<div className={classes.sequenceImage}>
<img className={classes.sequenceImageImg}
src={`https://res.cloudinary.com/${cloudinaryCloudName}/image/upload/c_fill,dpr_2.0,g_custom,h_96,q_auto,w_292/v1/${
resumeReading.sequence?.gridImageId
|| resumeReading.collection?.gridImageId
|| "sequences/vnyzzznenju0hzdv6pqb.jpg"
}`}
/>
</div>
}
</PostsItemTooltipWrapper>
{<div className={classes.actions}>
{dismissButton}
{!resumeReading && <PostsPageActions post={post} vertical />}
</div>}
{renderComments && <div className={classes.newCommentsSection} onClick={toggleComments}>
<PostsItemNewCommentsWrapper
terms={commentTerms}
post={post}
treeOptions={{
highlightDate: markedVisitedAt || post.lastVisitedAt,
condensed: condensedAndHiddenComments,
markAsRead: markAsRead,
}}
/>
</div>}
</div>
</AnalyticsContext>
)
};
const PostsItem2Component = registerComponent('PostsItem2', PostsItem2, {
styles,
hocs: [withErrorBoundary],
areEqual: {
terms: "deep",
},
});
declare global {
interface ComponentTypes {
PostsItem2: typeof PostsItem2Component
}
} | the_stack |
import { window } from 'vscode';
import { Resolver } from './variable-resolver';
describe('substituteFoamVariables', () => {
test('Does nothing if no Foam-specific variables are used', async () => {
const input = `
# \${AnotherVariable} <-- Unrelated to foam
# \${AnotherVariable:default_value} <-- Unrelated to foam
# \${AnotherVariable:default_value/(.*)/\${1:/upcase}/}} <-- Unrelated to foam
# $AnotherVariable} <-- Unrelated to foam
# $CURRENT_YEAR-\${CURRENT_MONTH}-$CURRENT_DAY <-- Unrelated to foam
`;
const givenValues = new Map<string, string>();
givenValues.set('FOAM_TITLE', 'My note title');
const resolver = new Resolver(givenValues, new Date());
expect((await resolver.resolveText(input))[1]).toEqual(input);
});
test('Correctly substitutes variables that are substrings of one another', async () => {
// FOAM_TITLE is a substring of FOAM_TITLE_NON_EXISTENT_VARIABLE
// If we're not careful with how we substitute the values
// we can end up putting the FOAM_TITLE in place FOAM_TITLE_NON_EXISTENT_VARIABLE should be.
const input = `
# \${FOAM_TITLE}
# $FOAM_TITLE
# \${FOAM_TITLE_NON_EXISTENT_VARIABLE}
# $FOAM_TITLE_NON_EXISTENT_VARIABLE
`;
const expected = `
# My note title
# My note title
# \${FOAM_TITLE_NON_EXISTENT_VARIABLE}
# $FOAM_TITLE_NON_EXISTENT_VARIABLE
`;
const givenValues = new Map<string, string>();
givenValues.set('FOAM_TITLE', 'My note title');
const resolver = new Resolver(givenValues, new Date());
expect((await resolver.resolveText(input))[1]).toEqual(expected);
});
});
describe('resolveFoamVariables', () => {
test('Does nothing for unknown Foam-specific variables', async () => {
const variables = ['FOAM_FOO'];
const expected = new Map<string, string>();
expected.set('FOAM_FOO', 'FOAM_FOO');
const givenValues = new Map<string, string>();
const resolver = new Resolver(givenValues, new Date());
expect(await resolver.resolveAll(variables)).toEqual(expected);
});
test('Resolves FOAM_TITLE', async () => {
const foamTitle = 'My note title';
const variables = ['FOAM_TITLE'];
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const expected = new Map<string, string>();
expected.set('FOAM_TITLE', foamTitle);
const givenValues = new Map<string, string>();
const resolver = new Resolver(givenValues, new Date());
expect(await resolver.resolveAll(variables)).toEqual(expected);
});
test('Resolves FOAM_TITLE without asking the user when it is provided', async () => {
const foamTitle = 'My note title';
const variables = ['FOAM_TITLE'];
const expected = new Map<string, string>();
expected.set('FOAM_TITLE', foamTitle);
const givenValues = new Map<string, string>();
givenValues.set('FOAM_TITLE', foamTitle);
const resolver = new Resolver(givenValues, new Date());
expect(await resolver.resolveAll(variables)).toEqual(expected);
});
test('Resolves FOAM_DATE_* properties with current day by default', async () => {
const variables = [
'FOAM_DATE_YEAR',
'FOAM_DATE_YEAR_SHORT',
'FOAM_DATE_MONTH',
'FOAM_DATE_MONTH_NAME',
'FOAM_DATE_MONTH_NAME_SHORT',
'FOAM_DATE_DATE',
'FOAM_DATE_DAY_NAME',
'FOAM_DATE_DAY_NAME_SHORT',
'FOAM_DATE_HOUR',
'FOAM_DATE_MINUTE',
'FOAM_DATE_SECOND',
'FOAM_DATE_SECONDS_UNIX',
];
const expected = new Map<string, string>();
expected.set(
'FOAM_DATE_YEAR',
new Date().toLocaleString('default', { year: 'numeric' })
);
expected.set(
'FOAM_DATE_MONTH_NAME',
new Date().toLocaleString('default', { month: 'long' })
);
expected.set(
'FOAM_DATE_DATE',
new Date().toLocaleString('default', { day: '2-digit' })
);
const givenValues = new Map<string, string>();
const resolver = new Resolver(givenValues, new Date());
expect(await resolver.resolveAll(variables)).toEqual(
expect.objectContaining(expected)
);
});
test('Resolves FOAM_DATE_* properties with given date', async () => {
const targetDate = new Date(2021, 9, 12, 1, 2, 3);
const variables = [
'FOAM_DATE_YEAR',
'FOAM_DATE_YEAR_SHORT',
'FOAM_DATE_MONTH',
'FOAM_DATE_MONTH_NAME',
'FOAM_DATE_MONTH_NAME_SHORT',
'FOAM_DATE_DATE',
'FOAM_DATE_DAY_NAME',
'FOAM_DATE_DAY_NAME_SHORT',
'FOAM_DATE_HOUR',
'FOAM_DATE_MINUTE',
'FOAM_DATE_SECOND',
'FOAM_DATE_SECONDS_UNIX',
];
const expected = new Map<string, string>();
expected.set('FOAM_DATE_YEAR', '2021');
expected.set('FOAM_DATE_YEAR_SHORT', '21');
expected.set('FOAM_DATE_MONTH', '10');
expected.set('FOAM_DATE_MONTH_NAME', 'October');
expected.set('FOAM_DATE_MONTH_NAME_SHORT', 'Oct');
expected.set('FOAM_DATE_DATE', '12');
expected.set('FOAM_DATE_DAY_NAME', 'Tuesday');
expected.set('FOAM_DATE_DAY_NAME_SHORT', 'Tue');
expected.set('FOAM_DATE_HOUR', '01');
expected.set('FOAM_DATE_MINUTE', '02');
expected.set('FOAM_DATE_SECOND', '03');
expected.set(
'FOAM_DATE_SECONDS_UNIX',
(targetDate.getTime() / 1000).toString()
);
const givenValues = new Map<string, string>();
const resolver = new Resolver(givenValues, targetDate);
expect(await resolver.resolveAll(variables)).toEqual(expected);
});
});
describe('resolveFoamTemplateVariables', () => {
test('Does nothing for template without Foam-specific variables', async () => {
const input = `
# \${AnotherVariable} <-- Unrelated to foam
# \${AnotherVariable:default_value} <-- Unrelated to foam
# \${AnotherVariable:default_value/(.*)/\${1:/upcase}/}} <-- Unrelated to foam
# $AnotherVariable} <-- Unrelated to foam
# $CURRENT_YEAR-\${CURRENT_MONTH}-$CURRENT_DAY <-- Unrelated to foam
`;
const expectedMap = new Map<string, string>();
const expectedString = input;
const expected = [expectedMap, expectedString];
const resolver = new Resolver(new Map(), new Date());
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Does nothing for unknown Foam-specific variables', async () => {
const input = `
# $FOAM_FOO
# \${FOAM_FOO}
# \${FOAM_FOO:default_value}
# \${FOAM_FOO:default_value/(.*)/\${1:/upcase}/}}
`;
const expectedMap = new Map<string, string>();
const expectedString = input;
const expected = [expectedMap, expectedString];
const resolver = new Resolver(new Map(), new Date());
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Allows extra variables to be provided; only resolves the unique set', async () => {
const foamTitle = 'My note title';
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const input = `
# $FOAM_TITLE
`;
const expectedOutput = `
# My note title
`;
const expectedMap = new Map<string, string>();
expectedMap.set('FOAM_TITLE', foamTitle);
const expected = [expectedMap, expectedOutput];
const resolver = new Resolver(
new Map(),
new Date(),
new Set(['FOAM_TITLE'])
);
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Appends FOAM_SELECTED_TEXT with a newline to the template if there is selected text but FOAM_SELECTED_TEXT is not referenced and the template ends in a newline', async () => {
const foamTitle = 'My note title';
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const input = `# \${FOAM_TITLE}\n`;
const expectedOutput = `# My note title\nSelected text\n`;
const expectedMap = new Map<string, string>();
expectedMap.set('FOAM_TITLE', foamTitle);
expectedMap.set('FOAM_SELECTED_TEXT', 'Selected text');
const expected = [expectedMap, expectedOutput];
const givenValues = new Map<string, string>();
givenValues.set('FOAM_SELECTED_TEXT', 'Selected text');
const resolver = new Resolver(
givenValues,
new Date(),
new Set(['FOAM_TITLE', 'FOAM_SELECTED_TEXT'])
);
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Appends FOAM_SELECTED_TEXT with a newline to the template if there is selected text but FOAM_SELECTED_TEXT is not referenced and the template ends in multiple newlines', async () => {
const foamTitle = 'My note title';
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const input = `# \${FOAM_TITLE}\n\n`;
const expectedOutput = `# My note title\n\nSelected text\n`;
const expectedMap = new Map<string, string>();
expectedMap.set('FOAM_TITLE', foamTitle);
expectedMap.set('FOAM_SELECTED_TEXT', 'Selected text');
const expected = [expectedMap, expectedOutput];
const givenValues = new Map<string, string>();
givenValues.set('FOAM_SELECTED_TEXT', 'Selected text');
const resolver = new Resolver(
givenValues,
new Date(),
new Set(['FOAM_TITLE', 'FOAM_SELECTED_TEXT'])
);
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Appends FOAM_SELECTED_TEXT without a newline to the template if there is selected text but FOAM_SELECTED_TEXT is not referenced and the template does not end in a newline', async () => {
const foamTitle = 'My note title';
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const input = `# \${FOAM_TITLE}`;
const expectedOutput = '# My note title\nSelected text';
const expectedMap = new Map<string, string>();
expectedMap.set('FOAM_TITLE', foamTitle);
expectedMap.set('FOAM_SELECTED_TEXT', 'Selected text');
const expected = [expectedMap, expectedOutput];
const givenValues = new Map<string, string>();
givenValues.set('FOAM_SELECTED_TEXT', 'Selected text');
const resolver = new Resolver(
givenValues,
new Date(),
new Set(['FOAM_TITLE', 'FOAM_SELECTED_TEXT'])
);
expect(await resolver.resolveText(input)).toEqual(expected);
});
test('Does not append FOAM_SELECTED_TEXT to a template if there is no selected text and is not referenced', async () => {
const foamTitle = 'My note title';
jest
.spyOn(window, 'showInputBox')
.mockImplementationOnce(jest.fn(() => Promise.resolve(foamTitle)));
const input = `
# \${FOAM_TITLE}
`;
const expectedOutput = `
# My note title
`;
const expectedMap = new Map<string, string>();
expectedMap.set('FOAM_TITLE', foamTitle);
expectedMap.set('FOAM_SELECTED_TEXT', '');
const expected = [expectedMap, expectedOutput];
const givenValues = new Map<string, string>();
givenValues.set('FOAM_SELECTED_TEXT', '');
const resolver = new Resolver(
givenValues,
new Date(),
new Set(['FOAM_TITLE', 'FOAM_SELECTED_TEXT'])
);
expect(await resolver.resolveText(input)).toEqual(expected);
});
}); | the_stack |
import { EventEmitter } from 'eventemitter3'
import FD from './factorioData'
import U from './generators/util'
import { Blueprint } from './Blueprint'
import { WireConnectionMap } from './WireConnectionMap'
const MAX_POLE_CONNECTION_COUNT = 5
export interface IConnection {
color: string
entityNumber1: number
entityNumber2: number
entitySide1: number
entitySide2: number
}
export class WireConnections extends EventEmitter {
private bp: Blueprint
private readonly connections = new WireConnectionMap()
public constructor(bp: Blueprint) {
super()
this.bp = bp
}
private static hash(conn: IConnection): string {
const firstE = Math.min(conn.entityNumber1, conn.entityNumber2)
const secondE = Math.max(conn.entityNumber1, conn.entityNumber2)
const firstS = firstE === conn.entityNumber1 ? conn.entitySide1 : conn.entitySide2
const secondS = secondE === conn.entityNumber2 ? conn.entitySide2 : conn.entitySide1
return `${conn.color}-${firstE}-${secondE}-${firstS}-${secondS}`
}
public static deserialize(
entityNumber: number,
connections: BPS.IConnection,
neighbours: number[]
): IConnection[] {
const parsedConnections: IConnection[] = []
const addConnSide = (side: string): void => {
if (connections[side]) {
// eslint-disable-next-line guard-for-in
for (const color in connections[side]) {
const conn = connections[side] as BPS.IConnSide
for (const data of conn[color]) {
parsedConnections.push({
color,
entityNumber1: entityNumber,
entityNumber2: data.entity_id,
entitySide1: Number(side),
entitySide2: data.circuit_id || 1,
})
}
}
}
}
const addCopperConnSide = (side: string, color: string): void => {
if (connections[side]) {
// For some reason Cu0 and Cu1 are arrays but the switch can only have 1 copper connection
const data = (connections[side] as BPS.IWireColor[])[0]
parsedConnections.push({
color,
entityNumber1: entityNumber,
entityNumber2: data.entity_id,
entitySide1: Number(side.slice(2, 3)) + 1,
entitySide2: 1,
})
}
}
if (connections) {
addConnSide('1')
addConnSide('2')
// power_switch only connections
addCopperConnSide('Cu0', 'copper')
addCopperConnSide('Cu1', 'copper')
}
if (neighbours) {
for (const entNr of neighbours) {
parsedConnections.push(WireConnections.toPoleConnection(entityNumber, entNr))
}
}
return parsedConnections
}
public static serialize(
entityNumber: number,
connections: IConnection[],
getType: (entityNumber: number) => string,
entNrWhitelist?: Set<number>
): { connections: BPS.IConnection; neighbours: number[] } {
const serialized: BPS.IConnection = {}
const neighbours: number[] = []
for (const connection of connections) {
const isEntity1 = connection.entityNumber1 === entityNumber
const side = isEntity1 ? connection.entitySide1 : connection.entitySide2
const color = connection.color
const otherEntNr = isEntity1 ? connection.entityNumber2 : connection.entityNumber1
const otherEntSide = isEntity1 ? connection.entitySide2 : connection.entitySide1
if (entNrWhitelist && !entNrWhitelist.has(otherEntNr)) continue
if (color === 'copper' && getType(otherEntNr) === 'electric_pole') {
if (getType(entityNumber) === 'electric_pole') {
neighbours.push(otherEntNr)
} else if (getType(entityNumber) === 'power_switch') {
const SIDE = `Cu${side - 1}`
if (serialized[SIDE] === undefined) {
serialized[SIDE] = []
}
const c = serialized[SIDE] as BPS.IWireColor[]
c.push({
entity_id: otherEntNr,
wire_id: 0,
})
}
} else if (color === 'red' || color === 'green') {
if (serialized[side] === undefined) {
serialized[side] = {}
}
const SIDE = serialized[side] as BPS.IConnSide
if (SIDE[color] === undefined) {
SIDE[color] = []
}
SIDE[color].push({
entity_id: otherEntNr,
circuit_id: otherEntSide,
})
}
}
return {
connections: Object.keys(serialized).length === 0 ? undefined : serialized,
neighbours: neighbours.length === 0 ? undefined : neighbours,
}
}
private static toPoleConnection(entityNumber1: number, entityNumber2: number): IConnection {
return {
color: 'copper',
entityNumber1,
entityNumber2,
entitySide1: 1,
entitySide2: 1,
}
}
public create(connection: IConnection): void {
const hash = WireConnections.hash(connection)
if (this.connections.has(hash)) return
this.bp.history
.updateMap(this.connections, hash, connection, 'Connect entities')
.onDone(this.onCreateOrRemoveConnection.bind(this))
.commit()
}
private remove(connection: IConnection): void {
const hash = WireConnections.hash(connection)
if (!this.connections.has(hash)) return
this.bp.history
.updateMap(this.connections, hash, undefined, 'Disconnect entities')
.onDone(this.onCreateOrRemoveConnection.bind(this))
.commit()
}
private onCreateOrRemoveConnection(newValue: IConnection, oldValue: IConnection): void {
if (newValue) {
this.emit('create', WireConnections.hash(newValue), newValue)
} else if (oldValue) {
this.emit('remove', WireConnections.hash(oldValue), oldValue)
}
}
public get(hash: string): IConnection {
return this.connections.get(hash)
}
public forEach(fn: (value: IConnection, key: string) => void): void {
this.connections.forEach(fn)
}
public createEntityConnections(
entityNumber: number,
connections: BPS.IConnection,
neighbours: number[]
): void {
const conns = WireConnections.deserialize(entityNumber, connections, neighbours)
for (const conn of conns) {
this.create(conn)
}
}
public removeEntityConnections(entityNumber: number): void {
const conns = this.getEntityConnections(entityNumber)
for (const conn of conns) {
this.remove(conn)
}
}
public getEntityConnectionHashes(entityNumber: number): string[] {
return this.connections.getEntityConnectionHashes(entityNumber)
}
public getEntityConnections(entityNumber: number): IConnection[] {
return this.connections.getEntityConnections(entityNumber)
}
public serializeConnectionData(
entityNumber: number,
entNrWhitelist?: Set<number>
): { connections: BPS.IConnection; neighbours: number[] } {
const connections = this.getEntityConnections(entityNumber)
return WireConnections.serialize(
entityNumber,
connections,
entityNumber => this.bp.entities.get(entityNumber).type,
entNrWhitelist
)
}
public connectPowerPole(entityNumber: number): void {
const entity = this.bp.entities.get(entityNumber)
if (entity.type !== 'electric_pole') return
const areaSize = (entity.maxWireDistance + 1) * 2
const poles = this.bp.entityPositionGrid
.getEntitiesInArea({
x: entity.position.x,
y: entity.position.y,
w: areaSize,
h: areaSize,
})
.filter(
e =>
e !== entity &&
e.type === 'electric_pole' &&
this.getEntityConnections(e.entityNumber).filter(c => c.color === 'copper')
.length < MAX_POLE_CONNECTION_COUNT &&
U.pointInCircle(
e.position,
entity.position,
Math.min(e.maxWireDistance, entity.maxWireDistance)
)
)
.sort(
(a, b) =>
U.manhattenDistance(a.position, entity.position) -
U.manhattenDistance(b.position, entity.position)
)
let counter = MAX_POLE_CONNECTION_COUNT
const blacklist = new Set<number>()
for (const pole of poles) {
if (counter === 0) break
if (blacklist.has(pole.entityNumber)) continue
counter -= 1
blacklist.add(pole.entityNumber)
for (const connection of this.getEntityConnections(pole.entityNumber)) {
if (connection.color === 'copper') {
const otherEntNr =
pole.entityNumber === connection.entityNumber1
? connection.entityNumber2
: connection.entityNumber1
blacklist.add(otherEntNr)
}
}
this.create(WireConnections.toPoleConnection(entity.entityNumber, pole.entityNumber))
}
}
public generatePowerPoleWires(): void {
interface IPole extends IPoint {
entityNumber: number
name: string
}
const poles: IPole[] = this.bp.entities
.filter(e => e.type === 'electric_pole')
.map(e => ({
entityNumber: e.entityNumber,
name: e.name,
x: e.position.x,
y: e.position.y,
}))
if (poles.length < 2) return
const poleSetsTriangles = U.pointsToTriangles(poles).map(tri =>
tri
.flatMap<[IPole, IPole]>((_, i, arr) => {
if (i === arr.length - 1) return [[arr[0], arr[i]]]
return [[arr[i], arr[i + 1]]]
})
.filter(([pole0, pole1]) =>
U.pointInCircle(
pole0,
pole1,
Math.min(
FD.entities[pole0.name].maximum_wire_distance,
FD.entities[pole1.name].maximum_wire_distance
)
)
)
)
const poleSets = poleSetsTriangles
.flat()
.sort((a, b) => {
const minPos = (l: IPole[]): number =>
Math.min(l[0].x, l[1].x) + Math.min(l[0].y, l[1].y)
return minPos(a) - minPos(b)
})
.sort((a, b) => U.manhattenDistance(a[0], a[1]) - U.manhattenDistance(b[0], b[1]))
const hashPoleSet = ([pole0, pole1]: [IPole, IPole]): string => {
const min = Math.min(pole0.entityNumber, pole1.entityNumber)
const max = Math.max(pole0.entityNumber, pole1.entityNumber)
return `${min}-${max}`
}
const hashedTriangles = poleSetsTriangles
.filter(lines => lines.length === 3)
.map(lines => lines.map(hashPoleSet))
const finalPoleSets: IPole[][] = []
const addedMap: Set<string> = new Set()
while (poleSets.length) {
const poleSet = poleSets.shift()
const hash = hashPoleSet(poleSet)
const formsATriangle = hashedTriangles
.filter(tri => tri.includes(hash))
.map(tri => tri.filter(h => h !== hash))
.map(oLines => oLines.every(h => addedMap.has(h)))
.reduce((acc, bool) => acc || bool, false)
if (!formsATriangle) {
finalPoleSets.push(poleSet)
addedMap.add(hash)
}
}
for (const poleSet of finalPoleSets) {
this.create(
WireConnections.toPoleConnection(poleSet[0].entityNumber, poleSet[1].entityNumber)
)
}
}
public getPowerPoleDirection(entityNumber: number): number {
const connections = this.getEntityConnections(entityNumber).map(conn =>
entityNumber === conn.entityNumber1 ? conn.entityNumber2 : conn.entityNumber1
)
if (connections.length === 0) return 0
const points = connections
.map(entNr => this.bp.entities.get(entNr))
.filter(e => !!e)
.map(ent => ent.position)
if (points.length === 0) return 0
return getPowerPoleRotation(this.bp.entities.get(entityNumber).position, points)
function getPowerPoleRotation(centre: IPoint, points: IPoint[]): number {
const sectorSum = points
.map(p =>
U.getAngle(0, 0, p.x - centre.x, (p.y - centre.y) * -1 /* invert Y axis */)
)
.map(angleToSector)
.reduce((acc, sec) => acc + sec, 0)
return Math.floor(sectorSum / points.length) * 2
function angleToSector(angle: number): 0 | 1 | 2 | 3 {
const cwAngle = 360 - angle
const sectorAngle = 360 / 8
const offset = sectorAngle * 1.5
let newAngle = cwAngle - offset
if (Math.sign(newAngle) === -1) {
newAngle = 360 + newAngle
}
const sector = Math.floor(newAngle / sectorAngle)
return (sector % 4) as 0 | 1 | 2 | 3
}
}
}
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Location } from '@angular/common';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { ignoreElements } from 'rxjs/operators';
import { StorageService } from './storage.service';
import { defaultMultiWindowConfig, NGXMW_CONFIG } from './config.provider';
import { MultiWindowConfig } from '../types/multi-window.config';
import { AppWindow, KnownAppWindow, WindowData } from '../types/window.type';
import { Message, MessageTemplate, MessageType } from '../types/message.type';
import { WindowRef } from '../providers/window.provider';
import { WindowSaveStrategy } from '../types/window-save-strategy.enum';
@Injectable({
providedIn: 'root',
})
export class MultiWindowService {
private config: MultiWindowConfig;
private myWindow: WindowData;
private heartbeatId = null;
private windowScanId = null;
private knownWindows: KnownAppWindow[] = [];
/**
* A hash that keeps track of subjects for all send messages
*/
private messageTracker: { [key: string]: Subject<string> } = {};
/**
* A copy of the outbox that is regularly written to the local storage
*/
private outboxCache: { [key: string]: Message } = {};
/**
* A subject to subscribe to in order to get notified about messages send to this window
*/
private messageSubject: Subject<Message> = new Subject<Message>();
/**
* A subject to subscribe to in order to get notified about all known windows
*/
private windowSubject: Subject<KnownAppWindow[]> = new BehaviorSubject<KnownAppWindow[]>(this.knownWindows);
private static generateId(): string {
return new Date().getTime().toString(36).substr(-4) + Math.random().toString(36).substr(2, 9);
}
private tryMatchWindowKey(source: string): string {
const nameRegex = new RegExp(
// Escape any potential regex-specific chars in the keyPrefix which may be changed by the dev
this.config.keyPrefix.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + 'w_([a-z0-9]+)'
);
const match = source.match(nameRegex);
if (match !== null) {
return match[1];
}
return null;
}
private generatePayloadKey({messageId}: Message): string {
return this.config.keyPrefix + 'payload_' + messageId;
}
private generateWindowKey(windowId: string): string {
return this.config.keyPrefix + 'w_' + windowId;
}
private isWindowKey(key: string): boolean {
return key.indexOf(this.config.keyPrefix + 'w_') === 0;
}
constructor(@Inject(NGXMW_CONFIG) customConfig: MultiWindowConfig, @Optional() private location: Location,
private storageService: StorageService, private windowRef: WindowRef) {
this.config = {...defaultMultiWindowConfig, ...customConfig};
let windowId: string;
if (this.location) {
// Try to extract the new window name from the location path
windowId = this.tryMatchWindowKey(this.location.path(true));
}
// Only check the name save strategy if no id has been extracted from the path already
if (!windowId && this.config.windowSaveStrategy !== WindowSaveStrategy.NONE) {
// There might be window data stored in the window.name property, try restoring it
const storedWindowData = this.windowRef.nativeWindow.name;
if (this.config.windowSaveStrategy === WindowSaveStrategy.SAVE_BACKUP) {
// There should be a JSON string in the window.name, try parsing it and set the values
try {
const storedJsonData = JSON.parse(storedWindowData);
windowId = storedJsonData.ngxmw_id;
this.windowRef.nativeWindow.name = storedJsonData.backup;
} catch (ex) { // Swallow JSON parsing exceptions, as we can't handle them anyway
}
} else {
windowId = this.tryMatchWindowKey(storedWindowData);
if (this.config.windowSaveStrategy === WindowSaveStrategy.SAVE_WHEN_EMPTY) {
this.windowRef.nativeWindow.name = '';
}
}
}
this.init(windowId);
this.start();
}
get name(): string {
return this.myWindow.name;
}
set name(value: string) {
this.myWindow.name = value;
}
get id(): string {
return this.myWindow.id;
}
/**
* An observable to subscribe to. It emits all messages the current window receives.
* After a message has been emitted by this observable it is marked as read, so the sending window
* gets informed about successful delivery.
*/
public onMessage(): Observable<Message> {
return this.messageSubject.asObservable();
}
/**
* An observable to subscribe to. It emits the array of known windows
* whenever it is read again from the localstorage.
*
* This Observable emits the last list of known windows on subscription
* (refer to rxjs BehaviorSubject).
*
* Use {@link getKnownWindows} to get the current list of
* known windows or if you only need a snapshot of that list.
*
* @see {@link MultiWindowConfig#newWindowScan}
* @returns
*/
public onWindows(): Observable<KnownAppWindow[]> {
return this.windowSubject.asObservable();
}
/**
* Get the latest list of known windows.
*
* Use {@link onWindows} to get an observable which emits
* whenever is updated.
*/
public getKnownWindows() {
return this.knownWindows;
}
/**
* Start so that the current instance of the angular app/service/tab participates in the cross window communication.
* It starts the interval-based checking for messages and updating the heartbeat.
*
* Note: There should be no need to call this method in production apps. It will automatically be called internally
* during service construction (see {@link MultiWindowService} constructor)
*/
public start(): void {
if (!this.heartbeatId) {
this.heartbeatId = setInterval(this.heartbeat, this.config.heartbeat);
}
if (!this.windowScanId) {
this.windowScanId = setInterval(this.scanForWindows, this.config.newWindowScan);
}
}
/**
* Stop the current instance of the angular app/service/tab from participating in the cross window communication.
* It stops the interval-based checking for messages and updating the heartbeat.
*
* Note: There should be no need to call this method in production apps.
*/
public stop(): void {
if (this.heartbeatId) {
clearInterval(this.heartbeatId);
this.heartbeatId = null;
}
if (this.windowScanId) {
clearInterval(this.windowScanId);
this.windowScanId = null;
}
}
/**
* Remove the current window representation from the localstorage.
*
* Note: Unless you {@link stop}ped the service the window representation will be
* recreated after {@link MultiWindowConfig#heartbeat} milliseconds
*/
public clear(): void {
this.storageService.removeLocalItem(this.generateWindowKey(this.myWindow.id));
}
/**
* Send a message to another window.
*
* @param recipientId The ID of the recipient window.
* @param event Custom identifier to distinguish certain events
* @param data Custom data to contain the data for the event
* @param payload Further data to be passed to the recipient window via a separate entry in the localstorage
* @returns An observable that emits the messageId once the message has been put into
* the current windows outbox. It completes on successful delivery and fails if the delivery times out.
*/
public sendMessage(recipientId: string, event: string, data: any, payload?: any): Observable<string> {
const messageId = this.pushToOutbox({
recipientId,
type: MessageType.MESSAGE,
event,
data,
payload,
});
this.messageTracker[messageId] = new Subject<string>();
return this.messageTracker[messageId].asObservable();
}
/**
* Create a new window and get informed once it has been created.
*
* Note: The actual window "creation" of redirection needs to be performed by
* the library user. This method only returns helpful information on how to
* do that
*
* The returned object contains three properties:
*
* windowId: An id generated to be assigned to the newly created window
*
* urlString: This string must be included in the url the new window loads.
* It does not matter whether it is in the path, query or hash part
*
* created: An observable that will complete after new window was opened and was able
* to receive a message. If the window does not start consuming messages within
* {@link MultiWindowConfig#messageTimeout}, this observable will fail, although
* the window might become present after that. The Observable will never emit any elements.
*/
public newWindow(): { windowId: string, urlString: string, created: Observable<string> } {
if (this.location === null) {
// Reading information from the URL is only possible with the Location provider. If
// this window does not have one, another one will have none as well and thus would
// not be able to read its new windowId from the url path
throw new Error('No Location Provider present');
}
const newWindowId = MultiWindowService.generateId();
const messageId = this.pushToOutbox({
recipientId: newWindowId,
type: MessageType.PING,
event: undefined,
data: undefined,
payload: undefined,
});
this.messageTracker[messageId] = new Subject<string>();
return {
windowId: newWindowId,
urlString: this.generateWindowKey(newWindowId),
created: this.messageTracker[messageId].pipe(ignoreElements()),
};
}
public saveWindow(): void {
if (this.config.windowSaveStrategy !== WindowSaveStrategy.NONE) {
const windowId = this.generateWindowKey(this.id);
if ((this.config.windowSaveStrategy === WindowSaveStrategy.SAVE_WHEN_EMPTY && !this.windowRef.nativeWindow.name)
|| this.config.windowSaveStrategy === WindowSaveStrategy.SAVE_FORCE) {
this.windowRef.nativeWindow.name = windowId;
} else if (this.config.windowSaveStrategy === WindowSaveStrategy.SAVE_BACKUP) {
this.windowRef.nativeWindow.name = JSON.stringify({ngxmw_id: windowId, backup: this.windowRef.nativeWindow.name});
}
}
}
private init(windowId?: string): void {
const windowKey = windowId
? this.generateWindowKey(windowId)
: this.storageService.getWindowName();
let windowData: WindowData | null = null;
if (windowKey && this.isWindowKey(windowKey)) {
windowData = this.storageService.getLocalObject<WindowData>(windowKey);
}
if (windowData !== null) {
// Restore window information from storage
this.myWindow = {
id: windowData.id,
name: windowData.name,
heartbeat: windowData.heartbeat,
};
} else {
const myWindowId = windowId || MultiWindowService.generateId();
this.myWindow = {
id: myWindowId,
name: 'AppWindow ' + myWindowId,
heartbeat: -1,
};
}
this.storageService.setWindowName(windowKey);
// Scan for already existing windows
this.scanForWindows();
// Trigger heartbeat for the first time
this.heartbeat();
}
private pushToOutbox({recipientId, type, event, data, payload}: MessageTemplate,
messageId: string = MultiWindowService.generateId()): string {
if (recipientId === this.id) {
throw new Error('Cannot send messages to self');
}
this.outboxCache[messageId] = {
messageId,
recipientId,
senderId: this.myWindow.id,
sendTime: new Date().getTime(),
type,
event,
data,
payload,
send: false,
};
return messageId;
}
private heartbeat = () => {
const now = new Date().getTime();
// Check whether there are new messages for the current window in the other window's outboxes
// Store the ids of all messages we receive in this iteration
const receivedMessages: string[] = [];
this.knownWindows.forEach(windowData => {
// Load the window from the localstorage
const appWindow = this.storageService.getLocalObject<AppWindow>(this.generateWindowKey(windowData.id));
if (appWindow === null) {
// No window found, it possibly got closed/removed since our last scanForWindow
return;
}
if (appWindow.id === this.myWindow.id) {
// Ignore messages from myself (not done using Array.filter to reduce array iterations)
// but check for proper last heartbeat time
if (this.myWindow.heartbeat !== -1 && this.myWindow.heartbeat !== appWindow.heartbeat) {
// The heartbeat value in the localstorage is a different one than the one we wrote into localstorage
// during our last heartbeat. There are probably two app windows
// using the same window id => change the current windows id
this.myWindow.id = MultiWindowService.generateId();
// tslint:disable-next-line:no-console
console.warn('Window ' + appWindow.id + ' detected that there is probably another instance with' +
' this id, changed id to ' + this.myWindow.id);
this.storageService.setWindowName(this.generateWindowKey(this.myWindow.id));
}
return;
}
if (now - appWindow.heartbeat > this.config.windowTimeout) {
// The window seems to be dead, remove the entry from the localstorage
this.storageService.removeLocalItem(this.generateWindowKey(appWindow.id));
}
// Update the windows name and heartbeat value in the list of known windows (that's what we iterate over)
windowData.name = appWindow.name;
windowData.heartbeat = appWindow.heartbeat;
if (appWindow.messages && appWindow.messages.length > 0) {
// This other window has messages, so iterate over the messages the other window has
appWindow.messages.forEach(message => {
if (message.recipientId !== this.myWindow.id) {
// The message is not targeted to the current window
return;
}
if (message.type === MessageType.MESSAGE_RECEIVED) {
// It's a message to inform the current window that a previously sent message from the
// current window has been processed by the recipient window
// Trigger the observable to complete and then remove it
if (this.messageTracker[message.messageId]) {
this.messageTracker[message.messageId].complete();
}
delete this.messageTracker[message.messageId];
// Remove the message from the outbox, as the transfer is complete
delete this.outboxCache[message.messageId];
} else {
receivedMessages.push(message.messageId);
// Check whether we already processed that message. If that's the case we've got a 'message_received'
// confirmation in our own outbox.
if (!(this.outboxCache[message.messageId] &&
this.outboxCache[message.messageId].type === MessageType.MESSAGE_RECEIVED)) {
// We did not process that message
// Create a new message for the message sender in the current window's
// outbox that the message has been processed (reuse the message id for that)
this.pushToOutbox({
recipientId: message.senderId,
type: MessageType.MESSAGE_RECEIVED,
event: undefined,
}, message.messageId);
// Process it locally, unless it's just a PING message
if (message.type !== MessageType.PING) {
if (message.payload === true) {
// The message has a separate payload
const payloadKey = this.generatePayloadKey(message);
message.payload = this.storageService.getLocalObject<any>(payloadKey);
this.storageService.removeLocalItem(payloadKey);
}
this.messageSubject.next(message);
}
}
}
});
}
});
// Iterate over the outbox to clean it up, process timeouts and payloads
Object.keys(this.outboxCache).forEach(messageId => {
const message = this.outboxCache[messageId];
if (message.type === MessageType.MESSAGE_RECEIVED && !receivedMessages.some(msgId => msgId === messageId)) {
// It's a message confirmation and we did not receive the 'original' method for that confirmation
// => the sender has received our confirmation and removed the message from it's outbox, thus we can
// safely remove the message confirmation as well
delete this.outboxCache[messageId];
} else if (message.type !== MessageType.MESSAGE_RECEIVED && now - message.sendTime > this.config.messageTimeout) {
// Delivering the message has failed, as the target window did not pick it up in time
// The type of message doesn't matter for that
delete this.outboxCache[messageId];
if (this.messageTracker[messageId]) {
this.messageTracker[messageId].error('Timeout');
}
delete this.messageTracker[messageId];
} else if (message.type === MessageType.MESSAGE && message.send === false) {
if (message.payload !== undefined && message.payload !== true) {
// Message has a payload that has not been moved yet, so move that in a separate localstorage key
this.storageService.setLocalObject(this.generatePayloadKey(message), message.payload);
message.payload = true;
}
this.messageTracker[message.messageId].next(message.messageId);
// Set property to undefined, as we do not need to encode "send:true" in the localstorage json multiple times
message.send = undefined;
}
});
this.storageService.setLocalObject(this.generateWindowKey(this.myWindow.id), {
heartbeat: now,
id: this.myWindow.id,
name: this.myWindow.name,
messages: Object.keys(this.outboxCache).map(key => this.outboxCache[key]),
});
if (this.myWindow.heartbeat === -1) {
// This was the first heartbeat run for the local window, so rescan for known windows to get
// the current (new) window in the list
this.scanForWindows();
}
// Store the new heartbeat value in the local windowData copy
this.myWindow.heartbeat = now;
}
private scanForWindows = () => {
this.knownWindows = this.storageService.getLocalObjects<WindowData>(
this.storageService.getLocalItemKeys().filter((key) => this.isWindowKey(key)))
.map(({id, name, heartbeat}: WindowData) => {
return {
id,
name,
heartbeat,
stalled: new Date().getTime() - heartbeat > this.config.heartbeat * 2,
self: this.myWindow.id === id,
};
});
this.windowSubject.next(this.knownWindows);
}
} | the_stack |
import * as collabs from "@collabs/collabs";
import { CRDTContainer } from "@collabs/container";
import seedrandom from "seedrandom";
// Minesweeper Collab
interface GameSettings {
readonly width: number;
readonly height: number;
readonly fractionMines: number;
}
enum FlagStatus {
NONE,
FLAG,
QUESTION_FLAG,
}
enum TileStatus {
BLANK,
FLAG,
QUESTION_FLAG,
REVEALED_EMPTY,
REVEALED_MINE,
}
class TileCollab extends collabs.CObject {
private readonly revealed: collabs.TrueWinsCBoolean;
private readonly flag: collabs.LWWCVariable<FlagStatus>;
number: number = 0;
constructor(initToken: collabs.InitToken, readonly isMine: boolean) {
super(initToken);
this.revealed = this.addChild(
"revealed",
collabs.Pre(collabs.TrueWinsCBoolean)()
);
this.flag = this.addChild(
"flag",
collabs.Pre(collabs.LWWCVariable)<FlagStatus>(FlagStatus.NONE)
);
}
reveal() {
this.revealed.value = true;
}
cycleFlag() {
this.flag.value = (this.flag.value + 1) % 3;
}
isRevealed(): boolean {
return this.revealed.value;
}
get status(): TileStatus {
if (this.revealed.value) {
return this.isMine ? TileStatus.REVEALED_MINE : TileStatus.REVEALED_EMPTY;
} else {
switch (this.flag.value) {
case FlagStatus.NONE:
return TileStatus.BLANK;
case FlagStatus.FLAG:
return TileStatus.FLAG;
case FlagStatus.QUESTION_FLAG:
return TileStatus.QUESTION_FLAG;
}
}
}
get letterCode(): string {
switch (this.status) {
case TileStatus.BLANK:
return " ";
case TileStatus.FLAG:
return "⚑";
case TileStatus.QUESTION_FLAG:
return "?";
case TileStatus.REVEALED_EMPTY:
return this.number + "";
case TileStatus.REVEALED_MINE:
return "✹";
}
}
}
enum GameStatus {
IN_PROGRESS,
WON,
LOST,
}
class MinesweeperCollab extends collabs.CObject {
readonly tiles: TileCollab[][];
constructor(
initToken: collabs.InitToken,
readonly width: number,
readonly height: number,
fractionMines: number,
startX: number,
startY: number,
seed: string
) {
super(initToken);
// Adjust fractionMines to account for fact that start
// won't be a mine
const size = width * height;
if (size > 1) fractionMines *= size / (size - 1);
// Place mines and init tiles
const rng = seedrandom(seed);
this.tiles = new Array<TileCollab[]>(width);
for (let x = 0; x < width; x++) {
this.tiles[x] = new Array<TileCollab>(height);
for (let y = 0; y < height; y++) {
const isMine =
x === startX && y === startY ? false : rng() < fractionMines;
this.tiles[x][y] = this.addChild(
x + ":" + y,
collabs.Pre(TileCollab)(isMine)
);
}
}
// Compute neighbor numbers
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
this.tiles[x][y].number = 0;
for (let neighbor of this.neighbors(x, y)) {
if (this.tiles[neighbor[0]][neighbor[1]].isMine)
this.tiles[x][y].number++;
}
}
}
}
leftClick(x: number, y: number) {
let tile = this.tiles[x][y];
if (!tile.isRevealed()) {
// Reveal it
let status = tile.status;
if (status === TileStatus.BLANK || status === TileStatus.QUESTION_FLAG) {
if (tile.isMine) tile.reveal();
else this.revealSafe(x, y);
}
} else if (tile.status === TileStatus.REVEALED_EMPTY) {
// If all indicated mines are flagged, reveal all
// non-flagged tiles
let neighbors = this.neighbors(x, y);
let flaggedCount = 0;
for (let neighbor of neighbors) {
let neighborTile = this.tiles[neighbor[0]][neighbor[1]];
if (neighborTile.status === TileStatus.FLAG) flaggedCount++;
}
if (flaggedCount === tile.number) {
// Reveal all non-revealed non-flagged neighbors,
// as if clicked
for (let neighbor of neighbors) {
let neighborTile = this.tiles[neighbor[0]][neighbor[1]];
if (neighborTile.status === TileStatus.BLANK)
this.leftClick(neighbor[0], neighbor[1]);
}
}
}
}
/**
* Recursively traverses the board starting from (x, y) until there is
* at least one neighbor mine.
* It assumes that (x, y) is not a mine.
*/
private revealSafe(x: number, y: number) {
this.tiles[x][y].reveal();
if (this.tiles[x][y].number === 0) {
// Recursively call reveal on the non-revealed (or flagged) neighbors
for (let neighbor of this.neighbors(x, y)) {
let [x_neighbor, y_neighbor] = neighbor;
if (!this.tiles[x_neighbor][y_neighbor].isRevealed()) {
this.revealSafe(x_neighbor, y_neighbor);
}
}
}
}
rightClick(x: number, y: number) {
if (!this.tiles[x][y].isRevealed()) {
this.tiles[x][y].cycleFlag();
}
}
/**
* A user wins when only mines are unrevealed,
* and loses if any mines are revealed.
*/
winStatus(): GameStatus {
let allEmptyRevealed = true;
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
let tile = this.tiles[x][y];
if (tile.isMine && tile.isRevealed()) return GameStatus.LOST;
if (!tile.isMine && !tile.isRevealed()) allEmptyRevealed = false;
}
}
return allEmptyRevealed ? GameStatus.WON : GameStatus.IN_PROGRESS;
}
// <------- UTILITIES ------->
/**
* Given a coordinate, it finds all of its neighbors.
* A neighbor is defined as the 8 surrounding cells (unless on the border,
* which would be any surrounding cell not outside the board).
* Source: https://stackoverflow.com/questions/652106/finding-neighbours-in-a-two-dimensional-array
* PD.: Sorry for being lazy and looking this up.
*/
private neighbors(x: number, y: number): Array<[number, number]> {
let neighbors: Array<[number, number]> = [];
for (
let i = Math.max(0, x - 1);
i <= Math.min(x + 1, this.width - 1);
i++
) {
for (
let j = Math.max(0, y - 1);
j <= Math.min(y + 1, this.height - 1);
j++
) {
if (x !== i || y !== j) {
neighbors.push([i, j]);
}
}
}
return neighbors;
}
}
(async function () {
const board = document.getElementById("board");
const winText = document.getElementById("winText")!;
/* Creating the grid */
// TODO: make refresh not destroy board each time?
// TODO: if game over, say win/lose and display whole board
function refreshDisplay() {
// @ts-ignore
board.innerHTML = "";
let state =
currentState.value === "settings"
? currentSettings.value
: currentGame.value.get();
for (let y = 0; y < state.height; y++) {
let row = document.createElement("tr");
for (let x = 0; x < state.width; x++) {
let box = document.createElement("th");
box.setAttribute("row", y.toString());
box.setAttribute("col", x.toString());
box.className = "cell";
box.id = "row_" + y.toString() + "_" + x.toString();
if (currentState.value === "game") {
let game = state as MinesweeperCollab;
let tile = game.tiles[x][y];
box.addEventListener("click", (event) => {
if (event.button === 0) game.leftClick(x, y);
});
box.addEventListener("contextmenu", function (e) {
e.preventDefault();
game.rightClick(x, y);
});
let letterCode = game.tiles[x][y].letterCode;
if (letterCode === "0") letterCode = " ";
box.appendChild(document.createTextNode(letterCode));
// Set the text and background colors
switch (tile.status) {
case TileStatus.BLANK:
case TileStatus.FLAG:
case TileStatus.QUESTION_FLAG:
box.style.color = "black";
box.style.backgroundColor = "gray";
break;
case TileStatus.REVEALED_EMPTY:
box.style.color = "black";
switch (tile.number) {
case 0:
box.style.backgroundColor = "Gainsboro";
break;
case 1:
box.style.backgroundColor = "#b3e5fc";
break;
case 2:
box.style.backgroundColor = "#c8e6c9";
break;
case 3:
box.style.backgroundColor = "#f8bbd0";
break;
case 4:
box.style.backgroundColor = "#e1bee7";
break;
case 5:
box.style.backgroundColor = "#bcaaa4";
break;
case 6:
box.style.backgroundColor = "#ffccbc";
break;
case 7:
box.style.backgroundColor = "#fff9c4";
break;
case 8:
box.style.backgroundColor = "#ffcdd2";
break;
}
break;
case TileStatus.REVEALED_MINE:
box.style.color = "red";
box.style.backgroundColor = "Gainsboro";
}
} else {
// It's GameSettings
let settings = state as GameSettings;
box.addEventListener("click", (event) => {
if (event.button === 0) {
// Start the game, with this tile safe
let newGame = currentGame
.set(
settings.width,
settings.height,
settings.fractionMines,
x,
y,
Math.random() + ""
)
.get();
currentState.value = "game";
newGame.leftClick(x, y);
}
});
box.appendChild(document.createTextNode(" "));
box.style.backgroundColor = "gray";
}
row.appendChild(box);
}
// @ts-ignore
board.appendChild(row);
}
if (state instanceof MinesweeperCollab) {
let game = state as MinesweeperCollab;
switch (game.winStatus()) {
case GameStatus.WON:
winText.innerHTML = "You won!";
break;
case GameStatus.LOST:
winText.innerHTML = "You lost.";
break;
case GameStatus.IN_PROGRESS:
winText.innerHTML = "";
}
} else {
winText.innerHTML = "";
}
}
let valid = true;
function invalidate() {
if (valid) {
valid = false;
setTimeout(() => {
refreshDisplay();
valid = true;
}, 0);
}
}
const widthInput = document.getElementById("width") as HTMLInputElement;
const heightInput = document.getElementById("height") as HTMLInputElement;
const percentMinesInput = document.getElementById(
"percentMines"
) as HTMLInputElement;
function settingsFromInput(): GameSettings {
return {
width: widthInput.valueAsNumber,
height: heightInput.valueAsNumber,
fractionMines: percentMinesInput.valueAsNumber / 100,
};
}
const container = new CRDTContainer();
const currentGame = container.registerCollab(
"currentGame",
collabs.Pre(collabs.LWWMutCVariable)(
collabs.ConstructorAsFunction(MinesweeperCollab)
)
);
const currentSettings = container.registerCollab(
"currentSettings",
collabs.Pre(collabs.LWWCVariable)(settingsFromInput())
);
// TODO: FWW instead of LWW? Also backup to view all games
// in case of concurrent progress.
const currentState = container.registerCollab(
"currentState",
collabs.Pre(collabs.LWWCVariable)<"game" | "settings">("settings")
);
container.on("Change", invalidate);
// Respond to user input.
document.getElementById("newGame")!.onclick = function () {
currentSettings.value = settingsFromInput();
currentState.value = "settings";
};
// Other event listeners are added directly in refreshDisplay.
await container.load();
// Display loaded state.
invalidate();
// Ready.
container.ready();
})(); | the_stack |
import {JsonArray, JsonObject, JsonValue} from 'type-fest';
export enum WebSocketOpCode {
/**
* The initial message sent by obs-websocket to newly connected clients.
*
* Initial OBS Version: 5.0.0
*/
Hello = 0,
/**
* The message sent by a newly connected client to obs-websocket in response to a `Hello`.
*
* Initial OBS Version: 5.0.0
*/
Identify = 1,
/**
* The response sent by obs-websocket to a client after it has successfully identified with obs-websocket.
*
* Initial OBS Version: 5.0.0
*/
Identified = 2,
/**
* The message sent by an already-identified client to update identification parameters.
*
* Initial OBS Version: 5.0.0
*/
Reidentify = 3,
/**
* The message sent by obs-websocket containing an event payload.
*
* Initial OBS Version: 5.0.0
*/
Event = 5,
/**
* The message sent by a client to obs-websocket to perform a request.
*
* Initial OBS Version: 5.0.0
*/
Request = 6,
/**
* The message sent by obs-websocket in response to a particular request from a client.
*
* Initial OBS Version: 5.0.0
*/
RequestResponse = 7,
/**
* The message sent by a client to obs-websocket to perform a batch of requests.
*
* Initial OBS Version: 5.0.0
*/
RequestBatch = 8,
/**
* The message sent by obs-websocket in response to a particular batch of requests from a client.
*
* Initial OBS Version: 5.0.0
*/
RequestBatchResponse = 9,
}
/* eslint-disable no-bitwise, @typescript-eslint/prefer-literal-enum-member */
export enum EventSubscription {
/**
* Subcription value used to disable all events.
*
* Initial OBS Version: 5.0.0
*/
None = 0,
/**
* Subscription value to receive events in the `General` category.
*
* Initial OBS Version: 5.0.0
*/
General = (1 << 0),
/**
* Subscription value to receive events in the `Config` category.
*
* Initial OBS Version: 5.0.0
*/
Config = (1 << 1),
/**
* Subscription value to receive events in the `Scenes` category.
*
* Initial OBS Version: 5.0.0
*/
Scenes = (1 << 2),
/**
* Subscription value to receive events in the `Inputs` category.
*
* Initial OBS Version: 5.0.0
*/
Inputs = (1 << 3),
/**
* Subscription value to receive events in the `Transitions` category.
*
* Initial OBS Version: 5.0.0
*/
Transitions = (1 << 4),
/**
* Subscription value to receive events in the `Filters` category.
*
* Initial OBS Version: 5.0.0
*/
Filters = (1 << 5),
/**
* Subscription value to receive events in the `Outputs` category.
*
* Initial OBS Version: 5.0.0
*/
Outputs = (1 << 6),
/**
* Subscription value to receive events in the `SceneItems` category.
*
* Initial OBS Version: 5.0.0
*/
SceneItems = (1 << 7),
/**
* Subscription value to receive events in the `MediaInputs` category.
*
* Initial OBS Version: 5.0.0
*/
MediaInputs = (1 << 8),
/**
* Subscription value to receive the `VendorEvent` event.
*
* Initial OBS Version: 5.0.0
*/
Vendors = (1 << 9),
/**
* Subscription value to receive events in the `Ui` category.
*
* Initial OBS Version: 5.0.0
*/
Ui = (1 << 10),
/**
* Helper to receive all non-high-volume events.
*
* Initial OBS Version: 5.0.0
*/
All = (General | Config | Scenes | Inputs | Transitions | Filters | Outputs | SceneItems | MediaInputs | Vendors),
/**
* Subscription value to receive the `InputVolumeMeters` high-volume event.
*
* Initial OBS Version: 5.0.0
*/
InputVolumeMeters = (1 << 16),
/**
* Subscription value to receive the `InputActiveStateChanged` high-volume event.
*
* Initial OBS Version: 5.0.0
*/
InputActiveStateChanged = (1 << 17),
/**
* Subscription value to receive the `InputShowStateChanged` high-volume event.
*
* Initial OBS Version: 5.0.0
*/
InputShowStateChanged = (1 << 18),
/**
* Subscription value to receive the `SceneItemTransformChanged` high-volume event.
*
* Initial OBS Version: 5.0.0
*/
SceneItemTransformChanged = (1 << 19),
}
/* eslint-enable no-bitwise, @typescript-eslint/prefer-literal-enum-member */
export enum RequestBatchExecutionType {
/**
* Not a request batch.
*
* Initial OBS Version: 5.0.0
*/
None = -1,
/**
* A request batch which processes all requests serially, as fast as possible.
*
* Note: To introduce artificial delay, use the `Sleep` request and the `sleepMillis` request field.
*
* Initial OBS Version: 5.0.0
*/
SerialRealtime = 0,
/**
* A request batch type which processes all requests serially, in sync with the graphics thread. Designed to provide high accuracy for animations.
*
* Note: To introduce artificial delay, use the `Sleep` request and the `sleepFrames` request field.
*
* Initial OBS Version: 5.0.0
*/
SerialFrame = 1,
/**
* A request batch type which processes all requests using all available threads in the thread pool.
*
* Note: This is mainly experimental, and only really shows its colors during requests which require lots of
* active processing, like `GetSourceScreenshot`.
*
* Initial OBS Version: 5.0.0
*/
Parallel = 2,
}
// WebSocket Message Types
export type IncomingMessage<Type = keyof IncomingMessageTypes> = Type extends keyof IncomingMessageTypes ? {
op: Type;
d: IncomingMessageTypes[Type];
} : never;
export type OutgoingMessage<Type = keyof OutgoingMessageTypes> = Type extends keyof OutgoingMessageTypes ? {
op: Type;
d: OutgoingMessageTypes[Type];
} : never;
export interface IncomingMessageTypes {
/**
* Message sent from the server immediately on client connection. Contains authentication information if auth is required. Also contains RPC version for version negotiation.
*/
[WebSocketOpCode.Hello]: {
/**
* Version number of obs-websocket
*/
obsWebSocketVersion: string;
/**
* Version number which gets incremented on each breaking change to the obs-websocket protocol.
* It's usage in this context is to provide the current rpc version that the server would like to use.
*/
rpcVersion: number;
/**
* Authentication challenge when password is required
*/
authentication?: {
challenge: string;
salt: string;
};
};
/**
* The identify request was received and validated, and the connection is now ready for normal operation.
*/
[WebSocketOpCode.Identified]: {
/**
* If rpc version negotiation succeeds, the server determines the RPC version to be used and gives it to the client
*/
negotiatedRpcVersion: number;
};
/**
* An event coming from OBS has occured. Eg scene switched, source muted.
*/
[WebSocketOpCode.Event]: EventMessage;
/**
* obs-websocket is responding to a request coming from a client
*/
[WebSocketOpCode.RequestResponse]: ResponseMessage;
}
export interface OutgoingMessageTypes {
/**
* Response to Hello message, should contain authentication string if authentication is required, along with PubSub subscriptions and other session parameters.
*/
[WebSocketOpCode.Identify]: {
/**
* Version number that the client would like the obs-websocket server to use
*/
rpcVersion: number;
/**
* Authentication challenge response
*/
authentication?: string;
/**
* Bitmask of `EventSubscription` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to.
*/
eventSubscriptions?: number;
};
/**
* Sent at any time after initial identification to update the provided session parameters.
*/
[WebSocketOpCode.Reidentify]: {
/**
* Bitmask of `EventSubscription` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to.
*/
eventSubscriptions?: number;
};
/**
* Client is making a request to obs-websocket. Eg get current scene, create source.
*/
[WebSocketOpCode.Request]: RequestMessage;
}
type EventMessage<T = keyof OBSEventTypes> = T extends keyof OBSEventTypes ? {
eventType: T;
/**
* The original intent required to be subscribed to in order to receive the event.
*/
eventIntent: number;
eventData: OBSEventTypes[T];
} : never;
export type RequestMessage<T = keyof OBSRequestTypes> = T extends keyof OBSRequestTypes ? {
requestType: T;
requestId: string;
requestData: OBSRequestTypes[T];
} : never;
export type ResponseMessage<T = keyof OBSResponseTypes> = T extends keyof OBSResponseTypes ? {
requestType: T;
requestId: string;
requestStatus: {result: true; code: number} | {result: false; code: number; comment: string};
responseData: OBSResponseTypes[T];
} : never;
// Events
export interface OBSEventTypes {
CurrentSceneCollectionChanging: {
/**
* Name of the current scene collection
*/
sceneCollectionName: string;
};
CurrentSceneCollectionChanged: {
/**
* Name of the new scene collection
*/
sceneCollectionName: string;
};
SceneCollectionListChanged: {
/**
* Updated list of scene collections
*/
sceneCollections: string[];
};
CurrentProfileChanging: {
/**
* Name of the current profile
*/
profileName: string;
};
CurrentProfileChanged: {
/**
* Name of the new profile
*/
profileName: string;
};
ProfileListChanged: {
/**
* Updated list of profiles
*/
profiles: string[];
};
ExitStarted: undefined;
InputCreated: {
/**
* Name of the input
*/
inputName: string;
/**
* The kind of the input
*/
inputKind: string;
/**
* The unversioned kind of input (aka no `_v2` stuff)
*/
unversionedInputKind: string;
/**
* The settings configured to the input when it was created
*/
inputSettings: JsonObject;
/**
* The default settings for the input
*/
defaultInputSettings: JsonObject;
};
InputRemoved: {
/**
* Name of the input
*/
inputName: string;
};
InputNameChanged: {
/**
* Old name of the input
*/
oldInputName: string;
/**
* New name of the input
*/
inputName: string;
};
InputActiveStateChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* Whether the input is active
*/
videoActive: boolean;
};
InputShowStateChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* Whether the input is showing
*/
videoShowing: boolean;
};
InputMuteStateChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* Whether the input is muted
*/
inputMuted: boolean;
};
InputVolumeChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* New volume level in multimap
*/
inputVolumeMul: number;
/**
* New volume level in dB
*/
inputVolumeDb: number;
};
InputAudioSyncOffsetChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* New sync offset in milliseconds
*/
inputAudioSyncOffset: number;
};
InputAudioTracksChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* Array of audio tracks along with their associated enable states
*/
inputAudioTracks: boolean[];
};
InputAudioMonitorTypeChanged: {
/**
* Name of the input
*/
inputName: string;
/**
* New monitor type of the input
*/
monitorType: string;
};
InputVolumeMeters: {
/**
* Array of active inputs with their associated volume levels
*/
inputs: JsonArray;
};
MediaInputPlaybackStarted: {
/**
* Name of the input
*/
inputName: string;
};
MediaInputPlaybackEnded: {
/**
* Name of the input
*/
inputName: string;
};
MediaInputActionTriggered: {
/**
* Name of the input
*/
inputName: string;
/**
* Action performed on the input. See `ObsMediaInputAction` enum
*/
mediaAction: string;
};
StreamStateChanged: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* The specific state of the output
*/
outputState: string;
};
RecordStateChanged: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* The specific state of the output
*/
outputState: string;
};
ReplayBufferStateChanged: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* The specific state of the output
*/
outputState: string;
};
VirtualcamStateChanged: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* The specific state of the output
*/
outputState: string;
};
ReplayBufferSaved: {
/**
* Path of the saved replay file
*/
savedReplayPath: string;
};
SceneItemCreated: {
/**
* Name of the scene the item was added to
*/
sceneName: string;
/**
* Name of the underlying source (input/scene)
*/
sourceName: string;
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
/**
* Index position of the item
*/
sceneItemIndex: number;
};
SceneItemRemoved: {
/**
* Name of the scene the item was removed from
*/
sceneName: string;
/**
* Name of the underlying source (input/scene)
*/
sourceName: string;
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
};
SceneItemListReindexed: {
/**
* Name of the scene
*/
sceneName: string;
/**
* Array of scene item objects
*/
sceneItems: JsonArray;
};
SceneItemEnableStateChanged: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
/**
* Whether the scene item is enabled (visible)
*/
sceneItemEnabled: boolean;
};
SceneItemLockStateChanged: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
/**
* Whether the scene item is locked
*/
sceneItemEnabled: boolean;
};
SceneItemTransformChanged: {
/**
* The name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
/**
* New transform/crop info of the scene item
*/
sceneItemTransform: JsonObject;
};
SceneCreated: {
/**
* Name of the new scene
*/
sceneName: string;
/**
* Whether the new scene is a group
*/
isGroup: boolean;
};
SceneRemoved: {
/**
* Name of the removed scene
*/
sceneName: string;
/**
* Whether the scene was a group
*/
isGroup: boolean;
};
SceneNameChanged: {
/**
* Old name of the scene
*/
oldSceneName: string;
/**
* New name of the scene
*/
sceneName: string;
};
CurrentProgramSceneChanged: {
/**
* Name of the scene that was switched to
*/
sceneName: string;
};
CurrentPreviewSceneChanged: {
/**
* Name of the scene that was switched to
*/
sceneName: string;
};
SceneListChanged: {
/**
* Updated array of scenes
*/
scenes: JsonArray;
};
StudioModeStateChanged: {
/**
* True == Enabled, False == Disabled
*/
studioModeEnabled: boolean;
};
VendorEvent: {
/**
* Name of the vendor emitting the event
*/
vendorName: string;
/**
* Vendor-provided event typedef
*/
eventType: string;
/**
* Vendor-provided event data. {} if event does not provide any data
*/
eventData: JsonObject;
};
}
// Requests and Responses
export interface OBSRequestTypes {
GetPersistentData: {
/**
* The data realm to select. `OBS_WEBSOCKET_DATA_REALM_GLOBAL` or `OBS_WEBSOCKET_DATA_REALM_PROFILE`
*/
realm: string;
/**
* The name of the slot to retrieve data from
*/
slotName: string;
};
SetPersistentData: {
/**
* The data realm to select. `OBS_WEBSOCKET_DATA_REALM_GLOBAL` or `OBS_WEBSOCKET_DATA_REALM_PROFILE`
*/
realm: string;
/**
* The name of the slot to retrieve data from
*/
slotName: string;
/**
* The value to apply to the slot
*/
slotValue: JsonValue;
};
GetSceneCollectionList: never;
SetCurrentSceneCollection: {
/**
* Name of the scene collection to switch to
*/
sceneCollectionName: string;
};
CreateSceneCollection: {
/**
* Name for the new scene collection
*/
sceneCollectionName: string;
};
GetProfileList: never;
SetCurrentProfile: {
/**
* Name of the profile to switch to
*/
profileName: string;
};
CreateProfile: {
/**
* Name for the new profile
*/
profileName: string;
};
RemoveProfile: {
/**
* Name of the profile to remove
*/
profileName: string;
};
GetProfileParameter: {
/**
* Category of the parameter to get
*/
parameterCategory: string;
/**
* Name of the parameter to get
*/
parameterName: string;
};
SetProfileParameter: {
/**
* Category of the parameter to set
*/
parameterCategory: string;
/**
* Name of the parameter to set
*/
parameterName: string;
/**
* Value of the parameter to set. Use `null` to delete
*/
parameterValue: string;
};
GetVideoSettings: never;
SetVideoSettings: {
/**
* Numerator of the fractional FPS value
*
* @restrictions >= 1
* @defaultValue Not changed
*/
fpsNumerator?: number;
/**
* Denominator of the fractional FPS value
*
* @restrictions >= 1
* @defaultValue Not changed
*/
fpsDenominator?: number;
/**
* Width of the base (canvas) resolution in pixels
*
* @restrictions >= 1, <= 4096
* @defaultValue Not changed
*/
baseWidth?: number;
/**
* Height of the base (canvas) resolution in pixels
*
* @restrictions >= 1, <= 4096
* @defaultValue Not changed
*/
baseHeight?: number;
/**
* Width of the output resolution in pixels
*
* @restrictions >= 1, <= 4096
* @defaultValue Not changed
*/
outputWidth?: number;
/**
* Height of the output resolution in pixels
*
* @restrictions >= 1, <= 4096
* @defaultValue Not changed
*/
outputHeight?: number;
};
GetStreamServiceSettings: never;
SetStreamServiceSettings: {
/**
* Type of stream service to apply. Example: `rtmp_common` or `rtmp_custom`
*/
streamServiceType: string;
/**
* Settings to apply to the service
*/
streamServiceSettings: JsonObject;
};
GetVersion: never;
GetStats: never;
BroadcastCustomEvent: {
/**
* Data payload to emit to all receivers
*/
eventData: JsonObject;
};
CallVendorRequest: {
/**
* Name of the vendor to use
*/
vendorName: string;
/**
* The request type to call
*/
requestType: string;
/**
* Object containing appropriate request data
*
* @defaultValue {}
*/
requestData?: JsonObject;
};
GetHotkeyList: never;
TriggerHotkeyByName: {
/**
* Name of the hotkey to trigger
*/
hotkeyName: string;
};
TriggerHotkeyByKeySequence: {
/**
* The OBS key ID to use. See https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h
*
* @defaultValue Not pressed
*/
keyId?: string;
/**
* Object containing key modifiers to apply
*
* @defaultValue Ignored
*/
keyModifiers?: {
/**
* Press Shift
*
* @defaultValue Not pressed
*/
shift?: boolean;
/**
* Press CTRL
*
* @defaultValue Not pressed
*/
control?: boolean;
/**
* Press ALT
*
* @defaultValue Not pressed
*/
alt?: boolean;
/**
* Press CMD (Mac)
*
* @defaultValue Not pressed
*/
command?: boolean;
};
};
Sleep: {
/**
* Number of milliseconds to sleep for (if `SERIAL_REALTIME` mode)
*
* @restrictions >= 0, <= 50000
*/
sleepMillis: number;
/**
* Number of frames to sleep for (if `SERIAL_FRAME` mode)
*
* @restrictions >= 0, <= 10000
*/
sleepFrames: number;
};
GetInputList: {
/**
* Restrict the array to only inputs of the specified kind
*
* @defaultValue All kinds included
*/
inputKind?: string;
};
GetInputKindList: {
/**
* True == Return all kinds as unversioned, False == Return with version suffixes (if available)
*
* @defaultValue false
*/
unversioned?: boolean;
};
CreateInput: {
/**
* Name of the scene to add the input to as a scene item
*/
sceneName: string;
/**
* Name of the new input to created
*/
inputName: string;
/**
* The kind of input to be created
*/
inputKind: string;
/**
* Settings object to initialize the input with
*
* @defaultValue Default settings used
*/
inputSettings?: JsonObject;
/**
* Whether to set the created scene item to enabled or disabled
*
* @defaultValue True
*/
sceneItemEnabled?: boolean;
};
RemoveInput: {
/**
* Name of the input to remove
*/
inputName: string;
};
SetInputName: {
/**
* Current input name
*/
inputName: string;
/**
* New name for the input
*/
newInputName: string;
};
GetInputDefaultSettings: {
/**
* Input kind to get the default settings for
*/
inputKind: string;
};
GetInputSettings: {
/**
* Name of the input to get the settings of
*/
inputName: string;
};
SetInputSettings: {
/**
* Name of the input to set the settings of
*/
inputName: string;
/**
* Object of settings to apply
*/
inputSettings: JsonObject;
/**
* True == apply the settings on top of existing ones, False == reset the input to its defaults, then apply settings.
*
* @defaultValue true
*/
overlay?: boolean;
};
GetInputMute: {
/**
* Name of input to get the mute state of
*/
inputName: string;
};
SetInputMute: {
/**
* Name of the input to set the mute state of
*/
inputName: string;
/**
* Whether to mute the input or not
*/
inputMuted: boolean;
};
ToggleInputMute: {
/**
* Name of the input to toggle the mute state of
*/
inputName: string;
};
GetInputVolume: {
/**
* Name of the input to get the volume of
*/
inputName: string;
};
SetInputVolume: {
/**
* Name of the input to set the volume of
*/
inputName: string;
/**
* Volume setting in mul
*
* @restrictions >= 0, <= 20
* @defaultValue `inputVolumeDb` should be specified
*/
inputVolumeMul?: number;
/**
* Volume setting in dB
*
* @restrictions >= -100, <= -26
* @defaultValue `inputVolumeMul` should be specified
*/
inputVolumeDb?: number;
};
GetInputAudioSyncOffset: {
/**
* Name of the input to get the audio sync offset of
*/
inputName: string;
};
SetInputAudioSyncOffset: {
/**
* Name of the input to set the audio sync offset of
*/
inputName: string;
/**
* New audio sync offset in milliseconds
*
* @restrictions >= -950, <= 20000
*/
inputAudioSyncOffset: number;
};
GetInputAudioMonitorType: {
/**
* Name of the input to get the audio monitor type of
*/
inputName: string;
};
SetInputAudioMonitorType: {
/**
* Name of the input to set the audio monitor type of
*/
inputName: string;
/**
* Audio monitor type
*/
monitorType: string;
};
GetInputPropertiesListPropertyItems: {
/**
* Name of the input
*/
inputName: string;
/**
* Name of the list property to get the items of
*/
propertyName: string;
};
PressInputPropertiesButton: {
/**
* Name of the input
*/
inputName: string;
/**
* Name of the button property to press
*/
propertyName: string;
};
GetMediaInputStatus: {
/**
* Name of the media input
*/
inputName: string;
};
SetMediaInputCursor: {
/**
* Name of the media input
*/
inputName: string;
/**
* New cursor position to set
*
* @restrictions >= 0
*/
mediaCursor: number;
};
OffsetMediaInputCursor: {
/**
* Name of the media input
*/
inputName: string;
/**
* Value to offset the current cursor position by
*/
mediaCursorOffset: number;
};
TriggerMediaInputAction: {
/**
* Name of the media input
*/
inputName: string;
/**
* Identifier of the `ObsMediaInputAction` enum
*/
mediaAction: string;
};
GetRecordStatus: never;
ToggleRecord: never;
StartRecord: never;
StopRecord: never;
ToggleRecordPause: never;
PauseRecord: never;
ResumeRecord: never;
GetRecordDirectory: never;
GetSceneItemList: {
/**
* Name of the scene to get the items of
*/
sceneName: string;
};
GetGroupItemList: {
/**
* Name of the group to get the items of
*/
sceneName: string;
};
GetSceneItemId: {
/**
* Name of the scene or group to search in
*/
sceneName: string;
/**
* Name of the source to find
*/
sourceName: string;
};
CreateSceneItem: {
/**
* Name of the scene to create the new item in
*/
sceneName: string;
/**
* Name of the source to add to the scene
*/
sourceName: string;
/**
* Enable state to apply to the scene item on creation
*
* @defaultValue True
*/
sceneItemEnabled?: boolean;
};
RemoveSceneItem: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
};
DuplicateSceneItem: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
/**
* Name of the scene to create the duplicated item in
*
* @defaultValue `sceneName` is assumed
*/
destinationSceneName?: string;
};
GetSceneItemTransform: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
};
SetSceneItemTransform: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
/**
* Object containing scene item transform info to update
*/
sceneItemTransform: JsonObject;
};
GetSceneItemEnabled: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
};
SetSceneItemEnabled: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
/**
* New enable state of the scene item
*/
sceneItemEnabled: boolean;
};
GetSceneItemLocked: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
};
SetSceneItemLocked: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
/**
* New lock state of the scene item
*/
sceneItemLocked: boolean;
};
GetSceneItemIndex: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
};
SetSceneItemIndex: {
/**
* Name of the scene the item is in
*/
sceneName: string;
/**
* Numeric ID of the scene item
*
* @restrictions >= 0
*/
sceneItemId: number;
/**
* New index position of the scene item
*
* @restrictions >= 0
*/
sceneItemIndex: number;
};
GetSceneList: never;
GetCurrentProgramScene: never;
SetCurrentProgramScene: {
/**
* Scene to set as the current program scene
*/
sceneName: string;
};
GetCurrentPreviewScene: never;
SetCurrentPreviewScene: {
/**
* Scene to set as the current preview scene
*/
sceneName: string;
};
CreateScene: {
/**
* Name for the new scene
*/
sceneName: string;
};
RemoveScene: {
/**
* Name of the scene to remove
*/
sceneName: string;
};
SetSceneName: {
/**
* Name of the scene to be renamed
*/
sceneName: string;
/**
* New name for the scene
*/
newSceneName: string;
};
GetSourceActive: {
/**
* Name of the source to get the active state of
*/
sourceName: string;
};
GetSourceScreenshot: {
/**
* Name of the source to take a screenshot of
*/
sourceName: string;
/**
* Image compression format to use. Use `GetVersion` to get compatible image formats
*/
imageFormat: string;
/**
* Width to scale the screenshot to
*
* @restrictions >= 8, <= 4096
* @defaultValue Source value is used
*/
imageWidth?: number;
/**
* Height to scale the screenshot to
*
* @restrictions >= 8, <= 4096
* @defaultValue Source value is used
*/
imageHeight?: number;
/**
* Compression quality to use. 0 for high compression, 100 for uncompressed. -1 to use "default" (whatever that means, idk)
*
* @restrictions >= -1, <= 100
* @defaultValue -1
*/
imageCompressionQuality?: number;
};
SaveSourceScreenshot: {
/**
* Name of the source to take a screenshot of
*/
sourceName: string;
/**
* Image compression format to use. Use `GetVersion` to get compatible image formats
*/
imageFormat: string;
/**
* Path to save the screenshot file to. Eg. `C:\Users\user\Desktop\screenshot.png`
*/
imageFilePath: string;
/**
* Width to scale the screenshot to
*
* @restrictions >= 8, <= 4096
* @defaultValue Source value is used
*/
imageWidth?: number;
/**
* Height to scale the screenshot to
*
* @restrictions >= 8, <= 4096
* @defaultValue Source value is used
*/
imageHeight?: number;
/**
* Compression quality to use. 0 for high compression, 100 for uncompressed. -1 to use "default" (whatever that means, idk)
*
* @restrictions >= -1, <= 100
* @defaultValue -1
*/
imageCompressionQuality?: number;
};
GetStreamStatus: never;
ToggleStream: never;
StartStream: never;
StopStream: never;
GetTransitionKindList: never;
GetSceneTransitionList: never;
GetCurrentSceneTransition: never;
SetCurrentSceneTransition: {
/**
* Name of the transition to make active
*/
transitionName: string;
};
SetCurrentSceneTransitionDuration: {
/**
* Duration in milliseconds
*
* @restrictions >= 50, <= 20000
*/
transitionDuration: number;
};
SetCurrentSceneTransitionSettings: {
/**
* Settings object to apply to the transition. Can be `{}`
*/
transitionSettings: JsonObject;
/**
* Whether to overlay over the current settings or replace them
*
* @defaultValue true
*/
overlay?: boolean;
};
TriggerStudioModeTransition: never;
GetStudioModeEnabled: never;
SetStudioModeEnabled: {
/**
* True == Enabled, False == Disabled
*/
studioModeEnabled: boolean;
};
}
export interface OBSResponseTypes {
GetPersistentData: {
/**
* Value associated with the slot. `null` if not set
*/
slotValue: JsonValue;
};
SetPersistentData: undefined;
GetSceneCollectionList: {
/**
* The name of the current scene collection
*/
currentSceneCollectionName: string;
/**
* Array of all available scene collections
*/
sceneCollections: string[];
};
SetCurrentSceneCollection: undefined;
CreateSceneCollection: undefined;
GetProfileList: {
/**
* The name of the current profile
*/
currentProfileName: string;
/**
* Array of all available profiles
*/
profiles: string[];
};
SetCurrentProfile: undefined;
CreateProfile: undefined;
RemoveProfile: undefined;
GetProfileParameter: {
/**
* Value associated with the parameter. `null` if not set and no default
*/
parameterValue: string;
/**
* Default value associated with the parameter. `null` if no default
*/
defaultParameterValue: string;
};
SetProfileParameter: undefined;
GetVideoSettings: {
/**
* Numerator of the fractional FPS value
*/
fpsNumerator: number;
/**
* Denominator of the fractional FPS value
*/
fpsDenominator: number;
/**
* Width of the base (canvas) resolution in pixels
*/
baseWidth: number;
/**
* Height of the base (canvas) resolution in pixels
*/
baseHeight: number;
/**
* Width of the output resolution in pixels
*/
outputWidth: number;
/**
* Height of the output resolution in pixels
*/
outputHeight: number;
};
SetVideoSettings: undefined;
GetStreamServiceSettings: {
/**
* Stream service type, like `rtmp_custom` or `rtmp_common`
*/
streamServiceType: string;
/**
* Stream service settings
*/
streamServiceSettings: JsonObject;
};
SetStreamServiceSettings: undefined;
GetVersion: {
/**
* Current OBS Studio version
*/
obsVersion: string;
/**
* Current obs-websocket version
*/
obsWebSocketVersion: string;
/**
* Current latest obs-websocket RPC version
*/
rpcVersion: number;
/**
* Array of available RPC requests for the currently negotiated RPC version
*/
availableRequests: string[];
/**
* Image formats available in `GetSourceScreenshot` and `SaveSourceScreenshot` requests.
*/
supportedImageFormats: string[];
};
GetStats: {
/**
* Current CPU usage in percent
*/
cpuUsage: number;
/**
* Amount of memory in MB currently being used by OBS
*/
memoryUsage: number;
/**
* Available disk space on the device being used for recording storage
*/
availableDiskSpace: number;
/**
* Current FPS being rendered
*/
activeFps: number;
/**
* Average time in milliseconds that OBS is taking to render a frame
*/
averageFrameRenderTime: number;
/**
* Number of frames skipped by OBS in the render thread
*/
renderSkippedFrames: number;
/**
* Total number of frames outputted by the render thread
*/
renderTotalFrames: number;
/**
* Number of frames skipped by OBS in the output thread
*/
outputSkippedFrames: number;
/**
* Total number of frames outputted by the output thread
*/
outputTotalFrames: number;
/**
* Total number of messages received by obs-websocket from the client
*/
webSocketSessionIncomingMessages: number;
/**
* Total number of messages sent by obs-websocket to the client
*/
webSocketSessionOutgoingMessages: number;
};
BroadcastCustomEvent: undefined;
CallVendorRequest: {
/**
* Object containing appropriate response data. {} if request does not provide any response data
*/
responseData: JsonObject;
};
GetHotkeyList: {
/**
* Array of hotkey names
*/
hotkeys: string[];
};
TriggerHotkeyByName: undefined;
TriggerHotkeyByKeySequence: undefined;
Sleep: undefined;
GetInputList: {
/**
* Array of inputs
*/
inputs: JsonArray;
};
GetInputKindList: {
/**
* Array of input kinds
*/
inputKinds: string[];
};
CreateInput: {
/**
* ID of the newly created scene item
*/
sceneItemId: number;
};
RemoveInput: undefined;
SetInputName: undefined;
GetInputDefaultSettings: {
/**
* Object of default settings for the input kind
*/
defaultInputSettings: JsonObject;
};
GetInputSettings: {
/**
* Object of settings for the input
*/
inputSettings: JsonObject;
/**
* The kind of the input
*/
inputKind: string;
};
SetInputSettings: undefined;
GetInputMute: {
/**
* Whether the input is muted
*/
inputMuted: boolean;
};
SetInputMute: undefined;
ToggleInputMute: {
/**
* Whether the input has been muted or unmuted
*/
inputMuted: boolean;
};
GetInputVolume: {
/**
* Volume setting in mul
*/
inputVolumeMul: number;
/**
* Volume setting in dB
*/
inputVolumeDb: number;
};
SetInputVolume: undefined;
GetInputAudioSyncOffset: {
/**
* Audio sync offset in milliseconds
*/
inputAudioSyncOffset: number;
};
SetInputAudioSyncOffset: undefined;
GetInputAudioMonitorType: {
/**
* Audio monitor type
*/
monitorType: string;
};
SetInputAudioMonitorType: undefined;
GetInputPropertiesListPropertyItems: {
/**
* Array of items in the list property
*/
propertyItems: JsonArray;
};
PressInputPropertiesButton: undefined;
GetMediaInputStatus: {
/**
* State of the media input
*/
mediaState: string;
/**
* Total duration of the playing media in milliseconds. `null` if not playing
*/
mediaDuration: number;
/**
* Position of the cursor in milliseconds. `null` if not playing
*/
mediaCursor: number;
};
SetMediaInputCursor: undefined;
OffsetMediaInputCursor: undefined;
TriggerMediaInputAction: undefined;
GetRecordStatus: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* Whether the output is paused
*/
ouputPaused: boolean;
/**
* Current formatted timecode string for the output
*/
outputTimecode: string;
/**
* Current duration in milliseconds for the output
*/
outputDuration: number;
/**
* Number of bytes sent by the output
*/
outputBytes: number;
};
ToggleRecord: undefined;
StartRecord: undefined;
StopRecord: undefined;
ToggleRecordPause: undefined;
PauseRecord: undefined;
ResumeRecord: undefined;
GetRecordDirectory: {
/**
* Output directory
*/
recordDirectory: string;
};
GetSceneItemList: {
/**
* Array of scene items in the scene
*/
sceneItems: JsonArray;
};
GetGroupItemList: {
/**
* Array of scene items in the group
*/
sceneItems: JsonArray;
};
GetSceneItemId: {
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
};
CreateSceneItem: {
/**
* Numeric ID of the scene item
*/
sceneItemId: number;
};
RemoveSceneItem: undefined;
DuplicateSceneItem: {
/**
* Numeric ID of the duplicated scene item
*/
sceneItemId: number;
};
GetSceneItemTransform: {
/**
* Object containing scene item transform info
*/
sceneItemTransform: JsonObject;
};
SetSceneItemTransform: undefined;
GetSceneItemEnabled: {
/**
* Whether the scene item is enabled. `true` for enabled, `false` for disabled
*/
sceneItemEnabled: boolean;
};
SetSceneItemEnabled: undefined;
GetSceneItemLocked: {
/**
* Whether the scene item is locked. `true` for locked, `false` for unlocked
*/
sceneItemLocked: boolean;
};
SetSceneItemLocked: undefined;
GetSceneItemIndex: {
/**
* Index position of the scene item
*/
sceneItemIndex: number;
};
SetSceneItemIndex: undefined;
GetSceneList: {
/**
* Current program scene
*/
currentProgramSceneName: string;
/**
* Current preview scene. `null` if not in studio mode
*/
currentPreviewSceneName: string;
/**
* Array of scenes in OBS
*/
scenes: JsonArray;
};
GetCurrentProgramScene: {
/**
* Current program scene
*/
currentProgramSceneName: string;
};
SetCurrentProgramScene: undefined;
GetCurrentPreviewScene: {
/**
* Current preview scene
*/
currentPreviewSceneName: string;
};
SetCurrentPreviewScene: undefined;
CreateScene: undefined;
RemoveScene: undefined;
SetSceneName: undefined;
GetSourceActive: {
/**
* Whether the source is showing in Program
*/
videoActive: boolean;
/**
* Whether the source is showing in the UI (Preview, Projector, Properties)
*/
videoShowing: boolean;
};
GetSourceScreenshot: {
/**
* Base64-encoded screenshot
*/
imageData: string;
};
SaveSourceScreenshot: {
/**
* Base64-encoded screenshot
*/
imageData: string;
};
GetStreamStatus: {
/**
* Whether the output is active
*/
outputActive: boolean;
/**
* Whether the output is currently reconnecting
*/
outputReconnecting: boolean;
/**
* Current formatted timecode string for the output
*/
outputTimecode: string;
/**
* Current duration in milliseconds for the output
*/
outputDuration: number;
/**
* Number of bytes sent by the output
*/
outputBytes: number;
/**
* Number of frames skipped by the output's process
*/
outputSkippedFrames: number;
/**
* Total number of frames delivered by the output's process
*/
outputTotalFrames: number;
};
ToggleStream: {
/**
* New state of the stream output
*/
outputActive: boolean;
};
StartStream: undefined;
StopStream: undefined;
GetTransitionKindList: {
/**
* Array of transition kinds
*/
transitionKinds: string[];
};
GetSceneTransitionList: {
/**
* Name of the current scene transition. Can be null
*/
currentSceneTransitionName: string;
/**
* Kind of the current scene transition. Can be null
*/
currentSceneTransitionKind: string;
/**
* Array of transitions
*/
transitions: JsonArray;
};
GetCurrentSceneTransition: {
/**
* Name of the transition
*/
transitionName: string;
/**
* Kind of the transition
*/
transitionKind: string;
/**
* Whether the transition uses a fixed (unconfigurable) duration
*/
transitionFixed: boolean;
/**
* Configured transition duration in milliseconds. `null` if transition is fixed
*/
transitionDuration: number;
/**
* Whether the transition supports being configured
*/
transitionConfigurable: boolean;
/**
* Object of settings for the transition. `null` if transition is not configurable
*/
transitionSettings: JsonObject;
};
SetCurrentSceneTransition: undefined;
SetCurrentSceneTransitionDuration: undefined;
SetCurrentSceneTransitionSettings: undefined;
TriggerStudioModeTransition: undefined;
GetStudioModeEnabled: {
/**
* Whether studio mode is enabled
*/
studioModeEnabled: boolean;
};
SetStudioModeEnabled: undefined;
} | the_stack |
/// <reference types="node" />
type I2CDeviceId = { manufacturer: number; product: number; name: string };
type BytesWritten = { bytesWritten: number; buffer: Buffer };
type BytesRead = { bytesRead: number; buffer: Buffer };
type CompletionCallback = (error: any) => any;
type BufferCallback = (error: any, bytesReadOrWritten: number, buffer: Buffer) => any;
type ResultCallback<T> = (error: any, result: T) => any;
type OpenOptions = {
/** A boolean value specifying whether access to devices on the I2C bus should be allowed even if they are already in use by a kernel driver/module. Corresponds to I2C_SLAVE_FORCE on Linux. The valid values for forceAccess are true and false. Optional, the default value is false. */
forceAccess: boolean;
};
export interface I2CFuncs {
i2c: boolean;
tenBitAddr: boolean;
protocolMangling: boolean;
smbusPec: boolean;
smbusBlockProcCall: boolean;
smbusQuick: boolean;
smbusReceiveByte: boolean;
smbusSendByte: boolean;
smbusReadByte: boolean;
smbusWriteByte: boolean;
smbusReadWord: boolean;
smbusWriteWord: boolean;
smbusProcCall: boolean;
smbusReadBlock: boolean;
smbusWriteBlock: boolean;
smbusReadI2cBlock: boolean;
smbusWriteI2cBlock: boolean;
}
export interface I2CBus {
/**
* Asynchronous close.
*
* @param {CompletionCallback} callback
* Completion callback
*/
close(callback: CompletionCallback): void;
/**
* Synchronous close.
*/
closeSync(): void;
/**
* Determine functionality of the bus/adapter asynchronously.
*
* @param {ResultCallback<I2CFuncs>} callback
* Callback that will recieve a frozen I2cFuncs object describing the I2C functionality available.
*/
i2cFuncs(callback: ResultCallback<I2CFuncs>): void;
/**
* Determine functionality of the bus/adapter synchronously.
*
* @return {I2CFuncs}
* A frozen I2cFuncs object describing the I2C functionality available.
*/
i2cFuncsSync(): I2CFuncs;
/**
* Scans the I2C bus asynchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {ResultCallback<number[]>} callback
* Callback that will recieve an array of numbers where each number represents the I2C address of a device which was detected.
*/
scan(callback: ResultCallback<number[]>): void;
/**
* Scans the I2C bus asynchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} address
* An integer specifying the address of the scan.
* @param {ResultCallback<number[]>} callback
* Callback that will recieve an array of numbers where each number represents the I2C address of a device which was detected.
*/
scan(address: number, callback: ResultCallback<number[]>): void;
/**
* Scans the I2C bus asynchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} startAddr
* An integer specifying the start address of the scan range.
* @param {number} endAddr
* An integer specifying the end address of the scan range.
* @param {ResultCallback<number[]>} callback
* Callback that will recieve an array of numbers where each number represents the I2C address of a device which was detected.
*/
scan(startAddr: number, endAddr: number, callback: ResultCallback<number[]>): void;
/**
* Scans the I2C bus synchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} [address]
* An integer specifying the address of the scan.
* @return {number[]}
* An array of numbers where each number represents the I2C address of a device which was detected.
*/
scanSync(address?: number): number[];
/**
* Scans the I2C bus synchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} [startAddr]
* An integer specifying the start address of the scan range.
* @param {number} [endAddr]
* An integer specifying the end address of the scan range.
* @return {number[]}
* An array of numbers where each number represents the I2C address of a device which was detected.
*/
scanSync(startAddr: number, endAddr: number): number[];
/**
* Asynchronous I2C device Id.
*
* @param {number} address
* I2C device address
* @param {ResultCallback<I2CDeviceId>} callback
* The callback gets two arguments (err, id). id is an object with the properties <code>manufacturer</code>, <code>product</code> and if known a human readable <code>name</code> for the associated manufacturer.
*/
deviceId(address: number, callback: ResultCallback<I2CDeviceId>): void;
/**
* Synchronous I2C device Id.
*
* @param {number} address
* I2C device address
* @return {I2CDeviceId}
* An object with the properties <code>manufacturer</code>, <code>product</code> and if known a human readable <code>name</code> for the associated manufacturer.
*/
deviceIdSync(address: number): I2CDeviceId;
/**
* Asynchronous plain I2C read.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to read.
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @param {BufferCallback} callback
* Callback that will recieve the number of bytes read and the given buffer.
*/
i2cRead(address: number, length: number, buffer: Buffer, callback: BufferCallback): void;
/**
* Synchronous plain I2C read.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to read.
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @return {number}
* The number of bytes read.
*/
i2cReadSync(address: number, length: number, buffer: Buffer): number;
/**
* Asynchronous plain I2C write.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to write.
* @param {Buffer} buffer
* The buffer that the data to write (must contain at least {length} bytes).
* @param {BufferCallback} callback
* Callback that will recieve the number of bytes written and the given buffer.
*/
i2cWrite(address: number, length: number, buffer: Buffer, callback: BufferCallback): void;
/**
* Synchronous plain I2C write.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to write.
* @param {Buffer} buffer
* The buffer that the data will to write (must contain at least {length} bytes).
* @return {number}
* The number of bytes written.
*/
i2cWriteSync(address: number, length: number, buffer: Buffer): number;
/**
* Asynchronous SMBus read byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {ResultCallback<number>} callback
* Callback that will recieve the byte read.
*/
readByte(address: number, command: number, callback: ResultCallback<number>): void;
/**
* Synchronous SMBus read byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @return {number}
* The byte read.
*/
readByteSync(address: number, command: number): number;
/**
* Asynchronous SMBus read word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {ResultCallback<number>} callback
* Callback that will recieve the word read.
*/
readWord(address: number, command: number, callback: ResultCallback<number>): void;
/**
* Synchronous SMBus read word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @return {number}
* The word read.
*/
readWordSync(address: number, command: number): number;
/**
* Asynchronous I2C block read (not defined by the SMBus
* specification). Reads a block of bytes from a device, from a
* designated register that is specified by cmd.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to read (max 32).
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @param {BufferCallback} callback
* Callback that will recieve the number of bytes read and the given buffer.
*/
readI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: BufferCallback): void;
/**
* Synchronous I2C block read (not defined by the SMBus
* specification). Reads a block of bytes from a device, from a
* designated register that is specified by cmd.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to read (max 32).
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @return {number}
* The number of bytes read.
*/
readI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number;
/**
* Asynchronous SMBus receive byte.
*
* @param {number} address
* I2C device address.
* @param {ResultCallback<number>} callback
* Callback that will recieve the byte received.
*/
receiveByte(address: number, callback: ResultCallback<number>): void;
/**
* Synchronous SMBus receive byte.
*
* @param {number} address
* I2C device address.
* @return {number}
* The byte received.
*/
receiveByteSync(address: number): number;
/**
* Asynchronous SMBus send byte.
*
* @param {number} address
* I2C device address.
* @param {number} byte
* The data byte to send.
* @param {CompletionCallback} callback
* Completion callback
*/
sendByte(address: number, byte: number, callback: CompletionCallback): void;
/**
* Synchronous SMBus send byte.
*
* @param {number} address
* I2C device address.
* @param {number} byte
* The data byte to send.
*/
sendByteSync(address: number, byte: number): void;
/**
* Asynchronous SMBus write byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} byte
* The data byte to write.
* @param {CompletionCallback} callback
* Completion callback
*/
writeByte(address: number, command: number, byte: number, callback: CompletionCallback): void;
/**
* Synchronous SMBus write byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} byte
* The data byte to write.
*/
writeByteSync(address: number, command: number, byte: number): void;
/**
* Asynchronous SMBus write word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} word
* The data word to write.
* @param {CompletionCallback} callback
* Completion callback
*/
writeWord(address: number, command: number, word: number, callback: CompletionCallback): void;
/**
* Synchronous SMBus write word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} word
* The data word to write.
*/
writeWordSync(address: number, command: number, word: number): void;
/**
* Asynchronous SMBus quick command. Writes a single bit to the device.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} bit
* The data bit to write (0 or 1).
* @param {CompletionCallback} callback
* Completion callback
*/
writeQuick(address: number, command: number, bit: number, callback: CompletionCallback): void;
/**
* Synchronous SMBus quick command. Writes a single bit to the device.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} bit
* The data bit to write (0 or 1).
*/
writeQuickSync(address: number, command: number, bit: number): void;
/**
* Asynchronous I2C block write (not defined by the SMBus
* specification). Writes a block of bytes to a device, to a designated
* register that is specified by {command}.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to write (max 32).
* @param {Buffer} buffer
* The buffer that the data to write (must contain at least {length} bytes).
* @param {BufferCallback} callback
* Callback that will recieve the number of bytes written and the given buffer.
*/
writeI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: BufferCallback): void;
/**
* Synchronous I2C block write (not defined by the SMBus
* specification). Writes a block of bytes to a device, to a designated
* register that is specified by {command}.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to write (max 32).
* @param {Buffer} buffer
* The buffer that the data will to write (must contain at least {length} bytes).
* @return {number}
* The number of bytes written.
*/
writeI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number;
/**
* Return the PromisifiedBus instance for this Bus instance.
*
* @return {PromisifiedBus}
* The PromisifiedBus instance for this Bus instance.
*/
promisifiedBus(): PromisifiedBus;
}
export interface PromisifiedBus {
/**
* Asynchronous close.
*
* @return {Promise<void>}
* A Promise that will be resolved with no arguments once the underlying resources have been released, or will be rejected if an error occurs while closing.
*/
close(): Promise<void>;
/**
* Determine functionality of the bus/adapter asynchronously.
*
* @return {Promise<I2CFuncs>}
* A Promise that on success will be resolved with a frozen I2cFuncs object describing the functionality available. The returned Promise will be rejected if an error occurs. See also [I2C functionality](https://www.kernel.org/doc/Documentation/i2c/functionality).
*/
i2cFuncs(): Promise<I2CFuncs>;
/**
* Scans the I2C bus asynchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} [address]
* An integer specifying the address of the scan.
* @return {Promise<number[]>}
* A Promise that on success will be resolved with an array of numbers where each number represents the I2C address of a device which was detected. The returned Promise will be rejected if an error occurs.
*/
scan(address?: number): Promise<number[]>;
/**
* Scans the I2C bus asynchronously for devices. The default address range 0x03 through 0x77 is the same as the default address range used by the <code>i2cdetect</code> command line tool.
*
* @param {number} [startAddr]
* An integer specifying the start address of the scan range.
* @param {number} [endAddr]
* An integer specifying the end address of the scan range.
* @return {Promise<number[]>}
* A Promise that on success will be resolved with an array of numbers where each number represents the I2C address of a device which was detected. The returned Promise will be rejected if an error occurs.
*/
scan(startAddr: number, endAddr: number): Promise<number[]>;
/**
* Asynchronous I2C device Id.
*
* @param {number} address
* I2C device address
* @return {Promise<I2CDeviceId>}
* A Promise that will be resolved with an id object on success, or will be rejected if an error occurs. id is an object with the properties <code>manufacturer</code>, <code>product</code> and if known a human readable <code>name</code> for the associated manufacturer.
*/
deviceId(address: number): Promise<I2CDeviceId>;
/**
* Asynchronous plain I2C read.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to read.
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @return {Promise<BytesRead>}
* A Promise that on success will be resolved with an object with a bytesRead property identifying the number of bytes read, and a buffer property that is a reference to the passed in buffer argument. The returned Promise will be rejected if an error occurs.
*/
i2cRead(address: number, length: number, buffer: Buffer): Promise<BytesRead>;
/**
* Asynchronous plain I2C write.
*
* @param {number} address
* I2C device address.
* @param {number} length
* The number of bytes to write.
* @param {Buffer} buffer
* The buffer that the data to write (must contain at least {length} bytes).
* @return {Promise<BytesWritten>}
* A Promise that on success will be resolved with an object with a bytesWritten property identifying the number of bytes written, and a buffer property that is a reference to the passed in buffer argument. The returned promise will be rejected if an error occurs.
*/
i2cWrite(address: number, length: number, buffer: Buffer): Promise<BytesWritten>;
/**
* Asynchronous SMBus read byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @return {Promise<number>}
* A Promise that will be resolved with a number representing the byte read on success, or will be rejected if an error occurs. byte is an unsigned integer in the range 0 to 255.
*/
readByte(address: number, command: number): Promise<number>;
/**
* Asynchronous SMBus read word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @return {Promise<number>}
* A Promise that will be resolved with a number representing the word read on success, or will be rejected if an error occurs. word is an unsigned integer in the range 0 to 65535.
*/
readWord(address: number, command: number): Promise<number>;
/**
* Asynchronous I2C block read (not defined by the SMBus specification).
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to read (max 32).
* @param {Buffer} buffer
* The buffer that the data will be written to (must be at least {length} bytes long).
* @return {Promise<BytesRead>}
* A Promise that on success will be resolved with an object with a bytesRead property identifying the number of bytes read, and a buffer property that is a reference to the passed in buffer argument. The returned Promise will be rejected if an error occurs.
*/
readI2cBlock(address: number, command: number, length: number, buffer: Buffer): Promise<BytesRead>;
/**
* Asynchronous SMBus receive byte.
*
* @param {number} address
* I2C device address.
* @return {Promise<number>}
* A Promise that will be resolved with a number representing the byte received on success, or will be rejected if an error occurs. byte is an unsigned integer in the range 0 to 255.
*/
receiveByte(address: number): Promise<number>;
/**
* Asynchronous SMBus send byte.
*
* @param {number} address
* I2C device address.
* @param {number} byte
* The data byte to send.
* @return {Promise<void>}
* A Promise that will be resolved with no arguments on success, or will be rejected if an error occurs.
*/
sendByte(address: number, byte: number): Promise<void>;
/**
* Asynchronous SMBus write byte.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} byte
* The data byte to write.
* @return {Promise<void>}
* A Promise that will be resolved with no arguments on success, or will be rejected if an error occurs.
*/
writeByte(address: number, command: number, byte: number): Promise<void>;
/**
* Asynchronous SMBus write word.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} word
* The data word to write.
* @return {Promise<void>}
* A Promise that will be resolved with no arguments on success, or will be rejected if an error occurs.
*/
writeWord(address: number, command: number, word: number): Promise<void>;
/**
* Asynchronous SMBus quick command.
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} bit
* The data bit to write (0 or 1).
* @return {Promise<void>}
* A Promise that will be resolved with no arguments on success, or will be rejected if an error occurs.
*/
writeQuick(address: number, command: number, bit: number): Promise<void>;
/**
* Asynchronous I2C block write (not defined by the SMBus specification).
*
* @param {number} address
* I2C device address.
* @param {number} command
* The command code.
* @param {number} length
* The number of bytes to write (max 32).
* @param {Buffer} buffer
* The buffer that the data to write (must contain at least {length} bytes).
* @return {Promise<BytesWritten>}
* A Promise that on success will be resolved with an object with a bytesWritten property identifying the number of bytes written, and a buffer property that is a reference to the passed in buffer argument. The returned promise will be rejected if an error occurs.
*/
writeI2cBlock(address: number, command: number, length: number, buffer: Buffer): Promise<BytesWritten>;
/**
* Return the Bus instance for this PromisifiedBus instance.
*
* @return {I2CBus}
* The Bus instance for this PromisifiedBus instance.
*/
bus(): I2CBus;
}
/**
* Asynchronous open.
*
* @param {number} busNumber
* The number of the I2C bus/adapter to open, 0 for /dev/i2c-0, 1 for /dev/i2c-1, ...
* @param {OpenOptions} [options]
* An optional options object.
* @param {CompletionCallback} callback
* Completion callback.
* @return {I2CBus}
* A new Bus object.
*/
export function open(busNumber: number, callback: CompletionCallback): I2CBus;
export function open(busNumber: number, options: OpenOptions, callback: CompletionCallback): I2CBus;
/**
* Synchronous open.
*
* @param {number} busNumber
* The number of the I2C bus/adapter to open, 0 for /dev/i2c-0, 1 for /dev/i2c-1, ...
* @param {OpenOptions} [options]
* An optional options object.
* @return {I2CBus}
* A new Bus object.
*/
export function openSync(busNumber: number, options?: OpenOptions): I2CBus;
/**
* Asynchronous open.
*
* @param {number} busNumber
* The number of the I2C bus/adapter to open, 0 for /dev/i2c-0, 1 for /dev/i2c-1, ...
* @param {OpenOptions} [options]
* An optional options object.
* @return {Promise<PromisifiedBus>}
* A Promise that, when resolved, yields a PromisifiedBus object.
*/
export function openPromisified(busNumber: number, options?: OpenOptions): Promise<PromisifiedBus>; | the_stack |
import assert from 'assert';
import { readFile } from 'fs-extra';
import { decode } from 'iconv-lite';
import { Aff } from './aff';
import type { AffInfo, Fx, Rep, SubstitutionSet } from './affDef';
import { cleanObject, isDefined } from './util';
const fixRegex = {
SFX: { m: /$/, r: '$' },
PFX: { m: /^/, r: '^' },
};
const yesRegex = /[yY]/;
const spaceRegex = /\s+/;
const commentRegex = /(?:^\s*#.*)|(?:\s+#.*)/;
const affixLine = /^\s*([^\s]+)\s+(.*)?$/;
const UTF8 = 'UTF-8';
interface Collector<T> {
addLine(line: AffLine): void;
getValue(): T | undefined;
}
export interface ConvEntry {
from: string;
to: string;
}
function convEntry(): Collector<ConvEntry[]> {
let fieldValue: ConvEntry[] | undefined;
return {
addLine: (line: AffLine) => {
if (fieldValue === undefined) {
fieldValue = [];
return;
}
const args = (line.value || '').split(spaceRegex);
fieldValue.push({ from: args[0], to: args[1] });
},
getValue: () => fieldValue,
};
}
function afEntry() {
let fieldValue: string[] | undefined;
return {
addLine: (line: AffLine) => {
if (fieldValue === undefined) {
// Add empty entry because rules start at 1
fieldValue = [''];
return;
}
if (line.value) {
fieldValue.push(line.value);
}
},
getValue: () => fieldValue,
};
}
function simpleTable<T>(map: (values: string[][]) => T) {
let data:
| {
count: string;
extra: string[] | undefined;
values: string[][];
}
| undefined;
function getValue() {
if (data?.values) return map(data.values);
return undefined;
}
function addLine(line: AffLine): void {
const args = (line.value || '').split(spaceRegex);
if (data === undefined) {
const [count, ...extraValues] = args;
const extra = extraValues.length ? extraValues : undefined;
const values: string[][] = [];
data = { count, extra, values };
return;
}
data.values.push(args);
}
return { addLine, getValue };
}
function tablePfxOrSfx(fieldValue: Afx | undefined, line: AffLine): Afx {
/*
Fields of an affix rules:
(0) Option name
(1) Flag
(2) stripping characters from beginning (at prefix rules) or end (at suffix rules) of the word
(3) affix (optionally with flags of continuation classes, separated by a slash)
(4) condition.
Zero stripping or affix are indicated by zero. Zero condition is indicated by dot.
Condition is a simplified, regular expression-like pattern, which must be met before the affix can be applied.
(Dot signs an arbitrary character. Characters in braces sign an arbitrary character from the character subset.
Dash hasn't got special meaning, but circumflex (^) next the first brace sets the complimenter character set.)
(5) Optional morphological fields separated by spaces or tabulators.
*/
if (fieldValue === undefined) {
fieldValue = new Map<string, Fx>();
}
const [subField] = (line.value || '').split(spaceRegex);
if (!fieldValue.has(subField)) {
const fx = parseAffixCreation(line);
fieldValue.set(fx.id, fx);
return fieldValue;
}
const rule = parseAffixRule(line);
if (!rule) {
console.log(`Affix rule missing values: ${line.option} ${line.value}`);
return fieldValue;
}
const fixRuleSet = fieldValue.get(subField);
assert(fixRuleSet);
const substitutionSets = fixRuleSet.substitutionSets;
const ruleAsString = rule.condition.source;
if (!substitutionSets.has(ruleAsString)) {
substitutionSets.set(ruleAsString, {
match: rule.condition,
substitutions: [],
});
}
const substitutionSet = substitutionSets.get(ruleAsString);
assert(substitutionSet);
const [attachText, attachRules] = rule.affix.split('/', 2);
substitutionSet.substitutions.push({
remove: rule.stripping,
replace: rule.replace,
attach: attachText,
attachRules,
extra: rule.extra,
});
return fieldValue;
}
/**
* Parse Affix creation line:
* `PFX|SFX flag cross_product number`
*/
function parseAffixCreation(line: AffLine): Fx {
const [flag, combinable, count, ...extra] = (line.value || '').split(spaceRegex);
const fx: Fx = {
id: flag,
type: line.option,
combinable: !!combinable.match(yesRegex),
count,
extra,
substitutionSets: new Map<string, SubstitutionSet>(),
};
return fx;
}
interface AffixRule {
type: 'PFX' | 'SFX';
flag: string;
stripping: string;
replace: RegExp;
affix: string;
condition: RegExp;
extra?: string;
}
const affixRuleRegEx = /^(\S+)\s+(\S+)\s+(\S+)\s*(.*)/;
const affixRuleConditionRegEx = /^((?:\[.*\]|\S+)+)\s*(.*)/;
/**
* `PFX|SFX flag stripping prefix [condition [morphological_fields...]]`
*/
function parseAffixRule(line: AffLine): AffixRule | undefined {
const [, flag, strip, affix, optional = ''] = (line.value || '').match(affixRuleRegEx) || [];
if (!flag || !strip || !affix) {
return undefined;
}
const [, rawCondition = '.', extra] = optional.match(affixRuleConditionRegEx) || [];
const type = line.option === 'SFX' ? 'SFX' : 'PFX';
const condition = fixMatch(type, rawCondition);
const affixRule: AffixRule = {
type,
flag,
stripping: strip,
replace: fixMatch(type, strip),
affix: cleanAffixAttach(affix),
condition,
extra,
};
return affixRule;
}
function cleanAffixAttach(affix: string): string {
const [fix, rules] = affix.split('/', 2);
const attach = fix === '0' ? '' : fix;
return attach + (rules ? '/' + rules : '');
}
function fixMatch(type: AffixRule['type'], match: string): RegExp {
const exp = affixMatchToRegExpString(match);
const fix = fixRegex[type];
return new RegExp(exp.replace(fix.m, fix.r));
}
function affixMatchToRegExpString(match: string): string {
if (match === '0') return '';
return match.replace(/([\\\-?*])/g, '\\$1');
}
function collectFx(): Collector<Afx> {
let value: Afx | undefined;
function addLine(line: AffLine) {
value = tablePfxOrSfx(value, line);
}
return {
addLine,
getValue: () => value,
};
}
const asPfx = collectFx;
const asSfx = collectFx;
const asString = () => collectPrimitive<string>((v) => v, '');
const asBoolean = () => collectPrimitive<boolean>((v) => !!parseInt(v), '1');
const asNumber = () => collectPrimitive<number>(parseInt, '0');
function collectPrimitive<T>(map: (line: string) => T, defaultValue = ''): Collector<T> {
let primitive: T | undefined;
function getValue() {
return primitive;
}
function addLine(line: AffLine) {
const { value = defaultValue } = line;
primitive = map(value);
}
return { addLine, getValue };
}
function toRep(values: string[][]): Rep[] {
return values.map((v) => ({ match: v[0], replaceWith: v[1] }));
}
function toSingleStrings(values: string[][]): string[] {
return values.map((v) => v[0]).filter(isDefined);
}
function toAffMap(values: string[][]): Exclude<AffInfo['MAP'], undefined> {
return toSingleStrings(values);
}
function toCompoundRule(values: string[][]): Exclude<AffInfo['COMPOUNDRULE'], undefined> {
return toSingleStrings(values);
}
function toCheckCompoundPattern(values: string[][]): Exclude<AffInfo['CHECKCOMPOUNDPATTERN'], undefined> {
return values;
}
type FieldCollector<T> = Collector<T>;
type AffFieldCollectorTable = {
[key in keyof AffInfo]-?: FieldCollector<Exclude<AffInfo[key], undefined>>;
};
/*
cspell:ignore COMPOUNDBEGIN COMPOUNDEND COMPOUNDMIDDLE COMPOUNDMIN COMPOUNDPERMITFLAG COMPOUNDRULE COMPOUNDFORBIDFLAG COMPOUNDFLAG
cspell:ignore FORBIDDENWORD KEEPCASE
cspell:ignore MAXDIFF NEEDAFFIX WORDCHARS
*/
// prettier-ignore
const createAffFieldTable: () => AffFieldCollectorTable = () => ({
AF : afEntry(),
BREAK : simpleTable(toSingleStrings),
CHECKCOMPOUNDCASE : asBoolean(),
CHECKCOMPOUNDDUP : asBoolean(),
CHECKCOMPOUNDPATTERN: simpleTable(toCheckCompoundPattern),
CHECKCOMPOUNDREP : asBoolean(),
COMPOUNDBEGIN : asString(),
COMPOUNDEND : asString(),
COMPOUNDMIDDLE : asString(),
COMPOUNDMIN : asNumber(),
COMPOUNDFLAG : asString(),
COMPOUNDPERMITFLAG : asString(),
COMPOUNDFORBIDFLAG : asString(),
COMPOUNDRULE : simpleTable(toCompoundRule),
FLAG : asString(), // 'long' | 'num'
FORBIDDENWORD : asString(),
FORCEUCASE : asString(),
ICONV : convEntry(),
KEEPCASE : asString(),
KEY : asString(),
MAP : simpleTable(toAffMap),
MAXCPDSUGS : asNumber(),
MAXDIFF : asNumber(),
NEEDAFFIX : asString(),
NOSPLITSUGS : asBoolean(),
NOSUGGEST : asString(),
OCONV : convEntry(),
ONLYINCOMPOUND : asString(),
ONLYMAXDIFF : asBoolean(),
PFX : asPfx(),
REP : simpleTable(toRep),
SET : asString(),
SFX : asSfx(),
TRY : asString(),
WARN : asString(),
WORDCHARS : asString(),
});
function collectionToAffInfo(affFieldCollectionTable: AffFieldCollectorTable, encoding: string): AffInfo {
type AffInfoKeys = keyof AffInfo;
type ParseResult = {
[key in AffInfoKeys]: AffInfo[key];
};
// prettier-ignore
const result: ParseResult = {
AF : affFieldCollectionTable.AF.getValue(),
BREAK : affFieldCollectionTable.BREAK.getValue(),
CHECKCOMPOUNDCASE : affFieldCollectionTable.CHECKCOMPOUNDCASE.getValue(),
CHECKCOMPOUNDDUP : affFieldCollectionTable.CHECKCOMPOUNDDUP.getValue(),
CHECKCOMPOUNDPATTERN: affFieldCollectionTable.CHECKCOMPOUNDPATTERN.getValue(),
CHECKCOMPOUNDREP : affFieldCollectionTable.CHECKCOMPOUNDREP.getValue(),
COMPOUNDBEGIN : affFieldCollectionTable.COMPOUNDBEGIN.getValue(),
COMPOUNDEND : affFieldCollectionTable.COMPOUNDEND.getValue(),
COMPOUNDMIDDLE : affFieldCollectionTable.COMPOUNDMIDDLE.getValue(),
COMPOUNDMIN : affFieldCollectionTable.COMPOUNDMIN.getValue(),
COMPOUNDFLAG : affFieldCollectionTable.COMPOUNDFLAG.getValue(),
COMPOUNDPERMITFLAG : affFieldCollectionTable.COMPOUNDPERMITFLAG.getValue(),
COMPOUNDFORBIDFLAG : affFieldCollectionTable.COMPOUNDFORBIDFLAG.getValue(),
COMPOUNDRULE : affFieldCollectionTable.COMPOUNDRULE.getValue(),
FLAG : affFieldCollectionTable.FLAG.getValue(),
FORBIDDENWORD : affFieldCollectionTable.FORBIDDENWORD.getValue(),
FORCEUCASE : affFieldCollectionTable.FORCEUCASE.getValue(),
ICONV : affFieldCollectionTable.ICONV.getValue(),
KEEPCASE : affFieldCollectionTable.KEEPCASE.getValue(),
KEY : affFieldCollectionTable.KEY.getValue(),
MAP : affFieldCollectionTable.MAP.getValue(),
MAXCPDSUGS : affFieldCollectionTable.MAXCPDSUGS.getValue(),
MAXDIFF : affFieldCollectionTable.MAXDIFF.getValue(),
NEEDAFFIX : affFieldCollectionTable.NEEDAFFIX.getValue(),
NOSPLITSUGS : affFieldCollectionTable.NOSPLITSUGS.getValue(),
NOSUGGEST : affFieldCollectionTable.NOSUGGEST.getValue(),
OCONV : affFieldCollectionTable.OCONV.getValue(),
ONLYINCOMPOUND : affFieldCollectionTable.ONLYINCOMPOUND.getValue(),
ONLYMAXDIFF : affFieldCollectionTable.ONLYMAXDIFF.getValue(),
PFX : affFieldCollectionTable.PFX.getValue(),
REP : affFieldCollectionTable.REP.getValue(),
SET : affFieldCollectionTable.SET.getValue() || encoding,
SFX : affFieldCollectionTable.SFX.getValue(),
TRY : affFieldCollectionTable.TRY.getValue(),
WARN : affFieldCollectionTable.WARN.getValue(),
WORDCHARS : affFieldCollectionTable.WORDCHARS.getValue(),
};
return cleanObject(result);
}
export async function parseAffFile(filename: string, encoding: string = UTF8) {
const buffer = await readFile(filename);
const file = decode(buffer, encoding);
const affInfo = parseAff(file, encoding);
if (affInfo.SET && affInfo.SET.toLowerCase() !== encoding.toLowerCase()) {
return parseAff(decode(buffer, affInfo.SET.toLowerCase()), affInfo.SET);
}
return affInfo;
}
export function parseAff(affFileContent: string, encoding: string = UTF8): AffInfo {
const lines = affFileContent.split(/\r?\n/g);
const affFieldCollectionTable = createAffFieldTable();
affFieldCollectionTable.SET.addLine({ option: 'SET', value: encoding });
lines
.map((line) => line.trimStart())
.map((line) => line.replace(commentRegex, ''))
.filter((line) => line.trim() !== '')
.map(parseLine)
.forEach((line: AffLine) => {
const field = line.option as keyof AffInfo;
affFieldCollectionTable[field]?.addLine(line);
});
return collectionToAffInfo(affFieldCollectionTable, encoding);
}
export function parseAffFileToAff(filename: string, encoding?: string) {
return parseAffFile(filename, encoding).then((affInfo) => new Aff(affInfo));
}
function parseLine(line: string): AffLine {
const result = line.match(affixLine) || ['', ''];
const [, option, value] = result;
return { option, value: value || undefined };
}
export interface AffLine {
option: string;
value: string | undefined;
}
type Afx = Map<string, Fx>;
export const testing = {
parseAffixRule,
tablePfxOrSfx,
parseLine,
}; | the_stack |
import * as fs from 'fs';
import * as Handlebars from 'handlebars';
import * as _ from 'lodash';
import * as path from 'path';
import { APIProcessor } from './APIProcessor';
import { ConfigProcessor } from './ConfigProcessor';
import * as consts from './const';
import { ExampleProcessor } from './ExampleProcessor';
import { PagesProcessor } from './PagesProcessor';
import { RedirectProcessor } from './RedirectProcessor';
const docsJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../docs.json'), 'utf8'));
const pjson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf8'));
/**
* check equality of x and y.
* If they are equal, returns true(context e.g. children) || false(context e.g. children)
* @param children
* @param x
* @param y
* @param options
* @returns {any}
*/
export function ifEquals(children, x, y, options): any {
return _.isEqual(x, y) ? options.fn(children) : options.inverse(children);
}
/**
* Filters children by a kind name such as Constructor or Method
* @param children
* @param options
* @param kind
* @returns {any}
*/
export function filterByKind(children, options, kind): any {
if (children) {
const filtered = children.filter((child) => {
return child.kindString === kind;
});
// Filtering by isProtected = true and any constructors (we always want to display constructors
const publicFiltered = filtered.filter((filteredChild) => {
return filteredChild.flags.isPublic || filteredChild.kindString === consts.kindStringConst;
});
return _.isEmpty(publicFiltered) ? options.inverse(children) : options.fn(publicFiltered);
} else {
return options.inverse(children);
}
}
/**
* Filters children by its tag name. For example filter by tag "example" of below
* [{"tag":"example","text":"\nhello('test');\n\n"}, {"tag": "somethingelse"}]
* would result in
* [{"tag":"example","text":"\nhello('test');\n\n"}]
* @param children
* @param options
* @param tag
* @returns {any}
*/
export function filterByTag(children, options, tag): any {
if (children) {
const filtered = children.filter((child) => {
return child.tag === tag;
});
return _.isEmpty(filtered) ? options.inverse(children) : options.fn(filtered);
} else {
return options.inverse(children);
}
}
/**
* Search the docs to find an entity with the ID
* @param docs
* @param id
* @returns {any}
*/
export function searchInterface(docs, id): any {
let candidate = null;
_.forEach(docs.children, (module) => {
_.forEach(module.children, (entity) => {
if (entity.id === id) {
candidate = entity;
}
});
});
return candidate;
}
/**
* Check if a signatures collection is empty
* 1. If signature itself is empty or undefined
* 2. If the first signature does not contain "parameters"
* @param context - current context, typically this
* @param options
*/
export function isSignatureValid(context, options): any {
const signatures = context.signatures;
if (_.isEmpty(signatures) || !signatures) {
return options.inverse(context);
}
const firstSignature: any = _.first(signatures);
// Flag to make sure parameters or type exist
const signatureOrType = firstSignature.parameters || firstSignature.type;
if (_.isEmpty(signatureOrType) || !signatureOrType) {
return options.inverse(context);
}
// Otherwise returns true
return options.fn(context);
}
/**
* Traverses a definition for an Array and returns a string representation
* @param arrayTree
* @param {string} result
* @returns {any}
*/
export function traverseArrayDefinition(arrayTree, result = ''): string {
// const type = arrayTree.type;
const element = arrayTree.elementType;
const elementName = element.name;
const elementType = element.type;
// tslint:disable-next-line
result = result + '[]';
if (consts.paramTypeArray === elementType) {
return traverseArrayDefinition(element, result);
}
return `${elementName}${result}`;
}
/**
* Construct a list of string representations of Matrix
*
* @example
* constructMatrixType('Type2DMatrix', [{ type: 'intrinsic', name: 'string' }])
* // 'string[][]'
*
* @param dim
* @param types
*/
export function constructMatrixType(dim: string, types: [{ type: string; name: string }]): string {
if (dim === null || dim === undefined) {
throw new TypeError('dim should not be null or undefined');
}
if (_.isEmpty(types)) {
throw new TypeError('types cannot be empty!');
}
const buffer = [];
let brackets;
if (dim === consts.type1DMatrix) {
brackets = '[]';
} else if (dim === consts.type2DMatrix) {
brackets = '[][]';
} else if (dim === consts.type3DMatrix) {
brackets = '[][][]';
} else if (dim === consts.type4DMatrix) {
brackets = '[][][][]';
}
types.forEach((type) => {
buffer.push(`${type.name}${brackets}`);
});
// Joining everything and returns a string
return buffer.join(' or ');
}
/**
* Prioritise getting text instead of shortText description
* @param param
*/
export function getText(param): string | undefined {
if (_.isEmpty(param)) {
throw new TypeError('Param should not be null or undefined');
}
const text = _.get(param, 'comment.text');
const shortText = _.get(param, 'comment.shortText');
if (text) {
return text;
} else if (shortText) {
return shortText;
}
return undefined;
}
/**
* Constructs a parameter table that may look something like:
* | Param | Type | Default | Description |
* | ------ | ------ | ------ | ------ |
* | object.X | any | | array-like or sparse matrix of shape = [nsamples, n_features]
* | object.y | any | | array-like, shape = [nsamples] or [n_samples, n_outputs]
*
* @param parameters
* @returns {string}
*/
export function constructParamTable(parameters): string {
// Param table characters blacklist
const paramTableCharsBlackList = [/\n/g, /\r\n/g];
/**
* Generic clean function before displaying it on the table parameters
* @param text
* @returns {string}
*/
const cleanTableText = (text) => {
const blacklistCleaned = _.reduce(
paramTableCharsBlackList,
(result, rmChar) => {
return _.replace(result, rmChar, '');
},
text,
);
return _.trim(blacklistCleaned);
};
/**
* Transforms param types, for example number[] or number[][]
* @param obj
*/
const renderParamType = (obj) => {
if (obj.type === consts.paramTypeArray) {
// Handling arrays
return traverseArrayDefinition(obj);
} else {
// Handling anything other than arrays
return obj.name;
}
};
/**
* Builds a readable reference parameter and append the result to the sum array
* @param param
* @param sum
* @param typeId
*/
const buildParamsFromReference = (param, sum, typeId, preprend = 'options') => {
const foundRef = searchInterface(docsJson, typeId);
if (_.isEmpty(foundRef)) {
// Handling the TS native references
_.forEach(param.type.typeArguments, (prop) => {
// Building a readable type arguments
let args: string;
if (_.isArray(prop.typeArguments)) {
args = prop.typeArguments.map(renderParamType).join(' | ');
} else if (prop.constraint) {
args = prop.constraint.type + ' ' + prop.constraint.types.map(renderParamType).join(' | ');
} else {
args = prop.type;
}
sum.push([`${param.name}`, args, prop.defaultValue, getText(prop)]);
});
} else if (foundRef.kindString === consts.refKindInterface) {
_.forEach(foundRef.children, (prop) => {
sum.push([`${param.name}.${prop.name}`, renderParamType(prop.type), prop.defaultValue, getText(prop)]);
});
} else if (foundRef.kindString === consts.refKindTypeAlias) {
// Handling a custom `type` such as Type2DMatrix or Type3DMatrix
const { type } = foundRef.type;
if (type === consts.returnTypeArray) {
// For each TypeXMatrix render its array representation as a string
// example: number[][][] | string[][][]
const { typeArguments } = param.type;
// const refType = foundRef.type.type;
const refName = foundRef.name;
const typeList = [];
for (let i = 0; i < typeArguments.length; i++) {
const typeArg = typeArguments[i];
if (typeArg.type === consts.refTypeArgTypeUnion) {
const types = typeArg.types;
typeList.push(constructMatrixType(refName, types));
} else if (typeArg.type === consts.refTypeTypeParameter) {
const types = typeArg.constraint.types;
typeList.push(constructMatrixType(refName, types));
} else if (typeArg.type === consts.refTypeArgTypeIntrinsic) {
typeList.push(constructMatrixType(refName, [typeArg]));
} else {
typeList.push('unknown');
}
}
sum.push([param.name, typeList.join(' or '), param.defaultValue, getText(param)]);
}
} else if (foundRef.kindString === consts.kindStringEnum) {
sum.push([
`${preprend}.${param.name}`,
foundRef.children.map((x) => x.name).join(' or '),
param.defaultValue,
getText(param),
]);
}
};
// Going through the method level params
// e.g. test(a: {}, b: number, c: string)
// a -> b -> c
const consolidatedParams = _.reduce(
parameters,
(sum, param) => {
const paramType = param.type.type;
if (consts.paramTypeReflection === paramType) {
// 1. Handle reflection/named param
// e.g. x: { test1, test2 }
_.forEach(param.type.declaration.children, (namedParam) => {
// const foundRef = searchInterface(docsJson, namedParam.type.id);
if (consts.paramTypeReference === namedParam.type.type) {
// If the reflection is actually a reference, such as ENUM, then buildParamFromReference
buildParamsFromReference(namedParam, sum, namedParam.type.id);
} else {
sum.push([
`options.${namedParam.name}`,
renderParamType(namedParam.type),
namedParam.defaultValue,
getText(namedParam),
]);
}
// buildParamsFromReference(param, sum, namedParam.type.id);
});
} else if (consts.paramTypeIntrinsic === paramType) {
// 2. Handle any intrintic params
// e.g. x: number
sum.push([param.name, renderParamType(param.type), param.defaultValue, getText(param)]);
} else if (consts.paramTypeArray === paramType) {
// 3. Handle any array params
// e.g. string[]
sum.push([param.name, renderParamType(param.type), param.defaultValue, getText(param)]);
} else if (consts.paramTypeReference === paramType) {
// 4.1. Handle any TS native references -> determined by _.isEmpty(foundRef)
// e.g. x: IterableIterator
// 4.2. Handle any custom defined interfaces / references. Custom references should have an ID that references definition within the docs.json
// e.g. x: Options
buildParamsFromReference(param, sum, param.type.id);
} else if (consts.paramTypeUnion === paramType) {
// 5. Handles any union types.
// e.g. string[] | string[][]
const unionTypes = _.map(param.type.types, (singleType) => {
if (singleType.type === consts.paramTypeReference) {
return constructMatrixType(singleType.name, singleType.typeArguments);
}
return renderParamType(singleType);
});
const unionTypesStr = unionTypes.join(' or ');
sum.push([param.name, unionTypesStr, param.defaultValue, getText(param)]);
}
return sum;
},
[],
);
// flatten any [ [ [] ] ] 3rd layer arrays
const tableHeader = '| Param | Type | Default | Description |\n';
const tableSplit = '| ------ | ------ | ------ | ------ |\n';
let stringBuilder = `${tableHeader}${tableSplit}`;
// TODO: Is there a better way of building a string??.. should we do it from the template?
for (let i = 0; i < _.size(consolidatedParams); i++) {
const [name, type, defaultValue, description] = consolidatedParams[i];
const cleanName = cleanTableText(name);
const cleanType = cleanTableText(type);
const cleanDefaultValue = cleanTableText(defaultValue);
const cleanDescription = cleanTableText(description);
stringBuilder += `| ${cleanName} | ${cleanType} | ${cleanDefaultValue} | ${cleanDescription}\n`;
}
return stringBuilder;
}
/**
* Construct a return table that may look something like:
* | Param | Type | Description |
* | ------ | ------ | ------ |
* | X | any | array-like or sparse matrix of shape = [nsamples, n_features]
* | y | any | array-like, shape = [nsamples] or [n_samples, n_outputs]
*
* @param typeArgument - example of typeArgument looks like:
* typeArguments": { "type": "reflection", "declaration": {... children}
*/
function constructReturnTable(typeArgument): string {
const children = typeArgument.declaration.children;
let table = '| Param | Type | Description |\n';
table += '| ------ | ------ | ------ |\n';
for (let i = 0; i < children.length; i++) {
const child = children[i];
const type = child.type.type;
if (type === consts.returnTypeIntrinsic) {
// If it's a simple type, such as string, number and etc
table += `| ${child.name} | ${child.type.name} | ${getText(child)}\n`;
} else if (type === consts.returnTypeArray) {
table += `| ${child.name} | ${traverseArrayDefinition(child.type)} | ${getText(child)}\n`;
}
}
return table;
}
/**
* Renders method return type
* This is slightly different to parameter renderer as it will simply return
* type.name if it's a simple return type
* @param type
* @returns {string}
*/
export function renderMethodReturnType(type): any {
if (type.type === consts.returnTypeIntrinsic) {
// Handles a simple promise return type
return type.name;
} else if (type.type === consts.returnTypeArray) {
// Handles an Array promise return type
return traverseArrayDefinition(type);
} else if (type.type === consts.returnTypeReflection) {
// Handles object return type
return constructReturnTable(type);
} else if (type.type === consts.returnTypeReference && type.name === consts.returnNamePromise) {
// Handles return type that returns a complex object
const returnTypes = type.typeArguments.map((typeArg) => {
let result;
if (typeArg.type === consts.returnTypeIntrinsic) {
// Simply return name if it's an intrinsic type
result = ':metal: Promise';
result += `<${typeArg.name}>`;
} else if (typeArg.type === consts.returnTypeReflection) {
// If it's a reflection type, an object, then render a table
result = ':metal: Promise\n';
result += constructReturnTable(typeArg);
} else if (typeArg.type === consts.returnTypeReference) {
result = ':metal: Promise';
result += '<self>';
}
return result;
});
return returnTypes.join('<br>');
}
}
/**
* Gets method () block next to the method name
* e.g. (props: any, x: string)
* @param parameters
* @returns {string}
*/
export function renderMethodBracket(parameters): string {
const params = _.map(parameters, (param) => {
const paramType = _.isString(param.type) ? param.type : 'object';
return `${param.name}: *\`${paramType}\`*`;
});
return `(${params.join(', ')})`;
}
/**
* Get a source link such as
* [ensemble/forest.ts:6](https://github.com/JasonShin/machinelearnjs/blob/master/src/lib/ensemble/forest.ts#L6)
* @param sources
* @returns {string}
*/
export function renderSourceLink(sources): string {
if (_.isEmpty(sources)) {
throw new TypeError('Sources cannot be empty');
}
const defined = _.map(sources, (src) => {
return `[${src.fileName}:${src.line}](${pjson.repository.url}/blob/master/src/lib/${src.fileName}#L${src.line})`;
});
return defined.join(',');
}
/**
* Renders a new line
* @returns {string}
*/
export function renderNewLine(): string {
return '\n';
}
/**
* Clean the string for hyperlink usage
* @param {string} str
* @returns {string}
*/
export function cleanHyperLink(str: string): string {
if (_.isEmpty(str)) {
throw new TypeError('Should not clean values other than strings');
}
// 1. Cloning the original str
let newStr = _.clone(str);
// 2. Replacing the known strings
newStr = _.replace(newStr, '_', '-');
// 3. apply lowercase transformation
return newStr.toLowerCase();
}
Handlebars.registerHelper('ifEquals', (children, x, y, options) => ifEquals(children, x, y, options));
Handlebars.registerHelper('isSignatureValid', (context, options) => isSignatureValid(context, options));
Handlebars.registerHelper('filterConstructor', (children, options) =>
filterByKind(children, options, consts.kindStringConst),
);
Handlebars.registerHelper('filterMethod', (children, options) =>
filterByKind(children, options, consts.kindStringMethod),
);
Handlebars.registerHelper('filterProperty', (children, options) =>
filterByKind(children, options, consts.kindStringProperty),
);
Handlebars.registerHelper('filterTagExample', (children, options) =>
filterByTag(children, options, consts.tagTypeExample),
);
Handlebars.registerHelper('constructParamTable', (parameters) => constructParamTable(parameters));
Handlebars.registerHelper('renderMethodReturnType', (type) => renderMethodReturnType(type));
Handlebars.registerHelper('methodBracket', (parameters) => renderMethodBracket(parameters));
Handlebars.registerHelper('getSourceLink', (sources) => renderSourceLink(sources));
Handlebars.registerHelper('newLine', renderNewLine);
Handlebars.registerHelper('cleanHyperLink', (str) => cleanHyperLink(str));
// Processors
const apiProcessor = new APIProcessor();
apiProcessor.run(Handlebars);
const pagesProcessor = new PagesProcessor();
pagesProcessor.run();
const exampleProcessor = new ExampleProcessor();
exampleProcessor.run(Handlebars);
const configProcessor = new ConfigProcessor();
configProcessor.run({ apiChildren: apiProcessor.apiChildren });
const redirectProcessor = new RedirectProcessor();
redirectProcessor.run(); | the_stack |
import * as _ from 'lodash'
import { Anchor } from './anchor'
import * as Stage from './stage'
import { SentenceArray } from './sentence-array'
import { errorUnderlineClass, theme } from '../peacoq/theme'
import { ProofTreeStack } from '../prooftree/stack'
import * as Command from '../sertop/command'
import * as ControlCommand from '../sertop/control-command'
import { setup as setupSertop } from '../sertop/sertop'
function tipKey(t : Tip) : number {
return t.caseOf({
nothing : () => -1,
just : s => s.sentenceId,
})
}
export class CoqDocument implements ICoqDocument {
public addsToProcess$ : Rx.Observable<StmAdd$>
private beginAnchor : Anchor
private commandObserver : Rx.Observer<Command$>
public command$ : Rx.Observable<Command$>
public contextPanel : IContextPanel
public editorChange$ : Rx.Observable<AceAjax.EditorChangeEvent>
public sentences : ISentenceArray
private endAnchor : Anchor
public input$ : Command$
private nextObserver : Rx.Observer<{}>
public output$s : CoqtopOutputStreams
public proofTrees : ProofTreeStack
public sentencesChanged$ : Rx.Observable<{}>
public sentenceBeingProcessed$ : Rx.Observable<ISentence<IBeingProcessed>>
public sentenceProcessed$ : Rx.Observable<ISentence<IProcessed>>
public session : AceAjax.IEditSession
private tipSubject : Rx.Subject<Tip>
public debouncedTip$ : Rx.Observable<Tip>
public tip$ : Rx.Observable<Tip>
constructor(
public editor : AceAjax.Editor
) {
const self = this
this.sentences = new SentenceArray(this)
// WARNING : This line must stay over calls to mkAnchor
this.session = editor.getSession()
this.beginAnchor = new Anchor(this, 0, 0, 'begin-marker', true)
this.endAnchor = new Anchor(this, 0, 0, 'end-marker', false)
this.editorChange$ =
Rx.Observable
.create<AceAjax.EditorChangeEvent>(observer => {
self.session.on('change', (e) => observer.onNext(e))
})
.share()
this.sentencesChanged$ = Rx.Observable.merge(
this.sentences.sentenceCreated$,
this.sentences.sentenceChangedStage$,
this.sentences.sentenceRemoved$
)
// this.editsChange$ = this.editsChangeSubject.asObservable()
const newEditSubject = new Rx.Subject<ISentence<IToProcess>>()
this.proofTrees = new ProofTreeStack()
this.sentenceBeingProcessed$ = this.sentences.sentenceBeingProcessed$
this.sentenceProcessed$ = this.sentences.sentenceProcessed$
this.tipSubject = new Rx.Subject<Tip>()
// Use distinctUntilChanged because PeaCoq automation triggers spurious
// tipSubject notifications for the same tip
// We don't want tip$ to be ref-counted as it creates problems with automation
const tip$ = this.tipSubject.distinctUntilChanged(tipKey).publish()
this.tip$ = tip$
// this.tip$.subscribe(t => console.log('tip$ from coq-document', t.sentenceId))
this.debouncedTip$ = this.tipSubject.distinctUntilChanged(tipKey).debounce(250).share()
this.sentenceBeingProcessed$.subscribe(s => this.setTip(just(s)))
const nextSubject = new Rx.ReplaySubject(1)
this.nextObserver = nextSubject.asObserver()
const sentencesToProcess$ = this.nextSentence(nextSubject.asObservable())
const commandSubject = new Rx.Subject<Command$>()
this.input$ =
commandSubject
// merge sequence of groups of commands into one sequence of commands
.concatMap(cmd$ => cmd$
// .do(e => console.log('ELEMENT IN', e))
// .doOnCompleted(() => console.log('COMPLETED'))
)
// .do(cmd => console.log('ELEMENT OUT', cmd))
this.output$s = setupSertop(this.input$)
this.commandObserver = commandSubject.asObserver()
const command$ = commandSubject.asObservable().publish()
this.command$ = command$
sentencesToProcess$.subscribe(e => this.moveCursorToPositionAndCenter(e.stopPosition))
sentencesToProcess$
.map(s => {
const command = new Command.Control(new ControlCommand.StmAdd({}, s.query, false))
s.commandTag = just(command.tag)
return Rx.Observable.just(command)
})
.subscribe(cmd$ => this.sendCommands(cmd$))
tip$.connect()
command$.connect()
}
public getActiveProofTree() : Maybe<IProofTree> {
return (
this.proofTrees.length > 0
? just(this.proofTrees.peek())
: nothing<IProofTree>()
)
}
public getAllSentences() : ISentence<IStage>[] { return this.sentences.getAll() }
public getSentenceAtPosition(pos : AceAjax.Position) : Maybe<ISentence<IStage>> {
const edit = _(this.getAllSentences()).find(e => e.containsPosition(pos))
return edit ? just(edit) : nothing<ISentence<IStage>>()
}
public getSentenceByStateId(id : StateId) : Maybe<ISentence<IStage>> {
const edit = _(this.getAllSentences()).find(e => e.getStateId().caseOf({
nothing : () => false,
just : s => s === id,
}))
return edit ? just(edit) : nothing<ISentence<IStage>>()
}
public getSentenceByTag(tag : CommandTag) : Maybe<ISentence<IStage>> {
const edit = _(this.getAllSentences()).find(e => e.commandTag.caseOf({
nothing : () => false,
just : s => s === tag,
}))
return edit ? just(edit) : nothing<ISentence<IStage>>()
}
public getSentencesBeingProcessed() : ISentence<IBeingProcessed>[] {
return <any>this.getAllSentences().filter(e => e.stage instanceof Stage.BeingProcessed)
}
public getSentencesToProcess() : ISentence<IToProcess>[] {
return <any>this.getAllSentences().filter(e => e.stage instanceof Stage.ToProcess)
}
public getProcessedSentences() : ISentence<IProcessed>[] {
return <any>this.getAllSentences().filter(e => e.stage instanceof Stage.Processed)
}
// getStopPositions() : AceAjax.Position[] {
// return _(this.editsProcessed).map(function(e) { return e.getStopPosition() }).value()
// }
// getLastSentence() : Maybe<ISentence<IEditStage>> {
// return this.edits.getLast()
// }
public getLastSentenceStop() : AceAjax.Position {
return this.sentences.getLast().caseOf({
nothing : () => this.beginAnchor.anchor.getPosition(),
just : last => last.stopPosition,
})
}
public moveCursorToPositionAndCenter(pos : AceAjax.Position) : void {
// this prevents the editor from marking selected the region jumped
this.editor.session.selection.clearSelection()
this.editor.moveCursorToPosition(pos)
this.editor.scrollToLine(pos.row, true, true, () => { })
}
public movePositionRight(pos : AceAjax.Position, n : number) : AceAjax.Position {
if (n === 0) { return pos }
const row = pos.row
const column = pos.column
const line = this.session.getLine(row)
if (column < line.length) {
return this.movePositionRight({
'row' : row,
'column' : column + 1
}, n - 1)
} else if (row < this.session.getLength()) {
return this.movePositionRight({
'row' : row + 1,
'column' : 0
}, n - 1)
} else {
return pos
}
}
// onProcessEditsFailure(vf : ValueFail) : Promise<any> {
// if (!(vf instanceof ValueFail)) {
// throw vf
// }
// this.editBeingProcessed.fmap((e) => e.onRemove())
// this.editBeingProcessed = nothing()
// _(this.editsToProcess).each((e) => e.onRemove())
// this.editsToProcess = []
// reportFailure(vf.message)
// console.log(vf.stateId)
// if (vf.stateId !== 0) {
// // TODO : also need to cancel edits > vf.stateId
// return peaCoqEditAt(vf.stateId)
// } else {
// return Promise.reject(vf)
// }
// }
// processEdits() : Promise<any> {
// const self = this
// if (this.editsToProcess.length === 0 || isJust(this.editBeingProcessed)) {
// return Promise.resolve()
// }
// const ebp = new EditBeingProcessed(this.editsToProcess.shift())
// this.editBeingProcessed = just(ebp)
// return (
// peaCoqAddPrime(ebp.query)
// .then((response) => {
// const stopPos = ebp.getStopPosition()
// self.session.selection.clearSelection()
// self.editor.moveCursorToPosition(stopPos)
// self.editor.scrollToLine(stopPos.row, true, true, () => { })
// self.editor.focus()
// const sid : number = response.stateId
// const ls = lastStatus
// const s = peaCoqStatus(false)
// const g = s.then(peaCoqGoal)
// const c = g.then(peaCoqGetContext)
// return Promise.all<any>([s, g, c]).then(
// ([s, g, c] : [Status, Goals, PeaCoqContext]) => {
// const e = new ProcessedEdit(ebp, sid, s, g, c)
// self.editsProcessed.push(e)
// _(editHandlers).each((h) => h(ebp.query, sid, ls, s, g, c))
// this.editBeingProcessed = nothing()
// return self.processEdits()
// })
// })
// .catch(self.onProcessEditsFailure.bind(self))
// )
// }
public markError(
range : AceAjax.Range,
clear$ : Rx.Observable<{}>
) : void {
const markerId = this.session.addMarker(range, errorUnderlineClass, 'text', false)
this.moveCursorToPositionAndCenter(range.start)
const markerChanged$ = this.editorChange$
.filter(e => range.contains(e.start.row, e.start.column) || range.contains(e.end.row, e.end.column))
.take(1)
Rx.Observable.merge(
markerChanged$,
clear$
).subscribe(() => this.session.removeMarker(markerId))
}
public next() : void {
this.nextObserver.onNext({})
}
public nextSentence(next$ : Rx.Observable<{}>) : Rx.Observable<ISentence<IToProcess>> {
return next$
.concatMap<ISentence<IToProcess>>(() => {
const lastEditStopPos = this.getLastSentenceStop()
const endPos = this.endAnchor.anchor.getPosition()
const unprocessedRange =
new AceAjax.Range(
lastEditStopPos.row, lastEditStopPos.column,
endPos.row, endPos.column
)
const unprocessedText = this.session.getTextRange(unprocessedRange)
if (CoqStringUtils.coqTrimLeft(unprocessedText) === '') {
return []
}
const nextIndex = CoqStringUtils.next(unprocessedText)
const newStopPos = this.movePositionRight(lastEditStopPos, nextIndex)
const query = unprocessedText.substring(0, nextIndex)
const previousEdit = this.sentences.getLast()
const stage = new Stage.ToProcess(this, lastEditStopPos, newStopPos)
const edit : ISentence<IToProcess> =
this.sentences.createSentence(this, lastEditStopPos, newStopPos, query, previousEdit, stage)
// debugger
return [edit]
})
.share()
}
public recenterEditor() {
const pos = this.editor.getCursorPosition()
this.editor.scrollToLine(pos.row, true, true, () => { })
}
public resetEditor(text : string) {
this.session.setValue(text)
this.editor.focus()
this.editor.scrollToLine(0, true, true, () => { })
}
public removeAllSentences() : void { this.sentences.removeAll() }
public removeSentence(e : ISentence<any>) : void { this.sentences.remove(e) }
// removeEditAndFollowingOnes(e : ISentence<any>) : void {
// this.edits.removeEditAndFollowingOnes(e)
// }
public removeSentences(pred : (e : ISentence<any>) => boolean) : void {
this.sentences.removeSentences(pred)
}
// removeFollowingEdits(e : ISentence<any>) : void {
// this.edits.removeFollowingEdits(e)
// }
public removeSentencesByStateIds(ids : StateId[]) : void {
this.sentences.removeSentences(e => e.getStateId().caseOf({
nothing : () => false,
just : id => _(ids).includes(id),
}))
}
// removeEdits(
// predicate : (e : ProcessedEdit) => boolean,
// beforeRemoval? : (e : ProcessedEdit) => void
// ) {
// _.remove(this.editsProcessed, function(e) {
// const toBeRemoved = predicate(e)
// if (toBeRemoved) {
// if (beforeRemoval) { beforeRemoval(e) }
// e.onRemove()
// }
// return toBeRemoved
// })
// }
public sendCommands(s : Command$) : void {
this.commandObserver.onNext(s)
}
public setTip(tip : Tip) : void {
this.tipSubject.onNext(tip)
}
} | the_stack |
import { Container, Enums } from "@packages/core-kernel";
import { RoundState } from "@packages/core-state/src/round-state";
import { Sandbox } from "@packages/core-test-framework";
import { Blocks, Identities, Utils } from "@packages/crypto";
import block1760000 from "./__fixtures__/block1760000";
let sandbox: Sandbox;
let roundState: RoundState;
let databaseService;
let dposState;
let getDposPreviousRoundState;
let stateStore;
let walletRepository;
let triggerService;
let eventDispatcher;
let logger;
beforeEach(() => {
databaseService = {
getLastBlock: jest.fn(),
getBlocks: jest.fn(),
getRound: jest.fn(),
saveRound: jest.fn(),
deleteRound: jest.fn(),
};
dposState = {
buildDelegateRanking: jest.fn(),
setDelegatesRound: jest.fn(),
getRoundDelegates: jest.fn(),
};
getDposPreviousRoundState = jest.fn();
stateStore = {
setGenesisBlock: jest.fn(),
getGenesisBlock: jest.fn(),
setLastBlock: jest.fn(),
getLastBlock: jest.fn(),
getLastBlocksByHeight: jest.fn(),
getCommonBlocks: jest.fn(),
getLastBlockIds: jest.fn(),
};
walletRepository = {
createWallet: jest.fn(),
findByPublicKey: jest.fn(),
findByUsername: jest.fn(),
};
triggerService = {
call: jest.fn(),
};
eventDispatcher = {
call: jest.fn(),
dispatch: jest.fn(),
};
logger = {
error: jest.fn(),
warning: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
};
sandbox = new Sandbox();
sandbox.app.bind(Container.Identifiers.DatabaseService).toConstantValue(databaseService);
sandbox.app.bind(Container.Identifiers.DposState).toConstantValue(dposState);
sandbox.app.bind(Container.Identifiers.DposPreviousRoundStateProvider).toConstantValue(getDposPreviousRoundState);
sandbox.app.bind(Container.Identifiers.StateStore).toConstantValue(stateStore);
sandbox.app.bind(Container.Identifiers.WalletRepository).toConstantValue(walletRepository);
sandbox.app.bind(Container.Identifiers.TriggerService).toConstantValue(triggerService);
sandbox.app.bind(Container.Identifiers.EventDispatcherService).toConstantValue(eventDispatcher);
sandbox.app.bind(Container.Identifiers.LogService).toConstantValue(logger);
roundState = sandbox.app.resolve<RoundState>(RoundState);
});
afterEach(() => {
jest.restoreAllMocks();
});
const generateBlocks = (count: number): any[] => {
const blocks: any[] = [];
for (let i = 1; i <= count; i++) {
blocks.push({
data: {
height: i,
id: "id_" + i,
generatorPublicKey: "public_key_" + i,
},
} as any);
}
return blocks;
};
const generateDelegates = (count: number): any[] => {
const delegates: any[] = [];
for (let i = 1; i <= count; i++) {
const delegate: any = {
getPublicKey: () => {
return "public_key_" + i;
},
username: "username_" + i,
getAttribute: jest.fn().mockImplementation((key) => {
return key === "delegate.username" ? "username_" + i : i;
}),
setAttribute: jest.fn(),
};
delegate.clone = () => {
return delegate;
};
delegates.push(delegate);
}
return delegates;
};
describe("RoundState", () => {
describe("getBlocksForRound", () => {
let blocks: any[];
beforeEach(() => {
blocks = generateBlocks(3);
});
it("should return array of blocks when all requested blocks are in stateStore", async () => {
const lastBlock = blocks[2];
stateStore.getLastBlock.mockReturnValue(lastBlock);
stateStore.getLastBlocksByHeight.mockReturnValue(blocks);
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
// @ts-ignore
await expect(roundState.getBlocksForRound()).resolves.toEqual(blocks);
await expect(stateStore.getLastBlocksByHeight).toHaveBeenCalledWith(1, 3);
await expect(spyOnFromData).toHaveBeenCalledTimes(3);
});
it("should return array of blocks when only last block is in stateStore", async () => {
const lastBlock = blocks[2];
stateStore.getLastBlock.mockReturnValue(lastBlock);
stateStore.getLastBlocksByHeight.mockReturnValue([lastBlock]);
databaseService.getBlocks.mockResolvedValue(blocks.slice(0, 2));
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
// @ts-ignore
await expect(roundState.getBlocksForRound()).resolves.toEqual(blocks);
await expect(stateStore.getLastBlocksByHeight).toHaveBeenCalledWith(1, 3);
await expect(databaseService.getBlocks).toHaveBeenCalledWith(1, 2);
await expect(spyOnFromData).toHaveBeenCalledTimes(3);
});
});
describe("getActiveDelegates", () => {
it("should return shuffled round delegates", async () => {
const lastBlock = Blocks.BlockFactory.fromData(block1760000);
stateStore.getLastBlock.mockReturnValue(lastBlock);
const delegatePublicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37";
const delegateVoteBalance = Utils.BigNumber.make("100");
const roundDelegateModel = { publicKey: delegatePublicKey, balance: delegateVoteBalance };
databaseService.getRound.mockResolvedValueOnce([roundDelegateModel]);
const newDelegateWallet = { setAttribute: jest.fn(), clone: jest.fn(), setPublicKey: jest.fn() };
walletRepository.createWallet.mockReturnValueOnce(newDelegateWallet);
const oldDelegateWallet = { getAttribute: jest.fn() };
walletRepository.findByPublicKey.mockReturnValueOnce(oldDelegateWallet);
const delegateUsername = "test_delegate";
oldDelegateWallet.getAttribute.mockReturnValueOnce(delegateUsername);
const cloneDelegateWallet = {};
newDelegateWallet.clone.mockReturnValueOnce(cloneDelegateWallet);
// @ts-ignore
const spyOnShuffleDelegates = jest.spyOn(roundState, "shuffleDelegates");
await roundState.getActiveDelegates();
expect(walletRepository.findByPublicKey).toBeCalledWith(delegatePublicKey);
expect(walletRepository.createWallet).toBeCalledWith(Identities.Address.fromPublicKey(delegatePublicKey));
expect(oldDelegateWallet.getAttribute).toBeCalledWith("delegate.username");
expect(newDelegateWallet.setAttribute).toBeCalledWith("delegate", {
voteBalance: delegateVoteBalance,
username: delegateUsername,
round: 34510,
});
expect(newDelegateWallet.clone).toBeCalled();
expect(spyOnShuffleDelegates).toBeCalled();
});
it("should return cached forgingDelegates when round is the same", async () => {
const forgingDelegate = { getAttribute: jest.fn() };
const forgingDelegateRound = 2;
forgingDelegate.getAttribute.mockReturnValueOnce(forgingDelegateRound);
// @ts-ignore
roundState.forgingDelegates = [forgingDelegate] as any;
const roundInfo = { round: 2 };
const result = await roundState.getActiveDelegates(roundInfo as any);
expect(forgingDelegate.getAttribute).toBeCalledWith("delegate.round");
// @ts-ignore
expect(result).toBe(roundState.forgingDelegates);
});
});
describe("setForgingDelegatesOfRound", () => {
it("should call getActiveDelegates and set forgingDelegatesOfRound", async () => {
const delegate = {
username: "dummy_delegate",
};
triggerService.call.mockResolvedValue([delegate]);
const roundInfo = { round: 2, roundHeight: 2, nextRound: 3, maxDelegates: 51 };
// @ts-ignore
await roundState.setForgingDelegatesOfRound(roundInfo, [delegate]);
expect(triggerService.call).toHaveBeenCalledWith("getActiveDelegates", {
delegates: [delegate],
roundInfo,
});
// @ts-ignore
expect(roundState.forgingDelegates).toEqual([delegate]);
});
it("should call getActiveDelegates and set forgingDelegatesOfRound to [] if undefined is returned", async () => {
const delegate = {
username: "dummy_delegate",
};
triggerService.call.mockResolvedValue(undefined);
const roundInfo = { round: 2, roundHeight: 2, nextRound: 3, maxDelegates: 51 };
// @ts-ignore
await roundState.setForgingDelegatesOfRound(roundInfo, [delegate]);
expect(triggerService.call).toHaveBeenCalledWith("getActiveDelegates", {
delegates: [delegate],
roundInfo,
});
// @ts-ignore
expect(roundState.forgingDelegates).toEqual([]);
});
});
describe("detectMissedBlocks", () => {
const genesisBlocks = {
data: {
height: 1,
},
};
let delegates: any[];
beforeEach(() => {
delegates = generateDelegates(51);
// @ts-ignore
roundState.forgingDelegates = delegates;
});
it("should not detect missed round when stateStore.lastBlock is genesis block", async () => {
const block = {
data: {
height: 2,
},
};
stateStore.getLastBlock.mockReturnValue(genesisBlocks);
await roundState.detectMissedBlocks(block as any);
expect(logger.debug).not.toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalled();
});
it("should not detect missed block if slots are sequential", async () => {
const block1 = {
data: {
height: 2,
timestamp: 8,
},
};
stateStore.getLastBlock.mockReturnValue(block1);
const block2 = {
data: {
height: 3,
timestamp: 2 * 8,
},
};
await roundState.detectMissedBlocks(block2 as any);
expect(logger.debug).not.toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalled();
});
it("should detect missed block if slots are not sequential", async () => {
const block1 = {
data: {
height: 2,
timestamp: 8,
},
};
stateStore.getLastBlock.mockReturnValue(block1);
const block2 = {
data: {
height: 3,
timestamp: 3 * 8,
},
};
await roundState.detectMissedBlocks(block2 as any);
expect(logger.debug).toHaveBeenCalledTimes(1);
expect(eventDispatcher.dispatch).toHaveBeenCalledTimes(1);
expect(eventDispatcher.dispatch).toHaveBeenCalledWith(Enums.ForgerEvent.Missing, {
delegate: delegates[2],
});
});
it("should detect only one round if multiple rounds are missing", async () => {
const block1 = {
data: {
height: 2,
timestamp: 8,
},
};
stateStore.getLastBlock.mockReturnValue(block1);
const block2 = {
data: {
height: 3,
timestamp: 102 * 8,
},
};
await roundState.detectMissedBlocks(block2 as any);
expect(logger.debug).toHaveBeenCalledTimes(51);
expect(eventDispatcher.dispatch).toHaveBeenCalledTimes(51);
});
});
describe("detectMissedRound", () => {
let delegates: any[];
let blocksInCurrentRound: any[];
beforeEach(() => {
delegates = generateDelegates(3);
// @ts-ignore
roundState.forgingDelegates = delegates;
blocksInCurrentRound = generateBlocks(3);
walletRepository.findByPublicKey = jest.fn().mockImplementation((publicKey) => {
return delegates.find((delegate) => delegate.getPublicKey() === publicKey);
});
});
it("should not detect missed round if all delegates forged blocks", () => {
// @ts-ignore
roundState.blocksInCurrentRound = blocksInCurrentRound;
// @ts-ignore
roundState.detectMissedRound();
expect(logger.debug).not.toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalled();
});
it("should detect missed round", () => {
blocksInCurrentRound[2].data.generatorPublicKey = "public_key_1";
// @ts-ignore
roundState.blocksInCurrentRound = blocksInCurrentRound;
// @ts-ignore
roundState.detectMissedRound();
expect(logger.debug).toHaveBeenCalledTimes(1);
expect(eventDispatcher.dispatch).toHaveBeenCalledWith(Enums.RoundEvent.Missed, { delegate: delegates[2] });
});
});
describe("applyRound", () => {
it("should build delegates, save round, dispatch events when height is 1", async () => {
const forgingDelegate = { getAttribute: jest.fn(), getPublicKey: jest.fn() };
const forgingDelegateRound = 1;
forgingDelegate.getAttribute.mockReturnValueOnce(forgingDelegateRound);
// @ts-ignore
roundState.forgingDelegates = [forgingDelegate] as any;
// @ts-ignore
roundState.blocksInCurrentRound = [];
const delegateWallet = {
getPublicKey: () => {
return "delegate public key";
},
getAttribute: jest.fn(),
};
const dposStateRoundDelegates = [delegateWallet];
dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates);
dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates);
const delegateWalletRound = 1;
delegateWallet.getAttribute.mockReturnValueOnce(delegateWalletRound);
walletRepository.findByPublicKey.mockReturnValueOnce(delegateWallet);
const delegateUsername = "test_delegate";
delegateWallet.getAttribute.mockReturnValueOnce(delegateUsername);
const height = 1;
// @ts-ignore
await roundState.applyRound(height);
expect(dposState.buildDelegateRanking).toBeCalled();
expect(dposState.setDelegatesRound).toBeCalledWith({
round: 1,
nextRound: 1,
roundHeight: 1,
maxDelegates: 51,
});
expect(databaseService.saveRound).toBeCalledWith(dposStateRoundDelegates);
expect(eventDispatcher.dispatch).toBeCalledWith("round.applied");
});
it("should build delegates, save round, dispatch events, and skip missing round checks when first round has genesis block only", async () => {
const forgingDelegate = { getAttribute: jest.fn(), getPublicKey: jest.fn() };
const forgingDelegateRound = 1;
forgingDelegate.getAttribute.mockReturnValueOnce(forgingDelegateRound);
// @ts-ignore
roundState.forgingDelegates = [forgingDelegate] as any;
// @ts-ignore
roundState.blocksInCurrentRound = [{ data: { height: 1 } }] as any;
const delegateWallet = { publicKey: "delegate public key", getAttribute: jest.fn() };
const dposStateRoundDelegates = [delegateWallet];
dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates);
dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates);
const delegateWalletRound = 2;
delegateWallet.getAttribute.mockReturnValueOnce(delegateWalletRound);
walletRepository.findByPublicKey.mockReturnValueOnce(delegateWallet);
const delegateUsername = "test_delegate";
delegateWallet.getAttribute.mockReturnValueOnce(delegateUsername);
const height = 51;
// @ts-ignore
await roundState.applyRound(height);
expect(dposState.buildDelegateRanking).toBeCalled();
expect(dposState.setDelegatesRound).toBeCalledWith({
round: 2,
nextRound: 2,
roundHeight: 52,
maxDelegates: 51,
});
expect(databaseService.saveRound).toBeCalledWith(dposStateRoundDelegates);
expect(eventDispatcher.dispatch).toBeCalledWith("round.applied");
});
it("should do nothing when next height is same round", async () => {
// @ts-ignore
await roundState.applyRound(50);
expect(logger.info).not.toBeCalled();
});
});
describe("applyBlock", () => {
let delegates: any[];
beforeEach(() => {
delegates = generateDelegates(51);
// @ts-ignore
roundState.forgingDelegates = delegates;
});
it("should push block to blocksInCurrentRound and skip applyRound when block is not last block in round", async () => {
const block = {
data: {
height: 52, // First block in round 2
},
};
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
await roundState.applyBlock(block as any);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([block]);
expect(databaseService.saveRound).not.toHaveBeenCalled();
});
it("should push block to blocksInCurrentRound, applyRound, check missing round, calculate delegates, and clear blocksInCurrentRound when block is last in round", async () => {
// @ts-ignore
roundState.blocksInCurrentRound = generateBlocks(50);
const block = {
data: {
height: 51, // Last block in round 1
generatorPublicKey: "public_key_51",
},
};
dposState.getRoundDelegates.mockReturnValue(delegates);
triggerService.call.mockImplementation((name, args) => {
return roundState.getActiveDelegates(args.roundInfo, args.delegates);
});
// @ts-ignore
const spyOnShuffleDelegates = jest.spyOn(roundState, "shuffleDelegates");
// @ts-ignore
const spyOnDetectMissedRound = jest.spyOn(roundState, "detectMissedRound");
// @ts-ignore
expect(roundState.blocksInCurrentRound.length).toEqual(50);
await roundState.applyBlock(block as any);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
expect(databaseService.saveRound).toHaveBeenCalled();
expect(eventDispatcher.dispatch).toHaveBeenCalledWith(Enums.RoundEvent.Applied);
expect(spyOnShuffleDelegates).toHaveBeenCalled();
expect(spyOnDetectMissedRound).toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalledWith(Enums.RoundEvent.Missed);
});
// TODO: Check how we can restore
it("should throw error if databaseService.saveRound throws error", async () => {
// @ts-ignore
roundState.blocksInCurrentRound = generateBlocks(50);
const block = {
data: {
height: 51, // Last block in round 1
generatorPublicKey: "public_key_51",
},
};
dposState.getRoundDelegates.mockReturnValue(delegates);
triggerService.call.mockImplementation((name, args) => {
return roundState.getActiveDelegates(args.roundInfo, args.delegates);
});
// @ts-ignore
const spyOnShuffleDelegates = jest.spyOn(roundState, "shuffleDelegates");
// @ts-ignore
const spyOnDetectMissedRound = jest.spyOn(roundState, "detectMissedRound");
databaseService.saveRound.mockImplementation(async () => {
throw new Error("Cannot save round");
});
// @ts-ignore
expect(roundState.blocksInCurrentRound.length).toEqual(50);
await expect(roundState.applyBlock(block as any)).rejects.toThrow("Cannot save round");
// @ts-ignore
expect(roundState.blocksInCurrentRound.length).toEqual(51);
expect(databaseService.saveRound).toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalled();
expect(spyOnShuffleDelegates).toHaveBeenCalled();
expect(spyOnDetectMissedRound).toHaveBeenCalled();
expect(eventDispatcher.dispatch).not.toHaveBeenCalledWith(Enums.RoundEvent.Missed);
});
// TODO: Check genesisBlock if required
});
describe("revertBlock", () => {
it("should remove last block from blocksInCurrentRound when block is in the same round", async () => {
const block = {
data: {
height: 52, // First block of round 2
},
} as any;
// @ts-ignore
roundState.blocksInCurrentRound = [block];
await roundState.revertBlock(block);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
expect(databaseService.deleteRound).not.toHaveBeenCalled();
});
it("should restore previous round, load previousRoundBlocks and delegates, remove last round from DB and remove last block from blocksInCurrentRound if block is last in round", async () => {
const blocksInPreviousRound: any[] = generateBlocks(51);
const delegates: any[] = generateDelegates(51);
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
const block = blocksInPreviousRound[50];
stateStore.getLastBlocksByHeight.mockReturnValue(blocksInPreviousRound);
stateStore.getLastBlock.mockReturnValue(block);
getDposPreviousRoundState.mockReturnValue({
getAllDelegates: jest.fn().mockReturnValue(delegates),
getActiveDelegates: jest.fn().mockReturnValue(delegates),
getRoundDelegates: jest.fn().mockReturnValue(delegates),
});
const spyOnCalcPreviousActiveDelegates = jest
// @ts-ignore
.spyOn(roundState, "calcPreviousActiveDelegates")
.mockReturnValue(delegates);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
await roundState.revertBlock(block);
expect(spyOnCalcPreviousActiveDelegates).toHaveBeenCalledTimes(1);
expect(spyOnFromData).toHaveBeenCalledTimes(51);
expect(databaseService.deleteRound).toHaveBeenCalledWith(2);
// @ts-ignore
expect(roundState.blocksInCurrentRound.length).toEqual(50);
});
it("should throw error if databaseService throws error", async () => {
const blocksInPreviousRound: any[] = generateBlocks(51);
const delegates: any[] = generateDelegates(51);
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
const block = blocksInPreviousRound[50];
stateStore.getLastBlocksByHeight.mockReturnValue(blocksInPreviousRound);
stateStore.getLastBlock.mockReturnValue(block);
getDposPreviousRoundState.mockReturnValue({
getAllDelegates: jest.fn().mockReturnValue(delegates),
getActiveDelegates: jest.fn().mockReturnValue(delegates),
getRoundDelegates: jest.fn().mockReturnValue(delegates),
});
const spyOnCalcPreviousActiveDelegates = jest
// @ts-ignore
.spyOn(roundState, "calcPreviousActiveDelegates")
.mockReturnValue(delegates);
databaseService.deleteRound.mockImplementation(async () => {
throw new Error("Database error");
});
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
await expect(roundState.revertBlock(block)).rejects.toThrow("Database error");
expect(spyOnCalcPreviousActiveDelegates).toHaveBeenCalledTimes(1);
expect(spyOnFromData).toHaveBeenCalledTimes(51);
expect(databaseService.deleteRound).toHaveBeenCalledWith(2);
// @ts-ignore
expect(roundState.blocksInCurrentRound.length).toEqual(51);
});
it("should throw error if last blocks is not equal to block", async () => {
const blocks = generateBlocks(2);
// @ts-ignore
roundState.blocksInCurrentRound = [blocks[0]];
await expect(roundState.revertBlock(blocks[1])).rejects.toThrow(
"Last block in blocksInCurrentRound doesn't match block with id id_2",
);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([blocks[0]]);
expect(databaseService.deleteRound).not.toHaveBeenCalled();
expect(stateStore.getLastBlocksByHeight).not.toHaveBeenCalled();
});
});
describe("restore", () => {
it("should restore blocksInCurrentRound and forgingDelegates when last block in middle of round", async () => {
const delegates: any[] = generateDelegates(51);
const blocks: any[] = generateBlocks(3);
const lastBlock = blocks[2];
stateStore.getLastBlock.mockReturnValue(lastBlock);
stateStore.getLastBlocksByHeight.mockReturnValue(blocks);
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
triggerService.call.mockResolvedValue(delegates);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
// @ts-ignore
expect(roundState.forgingDelegates).toEqual([]);
await roundState.restore();
expect(spyOnFromData).toHaveBeenCalledTimes(3);
expect(databaseService.deleteRound).toHaveBeenCalledWith(2);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual(blocks);
// @ts-ignore
expect(roundState.forgingDelegates).toEqual(delegates);
});
it("should restore blocksInCurrentRound and forgingDelegates when last block is lastBlock of round", async () => {
const delegates: any[] = generateDelegates(51);
const blocks: any[] = generateBlocks(51);
const lastBlock = blocks[50];
stateStore.getLastBlock.mockReturnValue(lastBlock);
stateStore.getLastBlocksByHeight.mockReturnValue(blocks);
// @ts-ignore
const spyOnFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
dposState.getRoundDelegates.mockReturnValue(delegates);
triggerService.call.mockResolvedValue(delegates);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
// @ts-ignore
expect(roundState.forgingDelegates).toEqual([]);
await roundState.restore();
expect(databaseService.deleteRound).toHaveBeenCalledWith(2);
expect(databaseService.saveRound).toHaveBeenCalledWith(delegates);
expect(spyOnFromData).toHaveBeenCalledTimes(51);
expect(eventDispatcher.dispatch).toHaveBeenCalledWith(Enums.RoundEvent.Applied);
// @ts-ignore
expect(roundState.blocksInCurrentRound).toEqual([]);
// @ts-ignore
expect(roundState.forgingDelegates).toEqual(delegates);
});
it("should throw if databaseService throws error", async () => {
const delegates: any[] = generateDelegates(51);
const blocks: any[] = generateBlocks(51);
const lastBlock = blocks[50];
stateStore.getLastBlock.mockReturnValue(lastBlock);
stateStore.getLastBlocksByHeight.mockReturnValue(blocks);
dposState.getRoundDelegates.mockReturnValue(delegates);
triggerService.call.mockResolvedValue(delegates);
// @ts-ignore
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation((block) => {
return block;
});
databaseService.deleteRound.mockImplementation(() => {
throw new Error("Database error");
});
await expect(roundState.restore()).rejects.toThrow("Database error");
expect(databaseService.deleteRound).toHaveBeenCalledWith(2);
});
});
describe("calcPreviousActiveDelegates", () => {
it("should return previous active delegates && set ranks", async () => {
const delegates = generateDelegates(51);
const blocks = generateBlocks(51);
getDposPreviousRoundState.mockReturnValue({
getAllDelegates: jest.fn().mockReturnValue(delegates),
getActiveDelegates: jest.fn().mockReturnValue(delegates),
getRoundDelegates: jest.fn().mockReturnValue(delegates),
});
walletRepository.findByUsername = jest.fn().mockImplementation((username) => {
return delegates.find((delegate) => delegate.username === username);
});
const roundInfo: any = { round: 1 };
// @ts-ignore
await expect(roundState.calcPreviousActiveDelegates(roundInfo, blocks)).resolves.toEqual(delegates);
expect(walletRepository.findByUsername).toHaveBeenCalledTimes(51);
expect(delegates[0].setAttribute).toHaveBeenCalledWith("delegate.rank", 1);
expect(delegates[0].setAttribute).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import identity = require('lodash.identity')
const plain = true
import { IJSONBlock } from '../models/Block'
import {
ITransaction,
} from '../ourbit/types'
import { IPersistInterface } from '../stores'
import { toBN } from '../utils'
export const makeSequelizeModels = (
Sequelize: any,
sequelize: any,
) => {
const { DataTypes } = Sequelize
const Reducer = sequelize.define('reducer', {
id: { type: DataTypes.STRING, primaryKey: true },
})
const Transaction = sequelize.define('transaction', {
id: { type: DataTypes.STRING, primaryKey: true },
mid: { type: DataTypes.INTEGER, autoIncrement: true },
blockHash: { type: DataTypes.STRING },
}, {
indexes: [
{ fields: ['blockHash'] },
],
})
const Patch = sequelize.define('patch', {
id: { type: DataTypes.STRING, primaryKey: true },
mid: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
})
const Operation = sequelize.define('operation', {
mid: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
path: { type: DataTypes.STRING },
op: { type: DataTypes.JSONB },
value: { type: DataTypes.JSONB },
oldValue: { type: DataTypes.JSONB },
volatile: { type: DataTypes.BOOLEAN, defaultValue: false },
})
const Reason = sequelize.define('reason', {
key: { type: DataTypes.STRING },
meta: { type: DataTypes.JSONB },
}, {
indexes: [
{ fields: ['key'] },
],
})
// we explicitely don't save all of the fields of block, even though typescript assumes we do
// if there's every a property that ethereumjs-blockstream expects that we don't store, stuff will break
const HistoricalBlock = sequelize.define('historicalblock', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
hash: { type: DataTypes.STRING },
number: { type: DataTypes.STRING },
numberDecimal: { type: DataTypes.DECIMAL(76, 0) },
parentHash: { type: DataTypes.STRING },
}, {
indexes: [
{ fields: ['hash'] },
{ fields: ['numberDecimal'] },
],
})
// each reducer has many historical blocks
Reducer.HistoricalBlocks = Reducer.hasMany(HistoricalBlock)
// each historical block belongs to a reducer
HistoricalBlock.Reducer = HistoricalBlock.belongsTo(Reducer)
// a reducer has many transactions
Reducer.Transactions = Reducer.hasMany(Transaction)
// a transaction belongs to a reducer
Transaction.Reducer = Transaction.belongsTo(Reducer)
// transaction has many patches
Transaction.Patches = Transaction.hasMany(Patch)
// patch belongs to transaction
Patch.Transaction = Patch.belongsTo(Transaction)
// a patch has many operations
Patch.Operations = Patch.hasMany(Operation)
// an operation belongs to patch
Operation.Patch = Operation.belongsTo(Patch)
// a reason belongs to a patch
Reason.Patch = Reason.belongsTo(Patch)
// a patch has one reason
Patch.Reason = Patch.hasOne(Reason)
return {
Reducer,
HistoricalBlock,
Transaction,
Patch,
Reason,
Operation,
}
}
async function* batch (
model: any,
query = {},
batchSize = 1000,
mapper: (v: any) => any = identity,
) {
const count = await model.count(query)
if (count === 0) {
return false
}
const pages = Math.max(Math.round(count / batchSize), 1)
let page = 1
while (page <= pages) {
const params = {
...query,
offset: (page - 1) * batchSize,
limit: batchSize,
}
const gots = await model.findAll(params)
yield mapper(gots)
page = page + 1
}
}
class SequelizePersistInterface implements IPersistInterface {
private Reducer
private HistoricalBlock
private Transaction
private Patch
private Reason
private Operation
constructor (
private Sequelize: any,
sequelize: any,
) {
const {
Reducer,
HistoricalBlock,
Transaction,
Patch,
Operation,
Reason,
} = makeSequelizeModels(
Sequelize,
sequelize,
)
this.Reducer = Reducer
this.HistoricalBlock = HistoricalBlock
this.Transaction = Transaction
this.Patch = Patch
this.Operation = Operation
this.Reason = Reason
}
public setup = async () => {
await this.Reducer.sync()
await this.Transaction.sync()
await this.Patch.sync()
await this.Operation.sync()
await this.Reason.sync()
await this.HistoricalBlock.sync()
}
public setdown = async () => {
await this.Reason.drop({ cascade: true })
await this.Operation.drop({ cascade: true })
await this.Patch.drop({ cascade: true })
await this.Transaction.drop({ cascade: true })
await this.Reducer.drop({ cascade: true })
await this.HistoricalBlock.drop({ cascade: true })
}
public saveReducer = async (reducerKey: string): Promise<any> => {
await this.Reducer.upsert({ id: reducerKey })
}
public deleteReducer = async (reducerKey: string): Promise<any> => {
await this.Reducer.destroy({
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
})
}
public getHistoricalBlocks = async (reducerKey: string): Promise<IJSONBlock[]> => {
const blocks = await this.HistoricalBlock.findAll({
include: [{
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
order: [['numberDecimal', 'ASC']],
})
return blocks.map((b) => b.get({ plain }))
}
public saveHistoricalBlock = async (
reducerKey: string,
blockRetention: number,
block: IJSONBlock,
): Promise<any> => {
try {
const blockNum = toBN(block.number)
// TODO: needed optimization to reduce calls to DB
await this.HistoricalBlock.create({
reducerId: reducerKey,
hash: block.hash,
number: block.number,
numberDecimal: blockNum.toString(),
parentHash: block.parentHash,
})
// remove blocks that are further away than the block retention limit
await this.HistoricalBlock.destroy({
where: {
reducerId: { [this.Sequelize.Op.eq]: reducerKey },
numberDecimal: { [this.Sequelize.Op.lte]: blockNum.sub(toBN(blockRetention)).toString() },
},
})
} catch (error) {
throw new Error(`Was not able to save historical block
${JSON.stringify(block)} in reducer ${reducerKey}. ${error.stack}`)
}
}
public deleteHistoricalBlock = async (reducerKey: string, blockHash: string): Promise<any> => {
try {
await this.HistoricalBlock.destroy({
where: {
reducerId: { [this.Sequelize.Op.eq]: reducerKey },
hash: { [this.Sequelize.Op.eq]: blockHash },
},
})
} catch (error) {
throw new Error(`Was not able to delete historical block ${blockHash} in reducer ${reducerKey}. ${error.stack}`)
}
}
public deleteHistoricalBlocks = async (reducerKey: string): Promise<any> => {
try {
await this.HistoricalBlock.destroy({
where: {
reducerId: { [this.Sequelize.Op.eq]: reducerKey },
},
})
} catch (error) {
throw new Error(`Was not able to delete historical blocks in reducer ${reducerKey}. ${error.stack}`)
}
}
public getLatestTransaction = async (reducerKey: string): Promise<ITransaction> => {
try {
return (await this.Transaction.findOne({
order: [['mid', 'DESC']],
rejectOnEmpty: true,
include: [{
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
})).get({ plain })
} catch (error) {
throw new Error(`Could not get latest transaction ${error.stack}`)
}
}
public getAllTransactionsTo = async function (reducerKey: string, toTxId: null | string):
Promise<any> {
let initial
try {
initial = await this.getPlainTransaction(reducerKey, toTxId)
} catch (error) {
throw new Error(`Could not find txId ${toTxId} in ${reducerKey} - ${error.stack}`)
}
const query = {
where: { mid: { [this.Sequelize.Op.lte]: initial.mid } },
include: [{
model: this.Patch,
include: [{
model: this.Operation,
where: { volatile: { [this.Sequelize.Op.eq]: false } },
}],
}, {
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
order: [
['mid', 'ASC'],
[{ model: this.Patch }, 'mid', 'ASC'],
[{ model: this.Patch }, { model: this.Operation }, 'mid', 'ASC'],
],
}
return batch(this.Transaction, query, 1000, (txs) => txs.map(
(tx) => tx.get({ plain }),
))
}
public deleteTransaction = async (reducerKey: string, tx: ITransaction) => {
// @TODO does this delete patches, etc as well? seems like not, by default
return this.Transaction.destroy({
where: { id: { [this.Sequelize.Op.eq]: tx.id } },
include: [{
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
})
}
public saveTransaction = async (reducerKey: string, tx: ITransaction) => {
return this.Transaction.create({
...tx,
reducerId: reducerKey,
}, {
include: [{
association: this.Transaction.Patches,
include: [
this.Patch.Reason,
this.Patch.Operations,
],
}],
})
}
public getTransaction = async (reducerKey: string, txId: string): Promise<ITransaction> => {
return this.getTransactionWithQuery(reducerKey, { id: { [this.Sequelize.Op.eq]: txId } })
}
public getTransactionByBlockHash = async (reducerKey: string, blockHash: string): Promise<ITransaction> => {
return this.getTransactionWithQuery(reducerKey, { blockHash: { [this.Sequelize.Op.eq]: blockHash } })
}
private getTransactionWithQuery = async (reducerKey, where: object): Promise<ITransaction> => {
try {
return (await this.Transaction.findOne({
where,
include: [{
model: this.Patch,
required: false,
include: [{
model: this.Operation,
required: false,
}, {
model: this.Reason,
required: false,
}],
}, {
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
order: [
[{ model: this.Patch }, 'mid', 'ASC'],
[{ model: this.Patch }, { model: this.Operation }, 'mid', 'ASC'],
],
rejectOnEmpty: true,
})).get({ plain })
} catch (error) {
throw new Error(`Could not find transaction using query
${JSON.stringify(where)} under reducer ${reducerKey} ${error.stack}`)
}
}
private getPlainTransaction = async (reducerKey: string, txId: string): Promise<ITransaction> => {
try {
return (await this.Transaction.findOne({
where: { id: { [this.Sequelize.Op.eq]: txId } },
rejectOnEmpty: true,
include: [{
model: this.Reducer,
where: { id: { [this.Sequelize.Op.eq]: reducerKey } },
}],
})).get({ plain })
} catch (error) {
throw new Error(`Could not get transaction ${txId} ${error.stack}`)
}
}
}
export default SequelizePersistInterface | the_stack |
* @fileoverview Implements the SVGWrapper class
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {OptionList} from '../../util/Options.js';
import {BBox} from '../../util/BBox.js';
import {CommonWrapper, AnyWrapperClass, Constructor} from '../common/Wrapper.js';
import {SVG, XLINKNS} from '../svg.js';
import {SVGWrapperFactory} from './WrapperFactory.js';
import {SVGFontData, SVGDelimiterData, SVGCharOptions} from './FontData.js';
export {Constructor, StringMap} from '../common/Wrapper.js';
/*****************************************************************/
/**
* Shorthand for makeing a SVGWrapper constructor
*/
export type SVGConstructor<N, T, D> = Constructor<SVGWrapper<N, T, D>>;
/*****************************************************************/
/**
* The type of the SVGWrapper class (used when creating the wrapper factory for this class)
*/
export interface SVGWrapperClass extends AnyWrapperClass {
kind: string;
}
/*****************************************************************/
/**
* The base SVGWrapper class
*
* @template N The HTMLElement node class
* @template T The Text node class
* @template D The Document class
*/
export class SVGWrapper<N, T, D> extends
CommonWrapper<
SVG<N, T, D>,
SVGWrapper<N, T, D>,
SVGWrapperClass,
SVGCharOptions,
SVGDelimiterData,
SVGFontData
> {
/**
* The kind of wrapper
*/
public static kind: string = 'unknown';
/**
* A fuzz factor for borders to avoid anti-alias problems at the edges
*/
public static borderFuzz = 0.005;
/**
* The factory used to create more SVGWrappers
*/
protected factory: SVGWrapperFactory<N, T, D>;
/**
* @override
*/
public parent: SVGWrapper<N, T, D>;
/**
* @override
*/
public childNodes: SVGWrapper<N, T, D>[];
/**
* The SVG element generated for this wrapped node
*/
public element: N = null;
/**
* Offset due to border/padding
*/
public dx: number = 0;
/**
* @override
*/
public font: SVGFontData;
/*******************************************************************/
/**
* Create the HTML for the wrapped node.
*
* @param {N} parent The HTML node where the output is added
*/
public toSVG(parent: N) {
this.addChildren(this.standardSVGnode(parent));
}
/**
* @param {N} parent The element in which to add the children
*/
public addChildren(parent: N) {
let x = 0;
for (const child of this.childNodes) {
child.toSVG(parent);
const bbox = child.getOuterBBox();
if (child.element) {
child.place(x + bbox.L * bbox.rscale, 0);
}
x += (bbox.L + bbox.w + bbox.R) * bbox.rscale;
}
}
/*******************************************************************/
/**
* Create the standard SVG element for the given wrapped node.
*
* @param {N} parent The HTML element in which the node is to be created
* @returns {N} The root of the HTML tree for the wrapped node's output
*/
protected standardSVGnode(parent: N): N {
const svg = this.createSVGnode(parent);
this.handleStyles();
this.handleScale();
this.handleBorder();
this.handleColor();
this.handleAttributes();
return svg;
}
/**
* @param {N} parent The HTML element in which the node is to be created
* @returns {N} The root of the HTML tree for the wrapped node's output
*/
protected createSVGnode(parent: N): N {
this.element = this.svg('g', {'data-mml-node': this.node.kind});
const href = this.node.attributes.get('href');
if (href) {
parent = this.adaptor.append(parent, this.svg('a', {href: href})) as N;
const {h, d, w} = this.getOuterBBox();
this.adaptor.append(this.element, this.svg('rect', {
'data-hitbox': true, fill: 'none', stroke: 'none', 'pointer-events': 'all',
width: this.fixed(w), height: this.fixed(h + d), y: this.fixed(-d)
}));
}
this.adaptor.append(parent, this.element) as N;
return this.element;
}
/**
* Set the CSS styles for the svg element
*/
protected handleStyles() {
if (!this.styles) return;
const styles = this.styles.cssText;
if (styles) {
this.adaptor.setAttribute(this.element, 'style', styles);
}
BBox.StyleAdjust.forEach(([name, , lr]) => {
if (lr !== 0) return;
const x = this.styles.get(name);
if (x) {
this.dx += this.length2em(x, 1, this.bbox.rscale);
}
});
}
/**
* Set the (relative) scaling factor for the node
*/
protected handleScale() {
if (this.bbox.rscale !== 1) {
const scale = 'scale(' + this.fixed(this.bbox.rscale / 1000, 3) + ')';
this.adaptor.setAttribute(this.element, 'transform', scale);
}
}
/**
* Add the foreground and background colors
* (Only look at explicit attributes, since inherited ones will
* be applied to a parent element, and we will inherit from that)
*/
protected handleColor() {
const adaptor = this.adaptor;
const attributes = this.node.attributes;
const mathcolor = attributes.getExplicit('mathcolor') as string;
const color = attributes.getExplicit('color') as string;
const mathbackground = attributes.getExplicit('mathbackground') as string;
const background = attributes.getExplicit('background') as string;
const bgcolor = (this.styles?.get('background-color') || '');
if (mathcolor || color) {
adaptor.setAttribute(this.element, 'fill', mathcolor || color);
adaptor.setAttribute(this.element, 'stroke', mathcolor || color);
}
if (mathbackground || background || bgcolor) {
let {h, d, w} = this.getOuterBBox();
let rect = this.svg('rect', {
fill: mathbackground || background || bgcolor,
x: this.fixed(-this.dx), y: this.fixed(-d),
width: this.fixed(w),
height: this.fixed(h + d),
'data-bgcolor': true
});
let child = adaptor.firstChild(this.element);
if (child) {
adaptor.insert(rect, child);
} else {
adaptor.append(this.element, rect);
}
}
}
/**
* Create the borders, if any are requested.
*/
protected handleBorder() {
if (!this.styles) return;
const width = Array(4).fill(0);
const style = Array(4);
const color = Array(4);
for (const [name, i] of [['Top', 0], ['Right', 1], ['Bottom', 2], ['Left', 3]] as [string, number][]) {
const key = 'border' + name;
const w = this.styles.get(key + 'Width');
if (!w) continue;
width[i] = Math.max(0, this.length2em(w, 1, this.bbox.rscale));
style[i] = this.styles.get(key + 'Style') || 'solid';
color[i] = this.styles.get(key + 'Color') || 'currentColor';
}
const f = SVGWrapper.borderFuzz;
const bbox = this.getOuterBBox();
const [h, d, w] = [bbox.h + f, bbox.d + f, bbox.w + f];
const outerRT = [w, h];
const outerLT = [-f, h];
const outerRB = [w, -d];
const outerLB = [-f, -d];
const innerRT = [w - width[1], h - width[0]];
const innerLT = [-f + width[3], h - width[0]];
const innerRB = [w - width[1], -d + width[2]];
const innerLB = [-f + width[3], -d + width[2]];
const paths: number[][][] = [
[outerLT, outerRT, innerRT, innerLT],
[outerRB, outerRT, innerRT, innerRB],
[outerLB, outerRB, innerRB, innerLB],
[outerLB, outerLT, innerLT, innerLB]
];
const adaptor = this.adaptor;
const child = adaptor.firstChild(this.element) as N;
for (const i of [0, 1, 2, 3]) {
if (!width[i]) continue;
const path = paths[i];
if (style[i] === 'dashed' || style[i] === 'dotted') {
this.addBorderBroken(path, color[i], style[i], width[i], i);
} else {
this.addBorderSolid(path, color[i], child);
}
}
}
/**
* Create a solid border piece with the given color
*
* @param {[number, number][]} path The points for the border segment
* @param {string} color The color to use
* @param {N} child Insert the border before this child, if any
*/
protected addBorderSolid(path: number[][], color: string, child: N) {
const border = this.svg('polygon', {
points: path.map(([x, y]) => `${this.fixed(x - this.dx)},${this.fixed(y)}`).join(' '),
stroke: 'none',
fill: color
});
if (child) {
this.adaptor.insert(border, child);
} else {
this.adaptor.append(this.element, border);
}
}
/**
* Create a dashed or dotted border line with the given width and color
*
* @param {[number, number][]} path The points for the border segment
* @param {string} color The color to use
* @param {string} style Either 'dotted' or 'dashed'
* @param {number} t The thickness for the border line
* @param {number} i The side being drawn
*/
protected addBorderBroken(path: number[][], color: string, style: string, t: number, i: number) {
const dot = (style === 'dotted');
const t2 = t / 2;
const [tx1, ty1, tx2, ty2] = [[t2, -t2, -t2, -t2], [-t2, t2, -t2, -t2], [t2, t2, -t2, t2], [t2, t2, t2, -t2]][i];
const [A, B] = path;
const x1 = A[0] + tx1 - this.dx, y1 = A[1] + ty1;
const x2 = B[0] + tx2 - this.dx, y2 = B[1] + ty2;
const W = Math.abs(i % 2 ? y2 - y1 : x2 - x1);
const n = (dot ? Math.ceil(W / (2 * t)) : Math.ceil((W - t) / (4 * t)));
const m = W / (4 * n + 1);
const line = this.svg('line', {
x1: this.fixed(x1), y1: this.fixed(y1),
x2: this.fixed(x2), y2: this.fixed(y2),
'stroke-width': this.fixed(t), stroke: color, 'stroke-linecap': dot ? 'round' : 'square',
'stroke-dasharray': dot ? [1, this.fixed(W / n - .002)].join(' ') : [this.fixed(m), this.fixed(3 * m)].join(' ')
});
const adaptor = this.adaptor;
const child = adaptor.firstChild(this.element);
if (child) {
adaptor.insert(line, child);
} else {
adaptor.append(this.element, line);
}
}
/**
* Copy RDFa, aria, and other tags from the MathML to the SVG output nodes.
* Don't copy those in the skipAttributes list, or anything that already exists
* as a property of the node (e.g., no "onlick", etc.). If a name in the
* skipAttributes object is set to false, then the attribute WILL be copied.
* Add the class to any other classes already in use.
*/
protected handleAttributes() {
const attributes = this.node.attributes;
const defaults = attributes.getAllDefaults();
const skip = SVGWrapper.skipAttributes;
for (const name of attributes.getExplicitNames()) {
if (skip[name] === false || (!(name in defaults) && !skip[name] &&
!this.adaptor.hasAttribute(this.element, name))) {
this.adaptor.setAttribute(this.element, name, attributes.getExplicit(name) as string);
}
}
if (attributes.get('class')) {
const names = (attributes.get('class') as string).trim().split(/ +/);
for (const name of names) {
this.adaptor.addClass(this.element, name);
}
}
}
/*******************************************************************/
/**
* @param {number} x The x-offset for the element
* @param {number} y The y-offset for the element
* @param {N} element The element to be placed
*/
public place(x: number, y: number, element: N = null) {
x += this.dx;
if (!(x || y)) return;
if (!element) {
element = this.element;
y = this.handleId(y);
}
const translate = `translate(${this.fixed(x)},${this.fixed(y)})`;
const transform = this.adaptor.getAttribute(element, 'transform') || '';
this.adaptor.setAttribute(element, 'transform', translate + (transform ? ' ' + transform : ''));
}
/**
* Firefox and Safari don't scroll to the top of the element with an Id, so
* we shift the element up and then translate its contents down in order to
* correct for their positioning. Also, Safari will go to the baseline of
* a <text> element (e.g., when mtextInheritFont is true), so add a text
* element to help Safari get the right location.
*
* @param {number} y The current offset of the element
* @return {number} The new offset for the element if it has an id
*/
protected handleId(y: number): number {
if (!this.node.attributes || !this.node.attributes.get('id')) {
return y;
}
const adaptor = this.adaptor;
const h = this.getBBox().h;
//
// Remove the element's children and put them into a <g> with transform
//
const children = adaptor.childNodes(this.element);
children.forEach(child => adaptor.remove(child));
const g = this.svg('g', {'data-idbox': true, transform: `translate(0,${this.fixed(-h)})`}, children);
//
// Add the text element (not transformed) and the transformed <g>
//
adaptor.append(this.element, this.svg('text', {'data-id-align': true} , [this.text('')]));
adaptor.append(this.element, g);
return y + h;
}
/**
* Return the first child element, skipping id align boxes and href hit boxes
*
* @return {N} The first "real" child element
*/
public firstChild(): N {
const adaptor = this.adaptor;
let child = adaptor.firstChild(this.element);
if (child && adaptor.kind(child) === 'text' && adaptor.getAttribute(child, 'data-id-align')) {
child = adaptor.firstChild(adaptor.next(child));
}
if (child && adaptor.kind(child) === 'rect' && adaptor.getAttribute(child, 'data-hitbox')) {
child = adaptor.next(child);
}
return child;
}
/**
* @param {number} n The character number
* @param {number} x The x-position of the character
* @param {number} y The y-position of the character
* @param {N} parent The container for the character
* @param {string} variant The variant to use for the character
* @return {number} The width of the character
*/
public placeChar(n: number, x: number, y: number, parent: N, variant: string = null): number {
if (variant === null) {
variant = this.variant;
}
const C = n.toString(16).toUpperCase();
const [ , , w, data] = this.getVariantChar(variant, n);
if ('p' in data) {
const path = (data.p ? 'M' + data.p + 'Z' : '');
this.place(x, y, this.adaptor.append(parent, this.charNode(variant, C, path)));
} else if ('c' in data) {
const g = this.adaptor.append(parent, this.svg('g', {'data-c': C}));
this.place(x, y, g);
x = 0;
for (const n of this.unicodeChars(data.c, variant)) {
x += this.placeChar(n, x, y, g, variant);
}
} else if (data.unknown) {
const char = String.fromCodePoint(n);
const text = this.adaptor.append(parent, this.jax.unknownText(char, variant));
this.place(x, y, text);
return this.jax.measureTextNodeWithCache(text, char, variant).w;
}
return w;
}
/**
* @param {string} variant The name of the variant being used
* @param {string} C The hex string for the character code
* @param {string} path The data from the character
* @return {N} The <path> or <use> node for the glyph
*/
protected charNode(variant: string, C: string, path: string): N {
const cache = this.jax.options.fontCache;
return (cache !== 'none' ? this.useNode(variant, C, path) : this.pathNode(C, path));
}
/**
* @param {string} C The hex string for the character code
* @param {string} path The data from the character
* @return {N} The <path> for the glyph
*/
protected pathNode(C: string, path: string): N {
return this.svg('path', {'data-c': C, d: path});
}
/**
* @param {string} variant The name of the variant being used
* @param {string} C The hex string for the character code
* @param {string} path The data from the character
* @return {N} The <use> node for the glyph
*/
protected useNode(variant: string, C: string, path: string): N {
const use = this.svg('use', {'data-c': C});
const id = '#' + this.jax.fontCache.cachePath(variant, C, path);
this.adaptor.setAttribute(use, 'href', id, XLINKNS);
return use;
}
/*******************************************************************/
/**
* For debugging
*/
public drawBBox() {
let {w, h, d} = this.getBBox();
const box = this.svg('g', {style: {
opacity: .25
}}, [
this.svg('rect', {
fill: 'red',
height: this.fixed(h),
width: this.fixed(w)
}),
this.svg('rect', {
fill: 'green',
height: this.fixed(d),
width: this.fixed(w),
y: this.fixed(-d)
})
] as N[]);
const node = this.element || this.parent.element;
this.adaptor.append(node, box);
}
/*******************************************************************/
/*
* Easy access to some utility routines
*/
/**
* @param {string} type The tag name of the HTML node to be created
* @param {OptionList} def The properties to set for the created node
* @param {(N|T)[]} content The child nodes for the created HTML node
* @return {N} The generated HTML tree
*/
public html(type: string, def: OptionList = {}, content: (N | T)[] = []): N {
return this.jax.html(type, def, content);
}
/**
* @param {string} type The tag name of the svg node to be created
* @param {OptionList} def The properties to set for the created node
* @param {(N|T)[]} content The child nodes for the created SVG node
* @return {N} The generated SVG tree
*/
public svg(type: string, def: OptionList = {}, content: (N | T)[] = []): N {
return this.jax.svg(type, def, content);
}
/**
* @param {string} text The text from which to create an HTML text node
* @return {T} The generated text node with the given text
*/
public text(text: string): T {
return this.jax.text(text);
}
/**
* @param {number} x The dimension to display
* @param {number=} n The number of digits to display
* @return {string} The dimension with the given number of digits (minus trailing zeros)
*/
public fixed(x: number, n: number = 1): string {
return this.jax.fixed(x * 1000, n);
}
} | the_stack |
import { FavoriteBodyCreate } from '../model/favoriteBodyCreate';
import { FavoriteEntry } from '../model/favoriteEntry';
import { FavoritePaging } from '../model/favoritePaging';
import { FavoriteSiteBodyCreate } from '../model/favoriteSiteBodyCreate';
import { FavoriteSiteEntry } from '../model/favoriteSiteEntry';
import { SiteEntry } from '../model/siteEntry';
import { SitePaging } from '../model/sitePaging';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
import { buildCollectionParam } from '../../../alfrescoApiClient';
/**
* Favorites service.
* @module FavoritesApi
*/
export class FavoritesApi extends BaseApi {
/**
* Create a favorite
*
* Favorite a **site**, **file**, or **folder** in the repository.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
**Note:** You can favorite more than one entity by
specifying a list of objects in the JSON body like this:
JSON
[
{
\"target\": {
\"file\": {
\"guid\": \"abcde-01234-....\"
}
}
},
{
\"target\": {
\"file\": {
\"guid\": \"abcde-09863-....\"
}
}
},
]
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param personId The identifier of a person.
* @param favoriteBodyCreate An object identifying the entity to be favorited.
The object consists of a single property which is an object with the name site, file, or folder.
The content of that object is the guid of the target entity.
For example, to favorite a file the following body would be used:
JSON
{
\"target\": {
\"file\": {
\"guid\": \"abcde-01234-....\"
}
}
}
* @param opts Optional parameters
* @param opts.include Returns additional information about favorites, the following optional fields can be requested:
* path (note, this only applies to files and folders)
* properties
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FavoriteEntry>
*/
createFavorite(personId: string, favoriteBodyCreate: FavoriteBodyCreate, opts?: any): Promise<FavoriteEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(favoriteBodyCreate, 'favoriteBodyCreate');
opts = opts || {};
const postBody = favoriteBodyCreate;
const pathParams = {
'personId': personId
};
const queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorites', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , FavoriteEntry);
}
/**
* Create a site favorite
*
* **Note:** this endpoint is deprecated as of Alfresco 4.2, and will be removed in the future.
Use /people/{personId}/favorites instead.
Create a site favorite for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
**Note:** You can favorite more than one site by
specifying a list of sites in the JSON body like this:
JSON
[
{
\"id\": \"test-site-1\"
},
{
\"id\": \"test-site-2\"
}
]
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param personId The identifier of a person.
* @param favoriteSiteBodyCreate The id of the site to favorite.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FavoriteSiteEntry>
*/
createSiteFavorite(personId: string, favoriteSiteBodyCreate: FavoriteSiteBodyCreate, opts?: any): Promise<FavoriteSiteEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(favoriteSiteBodyCreate, 'favoriteSiteBodyCreate');
opts = opts || {};
const postBody = favoriteSiteBodyCreate;
const pathParams = {
'personId': personId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorite-sites', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , FavoriteSiteEntry);
}
/**
* Delete a favorite
*
* Deletes **favoriteId** as a favorite of person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param favoriteId The identifier of a favorite.
* @return Promise<{}>
*/
deleteFavorite(personId: string, favoriteId: string): Promise<any> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(favoriteId, 'favoriteId');
const postBody: null = null;
const pathParams = {
'personId': personId, 'favoriteId': favoriteId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorites/{favoriteId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Delete a site favorite
*
* **Note:** this endpoint is deprecated as of Alfresco 4.2, and will be removed in the future.
Use /people/{personId}/favorites/{favoriteId} instead.
Deletes site **siteId** from the favorite site list of person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @return Promise<{}>
*/
deleteSiteFavorite(personId: string, siteId: string): Promise<any> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorite-sites/{siteId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Get a favorite
*
* Gets favorite **favoriteId** for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param favoriteId The identifier of a favorite.
* @param opts Optional parameters
* @param opts.include Returns additional information about favorites, the following optional fields can be requested:
* path (note, this only applies to files and folders)
* properties
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FavoriteEntry>
*/
getFavorite(personId: string, favoriteId: string, opts?: any): Promise<FavoriteEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(favoriteId, 'favoriteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId, 'favoriteId': favoriteId
};
const queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorites/{favoriteId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , FavoriteEntry);
}
/**
* Get a favorite site
*
* **Note:** this endpoint is deprecated as of Alfresco 4.2, and will be removed in the future.
Use /people/{personId}/favorites/{favoriteId} instead.
Gets information on favorite site **siteId** of person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteEntry>
*/
getFavoriteSite(personId: string, siteId: string, opts?: any): Promise<SiteEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorite-sites/{siteId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteEntry);
}
/**
* List favorite sites
*
* **Note:** this endpoint is deprecated as of Alfresco 4.2, and will be removed in the future.
Use /people/{personId}/favorites instead.
Gets a list of a person's favorite sites.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SitePaging>
*/
listFavoriteSitesForPerson(personId: string, opts?: any): Promise<SitePaging> {
throwIfNotDefined(personId, 'personId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorite-sites', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SitePaging);
}
/**
* List favorites
*
* Gets a list of favorites for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
The default sort order for the returned list of favorites is type ascending, createdAt descending.
You can override the default by using the **orderBy** parameter.
You can use any of the following fields to order the results:
* type
* createdAt
* title
You can use the **where** parameter to restrict the list in the response
to entries of a specific kind. The **where** parameter takes a value.
The value is a single predicate that can include one or more **EXISTS**
conditions. The **EXISTS** condition uses a single operand to limit the
list to include entries that include that one property. The property values are:
* target/file
* target/folder
* target/site
For example, the following **where** parameter restricts the returned list to the file favorites for a person:
SQL
(EXISTS(target/file))
You can specify more than one condition using **OR**. The predicate must be enclosed in parentheses.
For example, the following **where** parameter restricts the returned list to the file and folder favorites for a person:
SQL
(EXISTS(target/file) OR EXISTS(target/folder))
*
* @param personId The identifier of a person.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to
sort the list by one or more fields.
Each field has a default sort order, which is normally ascending order. Read the API method implementation notes
above to check if any fields used in this method have a descending default search order.
To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field.
* @param opts.where A string to restrict the returned objects by using a predicate.
* @param opts.include Returns additional information about favorites, the following optional fields can be requested:
* path (note, this only applies to files and folders)
* properties
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FavoritePaging>
*/
listFavorites(personId: string, opts?: any): Promise<FavoritePaging> {
throwIfNotDefined(personId, 'personId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'orderBy': buildCollectionParam(opts['orderBy'], 'csv'),
'where': opts['where'],
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/favorites', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , FavoritePaging);
}
} | the_stack |
import { expect } from 'chai';
import * as sinon from 'sinon';
import { ElementFactory } from '../../../utils';
import { global, noop } from '../../../../src/facade/lang';
import {
Component,
Directive,
HostBinding,
HostListener,
ViewChild,
ContentChild
} from '../../../../src/core/directives/decorators';
import {
_resolveChildrenFactory,
_getChildElements,
getControllerOnElement,
_getSelectorAndCtrlName,
_getSelector,
_getParentCheckNotifiers
} from '../../../../src/core/directives/query/children_resolver';
import { DirectiveCtrl } from '../../../../src/core/directives/constants';
import { Inject } from '../../../../src/core/di/decorators';
import { forwardRef } from '../../../../src/core/di/forward_ref';
describe( `directives/query/children_resolver`, () => {
describe( `#_resolveChildrenFactory`, ()=> {
let $element;
let ctrl;
let mockedCtrlInstance;
const sandbox = sinon.sandbox.create();
let multiRef;
beforeEach( ()=> {
$element = ElementFactory();
ctrl = {};
mockedCtrlInstance = {
iamHere: true
};
sandbox.stub( $element[ '0' ], 'querySelector' )
.returns( $element[ 0 ] );
sandbox.stub( $element[ '0' ], 'querySelectorAll' )
.returns( [ $element[ 0 ], $element[ 0 ], $element[ 0 ] ] );
//sinon.stub( $element, 'data' ).withArgs( '$mockedCtrlController' ).returns( mockedCtrlInstance );
sinon.stub( $element, 'controller' )
.withArgs( 'fooCmp' ).returns( mockedCtrlInstance )
.withArgs( 'fooChildCmp' ).returns( mockedCtrlInstance );
global.angular = {
element(DOMorString){
multiRef = [ $element, $element, $element ];
(multiRef as any).eq = function ( idx: number ) {
return this[ idx ];
};
return DOMorString.length > 1 ? multiRef : $element
}
} as any;
} );
afterEach( ()=> {
sandbox.restore();
} );
it( `should return just jqLite element if querying for string`, ()=> {
const viewChildResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmp', '.hello', 'view', true );
viewChildResolver();
expect( $element.controller.called ).to.equal( false );
expect( ctrl.oneCmp ).to.equal( $element );
} );
it( `should return just jqLite element collection if querying for string`, ()=> {
const viewChildrenResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmpList', '.yo-mama', 'view' );
viewChildrenResolver();
expect( $element.controller.called ).to.equal( false );
expect( ctrl.oneCmpList ).to.equal( multiRef );
} );
it( `should set view child instance on controller`, ()=> {
@Component({selector:'foo-cmp',template:'foo'})
class Foo{}
const viewChildResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmp', Foo, 'view', true );
viewChildResolver();
expect( $element.controller.calledWith('fooCmp') ).to.equal( true );
expect( ctrl ).to.deep.equal( { oneCmp: { iamHere: true } } );
} );
it( `should set view children instances on controller`, ()=> {
@Component({selector:'foo-cmp',template:'foo'})
class Foo{}
const viewChildrenResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmpList', Foo, 'view' );
viewChildrenResolver();
expect( $element.controller.calledWith('fooCmp') ).to.equal( true );
expect( ctrl.oneCmpList ).to.deep.equal( [{ iamHere: true },{ iamHere: true },{ iamHere: true }] );
} );
it( `should set content child instance on controller`, ()=> {
@Component({selector:'foo-child-cmp',template:'foo'})
class Foo{}
const contentChildResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmp', Foo, 'content', true );
contentChildResolver();
expect( $element.controller.calledWith('fooChildCmp') ).to.equal( true );
expect( ctrl ).to.deep.equal( { oneCmp: { iamHere: true } } );
} );
it( `should set content children instances on controller`, ()=> {
@Component({selector:'foo-child-cmp',template:'foo'})
class Foo{}
const contentChildrenResolver = _resolveChildrenFactory( $element, ctrl, 'oneCmpList', Foo, 'content' );
contentChildrenResolver();
expect( $element.controller.calledWith('fooChildCmp') ).to.equal( true );
expect( ctrl.oneCmpList ).to.deep.equal( [{ iamHere: true },{ iamHere: true },{ iamHere: true }] );
//contentChildrenResolver();
//expect( $element.controller.calledWith('fooChildCmp') ).to.equal( true );
//expect( ctrl ).to.deep.equal( { oneCmpList: { iamHere: true } } );
} );
} );
describe( `#_getChildElements`, ()=> {
let $element;
const sandbox = sinon.sandbox.create();
beforeEach( ()=> {
$element = ElementFactory();
sandbox.stub( $element[ '0' ], 'querySelector' );
sandbox.stub( $element[ '0' ], 'querySelectorAll' );
global.angular = {
element(DOMorString){ return ElementFactory() }
} as any;
} );
afterEach( ()=> {
sandbox.restore();
} );
it( `should query for first view child if firstOnly and type==view`, ()=> {
const actual = _getChildElements( $element, 'view-child-item', 'view', true );
expect( $element[ 0 ].querySelector.called ).to.equal( true );
expect( $element[ 0 ].querySelector.calledWith( ':not(ng-transclude):not([ng-transclude]) > view-child-item' ) )
.to
.equal( true );
} );
it( `should query for all view children if firstOnly and type==view`, ()=> {
const actual = _getChildElements( $element, 'view-child-item', 'view' );
expect( $element[ 0 ].querySelectorAll.called ).to.equal( true );
expect( $element[ 0 ].querySelectorAll.calledWith( ':not(ng-transclude):not([ng-transclude]) > view-child-item' ) )
.to
.equal( true );
} );
it( `should query for first content child if firstOnly and type==content`, ()=> {
const actual = _getChildElements( $element, 'content-child-item', 'content', true );
expect( $element[ 0 ].querySelector.called ).to.equal( true );
expect( $element[ 0 ].querySelector.calledWith(
'ng-transclude content-child-item, [ng-transclude] content-child-item' ) )
.to
.equal( true );
} );
it( `should query for all content children if firstOnly and type==content`, ()=> {
const actual = _getChildElements( $element, 'content-child-item', 'content' );
expect( $element[ 0 ].querySelectorAll.called ).to.equal( true );
expect( $element[ 0 ].querySelectorAll.calledWith(
'ng-transclude content-child-item, [ng-transclude] content-child-item' ) )
.to
.equal( true );
} );
} );
describe( `#getControllerOnElement`, ()=> {
let $element;
beforeEach( ()=> {
$element = ElementFactory()
} );
it( `should return demanded ctrl instance on element`, ()=> {
const mockedCtrlInstance = {};
//sinon.stub( $element, 'data' ).withArgs( '$mockedCtrlController' ).returns( mockedCtrlInstance );
sinon.stub( $element, 'controller' ).withArgs( 'mockedCtrl' ).returns( mockedCtrlInstance );
expect( getControllerOnElement( $element, 'mockedCtrl' ) ).to.equal( mockedCtrlInstance );
} );
it( `should return null if demanded ctrl doesn't exist on provided element`, ()=> {
//sinon.stub( $element, 'data' ).withArgs( '$mockedCtrlController' ).returns( mockedCtrlInstance );
sinon.stub( $element, 'controller' ).withArgs( 'noneCtrl' ).returns( null );
expect( getControllerOnElement( $element, 'noneCtrl' ) ).to.equal( null )
} );
} );
describe( `#_getSelectorAndCtrlName`, ()=> {
it( `should return map containing CSS selector and injectable name string`, ()=> {
@Directive( { selector: '[hello-world]' } )
class HelloDirective {
}
@Component( { selector: 'my-cmp', template: 'hello' } )
class HelloComponent {
}
expect( _getSelectorAndCtrlName( HelloDirective ) ).to.deep.equal( {
selector: '[hello-world]',
childCtrlName: 'helloWorld'
} );
expect( _getSelectorAndCtrlName( HelloComponent ) ).to.deep.equal( {
selector: 'my-cmp',
childCtrlName: 'myCmp'
} );
} );
} );
describe( `#_getSelector`, ()=> {
it( `should get selector metadata from component/directive decorated class`, ()=> {
@Directive({selector:'[hello-world]'})
class HelloDirective{}
@Component({selector:'my-cmp',template:'hello'})
class HelloComponent{}
expect(_getSelector(HelloDirective)).to.equal('[hello-world]');
expect( _getSelector( HelloComponent ) ).to.equal( 'my-cmp' );
} );
it( `should return same value when input is string`, ()=> {
expect( _getSelector( 'hey-foo' ) ).to.equal( 'hey-foo' );
} );
} );
describe( `#_getParentCheckNotifiers`, ()=> {
it( `should return empty array with noop if no queries found on parent`, ()=> {
@Component( { selector: 'ctrl', template: 'this is it' } )
class Ctrl {
}
const actual = _getParentCheckNotifiers( new Ctrl() as DirectiveCtrl, [ {} ] );
const expected = [noop];
expect( actual ).to.deep.equal( expected );
} );
it( `should return empty array with noop if no property decorators exist on parent`, ()=> {
@Component( { selector: 'foo', template: 'hello' } )
class Foo {
}
@Component( { selector: 'ctrl', template: 'this is it' } )
class Ctrl {
}
const requiredCtrl = [ new Foo() ];
const ctrl = new Ctrl() as DirectiveCtrl;
const actual = _getParentCheckNotifiers( ctrl, requiredCtrl );
const expected = [ noop ];
expect( actual ).to.deep.equal( expected );
} );
it( `should return skip non @Query parameter decorators`, ()=> {
@Component( { selector: 'foo', template: 'hello' } )
class Foo {
@HostBinding('attr.aria-disabled') isDisabled: boolean;
@HostListener('blur') onBlur(){}
}
@Component( { selector: 'ctrl', template: 'this is it' } )
class Ctrl {
}
const requiredCtrl = [ new Foo() ];
const ctrl = new Ctrl() as DirectiveCtrl;
const actual = _getParentCheckNotifiers( ctrl, requiredCtrl );
const expected = [ noop ];
expect( actual ).to.deep.equal( expected );
} );
it( `should return notifier functions if parent @Queryies child and child @Injects parent`, ()=> {
@Component( { selector: 'ctrl', template: 'this is it' } )
class Ctrl {
constructor(
@Inject(forwardRef(()=>Foo)) private foo
){}
}
@Component( { selector: 'ctrl-content', template: 'this is it' } )
class CtrlContent {
constructor(
@Inject(forwardRef(()=>Foo)) private foo
){}
}
@Component( { selector: 'foo', template: 'hello' } )
class Foo {
@ViewChild(Ctrl) _ctrl: Ctrl;
@ContentChild(CtrlContent) _ctrlContent: CtrlContent;
@HostListener('blur') onBlur(){}
ngAfterViewInit(){}
ngAfterViewChecked(){}
ngAfterContentChecked(){}
ngAfterContentInit(){}
_ngOnChildrenChanged(){}
}
let requiredCtrl = [ new Foo() ];
let ctrlInView = new Ctrl(new Foo());
let ctrlInContent = new CtrlContent(new Foo());
const spyParentChildrenChanged = sinon.spy(requiredCtrl[0],'_ngOnChildrenChanged');
const viewChildActual = _getParentCheckNotifiers( ctrlInView as any, requiredCtrl );
const contentChildActual = _getParentCheckNotifiers( ctrlInContent as any, requiredCtrl );
expect( viewChildActual.length ).to.equal( 1 );
expect( viewChildActual[0] ).to.not.equal( noop );
expect( contentChildActual.length ).to.equal( 1 );
expect( contentChildActual[0] ).to.not.equal( noop );
viewChildActual[ 0 ]();
expect( spyParentChildrenChanged.calledOnce ).to.equal( true );
contentChildActual[ 0 ]();
expect( spyParentChildrenChanged.calledTwice ).to.equal( true );
} );
} );
} ); | the_stack |
import { mXparserConstants } from '../mXparserConstants';
/**
* Parser symbols - mXparserConstants tokens definition.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
*
* @version 4.2.0
* @class
*/
export class ParserSymbol {
public static DIGIT: string = "[0-9]";
public static DIGIT_B1: string = "1";
public static DIGIT_B2: string = "[01]";
public static DIGIT_B3: string = "[0-2]";
public static DIGIT_B4: string = "[0-3]";
public static DIGIT_B5: string = "[0-4]";
public static DIGIT_B6: string = "[0-5]";
public static DIGIT_B7: string = "[0-6]";
public static DIGIT_B8: string = "[0-7]";
public static DIGIT_B9: string = "[0-8]";
public static DIGIT_B10: string = "[0-9]";
public static DIGIT_B11: string = "[0-9aA]";
public static DIGIT_B12: string = "[0-9a-bA-B]";
public static DIGIT_B13: string = "[0-9a-cA-C]";
public static DIGIT_B14: string = "[0-9a-dA-D]";
public static DIGIT_B15: string = "[0-9a-eA-E]";
public static DIGIT_B16: string = "[0-9a-fA-F]";
public static DIGIT_B17: string = "[0-9a-gA-G]";
public static DIGIT_B18: string = "[0-9a-hA-H]";
public static DIGIT_B19: string = "[0-9a-iA-I]";
public static DIGIT_B20: string = "[0-9a-jA-J]";
public static DIGIT_B21: string = "[0-9a-kA-K]";
public static DIGIT_B22: string = "[0-9a-lA-L]";
public static DIGIT_B23: string = "[0-9a-mA-M]";
public static DIGIT_B24: string = "[0-9a-nA-N]";
public static DIGIT_B25: string = "[0-9a-oA-O]";
public static DIGIT_B26: string = "[0-9a-pA-P]";
public static DIGIT_B27: string = "[0-9a-qA-Q]";
public static DIGIT_B28: string = "[0-9a-rA-R]";
public static DIGIT_B29: string = "[0-9a-sA-S]";
public static DIGIT_B30: string = "[0-9a-tA-T]";
public static DIGIT_B31: string = "[0-9a-uA-U]";
public static DIGIT_B32: string = "[0-9a-vA-V]";
public static DIGIT_B33: string = "[0-9a-wA-W]";
public static DIGIT_B34: string = "[0-9a-xA-X]";
public static DIGIT_B35: string = "[0-9a-yA-Y]";
public static DIGIT_B36: string = "[0-9a-zA-Z]";
public static INTEGER: string; public static INTEGER_$LI$(): string { if (ParserSymbol.INTEGER == null) { ParserSymbol.INTEGER = ParserSymbol.DIGIT + "(" + ParserSymbol.DIGIT + ")*"; } return ParserSymbol.INTEGER; }
public static DEC_FRACT: string; public static DEC_FRACT_$LI$(): string { if (ParserSymbol.DEC_FRACT == null) { ParserSymbol.DEC_FRACT = "(" + ParserSymbol.INTEGER_$LI$() + ")?\\." + ParserSymbol.INTEGER_$LI$(); } return ParserSymbol.DEC_FRACT; }
public static DEC_FRACT_OR_INT: string; public static DEC_FRACT_OR_INT_$LI$(): string { if (ParserSymbol.DEC_FRACT_OR_INT == null) { ParserSymbol.DEC_FRACT_OR_INT = "(" + ParserSymbol.DEC_FRACT_$LI$() + "|" + ParserSymbol.INTEGER_$LI$() + ")"; } return ParserSymbol.DEC_FRACT_OR_INT; }
public static DECIMAL_REG_EXP: string; public static DECIMAL_REG_EXP_$LI$(): string { if (ParserSymbol.DECIMAL_REG_EXP == null) { ParserSymbol.DECIMAL_REG_EXP = "[+-]?" + ParserSymbol.DEC_FRACT_OR_INT_$LI$() + "([eE][+-]?" + ParserSymbol.INTEGER_$LI$() + ")?"; } return ParserSymbol.DECIMAL_REG_EXP; }
public static DECIMAL_SCIENTIFIC_REG_EXP: string; public static DECIMAL_SCIENTIFIC_REG_EXP_$LI$(): string { if (ParserSymbol.DECIMAL_SCIENTIFIC_REG_EXP == null) { ParserSymbol.DECIMAL_SCIENTIFIC_REG_EXP = "[+-]?" + ParserSymbol.DEC_FRACT_OR_INT_$LI$() + "([eE][+-]?" + ParserSymbol.INTEGER_$LI$() + ")"; } return ParserSymbol.DECIMAL_SCIENTIFIC_REG_EXP; }
public static BASE1_REG_EXP: string; public static BASE1_REG_EXP_$LI$(): string { if (ParserSymbol.BASE1_REG_EXP == null) { ParserSymbol.BASE1_REG_EXP = "[+-]?[bB]1\\.(" + ParserSymbol.DIGIT_B1 + ")*"; } return ParserSymbol.BASE1_REG_EXP; }
public static BASE2_REG_EXP: string; public static BASE2_REG_EXP_$LI$(): string { if (ParserSymbol.BASE2_REG_EXP == null) { ParserSymbol.BASE2_REG_EXP = "[+-]?[bB][2]?\\." + ParserSymbol.DIGIT_B2 + "(" + ParserSymbol.DIGIT_B2 + ")*"; } return ParserSymbol.BASE2_REG_EXP; }
public static BASE3_REG_EXP: string; public static BASE3_REG_EXP_$LI$(): string { if (ParserSymbol.BASE3_REG_EXP == null) { ParserSymbol.BASE3_REG_EXP = "[+-]?[bB]3\\." + ParserSymbol.DIGIT_B3 + "(" + ParserSymbol.DIGIT_B3 + ")*"; } return ParserSymbol.BASE3_REG_EXP; }
public static BASE4_REG_EXP: string; public static BASE4_REG_EXP_$LI$(): string { if (ParserSymbol.BASE4_REG_EXP == null) { ParserSymbol.BASE4_REG_EXP = "[+-]?[bB]4\\." + ParserSymbol.DIGIT_B4 + "(" + ParserSymbol.DIGIT_B4 + ")*"; } return ParserSymbol.BASE4_REG_EXP; }
public static BASE5_REG_EXP: string; public static BASE5_REG_EXP_$LI$(): string { if (ParserSymbol.BASE5_REG_EXP == null) { ParserSymbol.BASE5_REG_EXP = "[+-]?[bB]5\\." + ParserSymbol.DIGIT_B5 + "(" + ParserSymbol.DIGIT_B5 + ")*"; } return ParserSymbol.BASE5_REG_EXP; }
public static BASE6_REG_EXP: string; public static BASE6_REG_EXP_$LI$(): string { if (ParserSymbol.BASE6_REG_EXP == null) { ParserSymbol.BASE6_REG_EXP = "[+-]?[bB]6\\." + ParserSymbol.DIGIT_B6 + "(" + ParserSymbol.DIGIT_B6 + ")*"; } return ParserSymbol.BASE6_REG_EXP; }
public static BASE7_REG_EXP: string; public static BASE7_REG_EXP_$LI$(): string { if (ParserSymbol.BASE7_REG_EXP == null) { ParserSymbol.BASE7_REG_EXP = "[+-]?[bB]7\\." + ParserSymbol.DIGIT_B7 + "(" + ParserSymbol.DIGIT_B7 + ")*"; } return ParserSymbol.BASE7_REG_EXP; }
public static BASE8_REG_EXP: string; public static BASE8_REG_EXP_$LI$(): string { if (ParserSymbol.BASE8_REG_EXP == null) { ParserSymbol.BASE8_REG_EXP = "[+-]?([bB]8|[oO])\\." + ParserSymbol.DIGIT_B8 + "(" + ParserSymbol.DIGIT_B8 + ")*"; } return ParserSymbol.BASE8_REG_EXP; }
public static BASE9_REG_EXP: string; public static BASE9_REG_EXP_$LI$(): string { if (ParserSymbol.BASE9_REG_EXP == null) { ParserSymbol.BASE9_REG_EXP = "[+-]?[bB]9\\." + ParserSymbol.DIGIT_B9 + "(" + ParserSymbol.DIGIT_B9 + ")*"; } return ParserSymbol.BASE9_REG_EXP; }
public static BASE10_REG_EXP: string; public static BASE10_REG_EXP_$LI$(): string { if (ParserSymbol.BASE10_REG_EXP == null) { ParserSymbol.BASE10_REG_EXP = "[+-]?[bB]10\\." + ParserSymbol.DIGIT_B10 + "(" + ParserSymbol.DIGIT_B10 + ")*"; } return ParserSymbol.BASE10_REG_EXP; }
public static BASE11_REG_EXP: string; public static BASE11_REG_EXP_$LI$(): string { if (ParserSymbol.BASE11_REG_EXP == null) { ParserSymbol.BASE11_REG_EXP = "[+-]?[bB]11\\." + ParserSymbol.DIGIT_B11 + "(" + ParserSymbol.DIGIT_B11 + ")*"; } return ParserSymbol.BASE11_REG_EXP; }
public static BASE12_REG_EXP: string; public static BASE12_REG_EXP_$LI$(): string { if (ParserSymbol.BASE12_REG_EXP == null) { ParserSymbol.BASE12_REG_EXP = "[+-]?[bB]12\\." + ParserSymbol.DIGIT_B12 + "(" + ParserSymbol.DIGIT_B12 + ")*"; } return ParserSymbol.BASE12_REG_EXP; }
public static BASE13_REG_EXP: string; public static BASE13_REG_EXP_$LI$(): string { if (ParserSymbol.BASE13_REG_EXP == null) { ParserSymbol.BASE13_REG_EXP = "[+-]?[bB]13\\." + ParserSymbol.DIGIT_B13 + "(" + ParserSymbol.DIGIT_B13 + ")*"; } return ParserSymbol.BASE13_REG_EXP; }
public static BASE14_REG_EXP: string; public static BASE14_REG_EXP_$LI$(): string { if (ParserSymbol.BASE14_REG_EXP == null) { ParserSymbol.BASE14_REG_EXP = "[+-]?[bB]14\\." + ParserSymbol.DIGIT_B14 + "(" + ParserSymbol.DIGIT_B14 + ")*"; } return ParserSymbol.BASE14_REG_EXP; }
public static BASE15_REG_EXP: string; public static BASE15_REG_EXP_$LI$(): string { if (ParserSymbol.BASE15_REG_EXP == null) { ParserSymbol.BASE15_REG_EXP = "[+-]?[bB]15\\." + ParserSymbol.DIGIT_B15 + "(" + ParserSymbol.DIGIT_B15 + ")*"; } return ParserSymbol.BASE15_REG_EXP; }
public static BASE16_REG_EXP: string; public static BASE16_REG_EXP_$LI$(): string { if (ParserSymbol.BASE16_REG_EXP == null) { ParserSymbol.BASE16_REG_EXP = "[+-]?([bB]16|[hH])\\." + ParserSymbol.DIGIT_B16 + "(" + ParserSymbol.DIGIT_B16 + ")*"; } return ParserSymbol.BASE16_REG_EXP; }
public static BASE17_REG_EXP: string; public static BASE17_REG_EXP_$LI$(): string { if (ParserSymbol.BASE17_REG_EXP == null) { ParserSymbol.BASE17_REG_EXP = "[+-]?[bB]17\\." + ParserSymbol.DIGIT_B17 + "(" + ParserSymbol.DIGIT_B17 + ")*"; } return ParserSymbol.BASE17_REG_EXP; }
public static BASE18_REG_EXP: string; public static BASE18_REG_EXP_$LI$(): string { if (ParserSymbol.BASE18_REG_EXP == null) { ParserSymbol.BASE18_REG_EXP = "[+-]?[bB]18\\." + ParserSymbol.DIGIT_B18 + "(" + ParserSymbol.DIGIT_B18 + ")*"; } return ParserSymbol.BASE18_REG_EXP; }
public static BASE19_REG_EXP: string; public static BASE19_REG_EXP_$LI$(): string { if (ParserSymbol.BASE19_REG_EXP == null) { ParserSymbol.BASE19_REG_EXP = "[+-]?[bB]19\\." + ParserSymbol.DIGIT_B19 + "(" + ParserSymbol.DIGIT_B19 + ")*"; } return ParserSymbol.BASE19_REG_EXP; }
public static BASE20_REG_EXP: string; public static BASE20_REG_EXP_$LI$(): string { if (ParserSymbol.BASE20_REG_EXP == null) { ParserSymbol.BASE20_REG_EXP = "[+-]?[bB]20\\." + ParserSymbol.DIGIT_B20 + "(" + ParserSymbol.DIGIT_B20 + ")*"; } return ParserSymbol.BASE20_REG_EXP; }
public static BASE21_REG_EXP: string; public static BASE21_REG_EXP_$LI$(): string { if (ParserSymbol.BASE21_REG_EXP == null) { ParserSymbol.BASE21_REG_EXP = "[+-]?[bB]21\\." + ParserSymbol.DIGIT_B21 + "(" + ParserSymbol.DIGIT_B21 + ")*"; } return ParserSymbol.BASE21_REG_EXP; }
public static BASE22_REG_EXP: string; public static BASE22_REG_EXP_$LI$(): string { if (ParserSymbol.BASE22_REG_EXP == null) { ParserSymbol.BASE22_REG_EXP = "[+-]?[bB]22\\." + ParserSymbol.DIGIT_B22 + "(" + ParserSymbol.DIGIT_B22 + ")*"; } return ParserSymbol.BASE22_REG_EXP; }
public static BASE23_REG_EXP: string; public static BASE23_REG_EXP_$LI$(): string { if (ParserSymbol.BASE23_REG_EXP == null) { ParserSymbol.BASE23_REG_EXP = "[+-]?[bB]23\\." + ParserSymbol.DIGIT_B23 + "(" + ParserSymbol.DIGIT_B23 + ")*"; } return ParserSymbol.BASE23_REG_EXP; }
public static BASE24_REG_EXP: string; public static BASE24_REG_EXP_$LI$(): string { if (ParserSymbol.BASE24_REG_EXP == null) { ParserSymbol.BASE24_REG_EXP = "[+-]?[bB]24\\." + ParserSymbol.DIGIT_B24 + "(" + ParserSymbol.DIGIT_B24 + ")*"; } return ParserSymbol.BASE24_REG_EXP; }
public static BASE25_REG_EXP: string; public static BASE25_REG_EXP_$LI$(): string { if (ParserSymbol.BASE25_REG_EXP == null) { ParserSymbol.BASE25_REG_EXP = "[+-]?[bB]25\\." + ParserSymbol.DIGIT_B25 + "(" + ParserSymbol.DIGIT_B25 + ")*"; } return ParserSymbol.BASE25_REG_EXP; }
public static BASE26_REG_EXP: string; public static BASE26_REG_EXP_$LI$(): string { if (ParserSymbol.BASE26_REG_EXP == null) { ParserSymbol.BASE26_REG_EXP = "[+-]?[bB]26\\." + ParserSymbol.DIGIT_B26 + "(" + ParserSymbol.DIGIT_B26 + ")*"; } return ParserSymbol.BASE26_REG_EXP; }
public static BASE27_REG_EXP: string; public static BASE27_REG_EXP_$LI$(): string { if (ParserSymbol.BASE27_REG_EXP == null) { ParserSymbol.BASE27_REG_EXP = "[+-]?[bB]27\\." + ParserSymbol.DIGIT_B27 + "(" + ParserSymbol.DIGIT_B27 + ")*"; } return ParserSymbol.BASE27_REG_EXP; }
public static BASE28_REG_EXP: string; public static BASE28_REG_EXP_$LI$(): string { if (ParserSymbol.BASE28_REG_EXP == null) { ParserSymbol.BASE28_REG_EXP = "[+-]?[bB]28\\." + ParserSymbol.DIGIT_B28 + "(" + ParserSymbol.DIGIT_B28 + ")*"; } return ParserSymbol.BASE28_REG_EXP; }
public static BASE29_REG_EXP: string; public static BASE29_REG_EXP_$LI$(): string { if (ParserSymbol.BASE29_REG_EXP == null) { ParserSymbol.BASE29_REG_EXP = "[+-]?[bB]29\\." + ParserSymbol.DIGIT_B29 + "(" + ParserSymbol.DIGIT_B29 + ")*"; } return ParserSymbol.BASE29_REG_EXP; }
public static BASE30_REG_EXP: string; public static BASE30_REG_EXP_$LI$(): string { if (ParserSymbol.BASE30_REG_EXP == null) { ParserSymbol.BASE30_REG_EXP = "[+-]?[bB]30\\." + ParserSymbol.DIGIT_B30 + "(" + ParserSymbol.DIGIT_B30 + ")*"; } return ParserSymbol.BASE30_REG_EXP; }
public static BASE31_REG_EXP: string; public static BASE31_REG_EXP_$LI$(): string { if (ParserSymbol.BASE31_REG_EXP == null) { ParserSymbol.BASE31_REG_EXP = "[+-]?[bB]31\\." + ParserSymbol.DIGIT_B31 + "(" + ParserSymbol.DIGIT_B31 + ")*"; } return ParserSymbol.BASE31_REG_EXP; }
public static BASE32_REG_EXP: string; public static BASE32_REG_EXP_$LI$(): string { if (ParserSymbol.BASE32_REG_EXP == null) { ParserSymbol.BASE32_REG_EXP = "[+-]?[bB]32\\." + ParserSymbol.DIGIT_B32 + "(" + ParserSymbol.DIGIT_B32 + ")*"; } return ParserSymbol.BASE32_REG_EXP; }
public static BASE33_REG_EXP: string; public static BASE33_REG_EXP_$LI$(): string { if (ParserSymbol.BASE33_REG_EXP == null) { ParserSymbol.BASE33_REG_EXP = "[+-]?[bB]33\\." + ParserSymbol.DIGIT_B33 + "(" + ParserSymbol.DIGIT_B33 + ")*"; } return ParserSymbol.BASE33_REG_EXP; }
public static BASE34_REG_EXP: string; public static BASE34_REG_EXP_$LI$(): string { if (ParserSymbol.BASE34_REG_EXP == null) { ParserSymbol.BASE34_REG_EXP = "[+-]?[bB]34\\." + ParserSymbol.DIGIT_B34 + "(" + ParserSymbol.DIGIT_B34 + ")*"; } return ParserSymbol.BASE34_REG_EXP; }
public static BASE35_REG_EXP: string; public static BASE35_REG_EXP_$LI$(): string { if (ParserSymbol.BASE35_REG_EXP == null) { ParserSymbol.BASE35_REG_EXP = "[+-]?[bB]35\\." + ParserSymbol.DIGIT_B35 + "(" + ParserSymbol.DIGIT_B35 + ")*"; } return ParserSymbol.BASE35_REG_EXP; }
public static BASE36_REG_EXP: string; public static BASE36_REG_EXP_$LI$(): string { if (ParserSymbol.BASE36_REG_EXP == null) { ParserSymbol.BASE36_REG_EXP = "[+-]?[bB]36\\." + ParserSymbol.DIGIT_B36 + "(" + ParserSymbol.DIGIT_B36 + ")*"; } return ParserSymbol.BASE36_REG_EXP; }
public static FRACTION: string; public static FRACTION_$LI$(): string { if (ParserSymbol.FRACTION == null) { ParserSymbol.FRACTION = "(" + ParserSymbol.INTEGER_$LI$() + "\\_)?" + ParserSymbol.INTEGER_$LI$() + "\\_" + ParserSymbol.INTEGER_$LI$(); } return ParserSymbol.FRACTION; }
public static nameOnlyTokenRegExp: string = "([a-zA-Z_])+([a-zA-Z0-9_])*";
public static unitOnlyTokenRegExp: string; public static unitOnlyTokenRegExp_$LI$(): string { if (ParserSymbol.unitOnlyTokenRegExp == null) { ParserSymbol.unitOnlyTokenRegExp = "\\[" + ParserSymbol.nameOnlyTokenRegExp + "\\]"; } return ParserSymbol.unitOnlyTokenRegExp; }
public static nameOnlyTokenOptBracketsRegExp: string; public static nameOnlyTokenOptBracketsRegExp_$LI$(): string { if (ParserSymbol.nameOnlyTokenOptBracketsRegExp == null) { ParserSymbol.nameOnlyTokenOptBracketsRegExp = "(" + ParserSymbol.nameOnlyTokenRegExp + "|" + ParserSymbol.unitOnlyTokenRegExp_$LI$() + ")"; } return ParserSymbol.nameOnlyTokenOptBracketsRegExp; }
public static nameTokenRegExp: string; public static nameTokenRegExp_$LI$(): string { if (ParserSymbol.nameTokenRegExp == null) { ParserSymbol.nameTokenRegExp = "(\\s)*" + ParserSymbol.nameOnlyTokenRegExp + "(\\s)*"; } return ParserSymbol.nameTokenRegExp; }
public static nameTokenOptBracketsRegExp: string; public static nameTokenOptBracketsRegExp_$LI$(): string { if (ParserSymbol.nameTokenOptBracketsRegExp == null) { ParserSymbol.nameTokenOptBracketsRegExp = "(\\s)*" + ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$() + "(\\s)*"; } return ParserSymbol.nameTokenOptBracketsRegExp; }
public static paramsTokenRegeExp: string; public static paramsTokenRegeExp_$LI$(): string { if (ParserSymbol.paramsTokenRegeExp == null) { ParserSymbol.paramsTokenRegeExp = "(\\s)*\\((" + ParserSymbol.nameTokenRegExp_$LI$() + ",(\\s)*)*" + ParserSymbol.nameTokenRegExp_$LI$() + "\\)(\\s)*"; } return ParserSymbol.paramsTokenRegeExp; }
public static constArgDefStrRegExp: string; public static constArgDefStrRegExp_$LI$(): string { if (ParserSymbol.constArgDefStrRegExp == null) { ParserSymbol.constArgDefStrRegExp = ParserSymbol.nameTokenRegExp_$LI$() + "=(\\s)*(.)+(\\s)*"; } return ParserSymbol.constArgDefStrRegExp; }
public static constUnitgDefStrRegExp: string; public static constUnitgDefStrRegExp_$LI$(): string { if (ParserSymbol.constUnitgDefStrRegExp == null) { ParserSymbol.constUnitgDefStrRegExp = ParserSymbol.nameTokenOptBracketsRegExp_$LI$() + "=(\\s)*(.)+(\\s)*"; } return ParserSymbol.constUnitgDefStrRegExp; }
public static functionDefStrRegExp: string; public static functionDefStrRegExp_$LI$(): string { if (ParserSymbol.functionDefStrRegExp == null) { ParserSymbol.functionDefStrRegExp = ParserSymbol.nameTokenRegExp_$LI$() + ParserSymbol.paramsTokenRegeExp_$LI$() + "=(\\s)*(.)+(\\s)*"; } return ParserSymbol.functionDefStrRegExp; }
public static function1ArgDefStrRegExp: string; public static function1ArgDefStrRegExp_$LI$(): string { if (ParserSymbol.function1ArgDefStrRegExp == null) { ParserSymbol.function1ArgDefStrRegExp = ParserSymbol.nameTokenRegExp_$LI$() + "(\\s)*\\(" + ParserSymbol.nameTokenRegExp_$LI$() + "(\\s)*\\)(\\s)*=(\\s)*(.)+(\\s)*"; } return ParserSymbol.function1ArgDefStrRegExp; }
public static functionVariadicDefStrRegExp: string; public static functionVariadicDefStrRegExp_$LI$(): string { if (ParserSymbol.functionVariadicDefStrRegExp == null) { ParserSymbol.functionVariadicDefStrRegExp = ParserSymbol.nameTokenRegExp_$LI$() + "(\\s)*\\((\\s)*\\.\\.\\.(\\s)*\\)(\\s)*=(\\s)*(.)+(\\s)*"; } return ParserSymbol.functionVariadicDefStrRegExp; }
public static TYPE_ID: number = 20;
public static TYPE_DESC: string = "Parser Symbol";
public static LEFT_PARENTHESES_ID: number = 1;
public static RIGHT_PARENTHESES_ID: number = 2;
public static COMMA_ID: number = 3;
public static BLANK_ID: number = 4;
public static NUMBER_ID: number = 1;
public static NUMBER_TYPE_ID: number = 0;
public static LEFT_PARENTHESES_STR: string = "(";
public static RIGHT_PARENTHESES_STR: string = ")";
public static COMMA_STR: string = ",";
public static SEMI_STR: string = ";";
public static BLANK_STR: string = " ";
public static NUMBER_STR: string = "_num_";
public static LEFT_PARENTHESES_SYN: string = "( ... )";
public static RIGHT_PARENTHESES_SYN: string = "( ... )";
public static COMMA_SYN: string = "(a1, ... ,an)";
public static SEMI_SYN: string = "(a1; ... ;an)";
public static BLANK_SYN: string = " ";
public static NUMBER_SYN: string = "Integer (since v.1.0): 1, -2; Decimal (since v.1.0): 0.2, -0.3, 1.2; Leading zero (since v.4.1): 001, -002.1; Scientific notation (since v.4.2): 1.2e-10, 1.2e+10, 2.3e10; No leading zero (since v.4.2): .2, -.212; Fractions (since v.4.2): 1_2, 2_1_3, 14_3; Other systems (since v.4.1): b1.111, b2.1001, b3.12021, b16.af12, h.af1, b.1001, o.0127";
public static LEFT_PARENTHESES_DESC: string = "Left parentheses";
public static RIGHT_PARENTHESES_DESC: string = "Right parentheses";
public static COMMA_DESC: string = "Comma (function parameters)";
public static SEMI_DESC: string = "Semicolon (function parameters)";
public static BLANK_DESC: string = "Blank (whitespace) character";
public static NUMBER_DESC: string = "Decimal number";
public static NUMBER_REG_DESC: string = "Regullar expression for decimal numbers";
public static LEFT_PARENTHESES_SINCE: string; public static LEFT_PARENTHESES_SINCE_$LI$(): string { if (ParserSymbol.LEFT_PARENTHESES_SINCE == null) { ParserSymbol.LEFT_PARENTHESES_SINCE = mXparserConstants.NAMEv10; } return ParserSymbol.LEFT_PARENTHESES_SINCE; }
public static RIGHT_PARENTHESES_SINCE: string; public static RIGHT_PARENTHESES_SINCE_$LI$(): string { if (ParserSymbol.RIGHT_PARENTHESES_SINCE == null) { ParserSymbol.RIGHT_PARENTHESES_SINCE = mXparserConstants.NAMEv10; } return ParserSymbol.RIGHT_PARENTHESES_SINCE; }
public static COMMA_SINCE: string; public static COMMA_SINCE_$LI$(): string { if (ParserSymbol.COMMA_SINCE == null) { ParserSymbol.COMMA_SINCE = mXparserConstants.NAMEv10; } return ParserSymbol.COMMA_SINCE; }
public static SEMI_SINCE: string; public static SEMI_SINCE_$LI$(): string { if (ParserSymbol.SEMI_SINCE == null) { ParserSymbol.SEMI_SINCE = mXparserConstants.NAMEv10; } return ParserSymbol.SEMI_SINCE; }
public static BLANK_SINCE: string; public static BLANK_SINCE_$LI$(): string { if (ParserSymbol.BLANK_SINCE == null) { ParserSymbol.BLANK_SINCE = mXparserConstants.NAMEv42; } return ParserSymbol.BLANK_SINCE; }
public static NUMBER_SINCE: string; public static NUMBER_SINCE_$LI$(): string { if (ParserSymbol.NUMBER_SINCE == null) { ParserSymbol.NUMBER_SINCE = mXparserConstants.NAMEv10; } return ParserSymbol.NUMBER_SINCE; }
}
ParserSymbol["__class"] = "org.mariuszgromada.math.mxparser.parsertokens.ParserSymbol"; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.